text:
// Copyright (C) 2001-2003
// William E. Kempf
//
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear
// in supporting documentation.  William E. Kempf makes no representations
// about the suitability of this software for any purpose.
// It is provided "as is" without express or implied warranty.
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/interprocess for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_INTERPROCESS_CONDITION_TEST_TEMPLATE_HPP
#define BOOST_INTERPROCESS_CONDITION_TEST_TEMPLATE_HPP

#include <boost/interprocess/detail/config_begin.hpp>
#include <boost/interprocess/detail/workaround.hpp>
#include "boost_interprocess_check.hpp"
#include <boost/thread/detail/config.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/version.hpp>
#include <iostream>

namespace boost{
namespace interprocess{
namespace test {

boost::posix_time::ptime ptime_delay(int secs)
{
   return   microsec_clock::universal_time() +
            boost::posix_time::time_duration(0, 0, secs);
}

inline boost::xtime delay(int secs, int msecs=0, int nsecs=0)
{
    const int MILLISECONDS_PER_SECOND = 1000;
    const int NANOSECONDS_PER_SECOND = 1000000000;
    const int NANOSECONDS_PER_MILLISECOND = 1000000;

    boost::xtime xt;

    #if BOOST_VERSION >= 105100 //TIME_UTC is a macro in C11, breaking change in Boost.Thread
    int ret = boost::xtime_get(&xt, boost::TIME_UTC_);
    BOOST_INTERPROCES_CHECK(ret == static_cast<int>(boost::TIME_UTC_));(void)ret;
    #else
    int ret = boost::xtime_get(&xt, boost::TIME_UTC);
    BOOST_INTERPROCES_CHECK(ret == static_cast<int>(boost::TIME_UTC));(void)ret;
    #endif
    nsecs += xt.nsec;
    msecs += nsecs / NANOSECONDS_PER_MILLISECOND;
    secs += msecs / MILLISECONDS_PER_SECOND;
    nsecs += (msecs % MILLISECONDS_PER_SECOND) * NANOSECONDS_PER_MILLISECOND;
    xt.nsec = nsecs % NANOSECONDS_PER_SECOND;
    xt.sec += secs + (nsecs / NANOSECONDS_PER_SECOND);

    return xt;
}

template <typename F, typename T>
class binder
{
public:
    binder(const F& f, const T& p)
        : func(f), param(p) { }
    void operator()() const { func(param); }

private:
    F func;
    T param;
};

template <typename F, typename T>
binder<F, T> bind_function(F func, T param)
{
    return binder<F, T>(func, param);
}

template <class Condition, class Mutex>
struct condition_test_data
{
   condition_test_data() : notified(0), awoken(0) { }

   ~condition_test_data()
   {}

   Mutex      mutex;
   Condition  condition;
   int notified;
   int awoken;
};

template <class Condition, class Mutex>
void condition_test_thread(condition_test_data<Condition, Mutex>* data)
{
    boost::interprocess::scoped_lock<Mutex>
      lock(data->mutex);
    BOOST_INTERPROCES_CHECK(lock ? true : false);
    while (!(data->notified > 0))
        data->condition.wait(lock);
    BOOST_INTERPROCES_CHECK(lock ? true : false);
    data->awoken++;
}

struct cond_predicate
{
    cond_predicate(int& var, int val) : _var(var), _val(val) { }

    bool operator()() { return _var == _val; }

    int& _var;
    int _val;
};

template <class Condition, class Mutex>
void condition_test_waits(condition_test_data<Condition, Mutex>* data)
{
    boost::interprocess::scoped_lock<Mutex>
      lock(data->mutex);
    BOOST_INTERPROCES_CHECK(lock ? true : false);

    // Test wait.
    while (data->notified != 1)
        data->condition.wait(lock);
    BOOST_INTERPROCES_CHECK(lock ? true : false);
    BOOST_INTERPROCES_CHECK(data->notified == 1);
    data->awoken++;
    data->condition.notify_one();

    // Test predicate wait.
    data->condition.wait(lock, cond_predicate(data->notified, 2));
    BOOST_INTERPROCES_CHECK(lock ? true : false);
    BOOST_INTERPROCES_CHECK(data->notified == 2);
    data->awoken++;
    data->condition.notify_one();

    // Test timed_wait.
    while (data->notified != 3)
        data->condition.timed_wait(lock, ptime_delay(5));
    BOOST_INTERPROCES_CHECK(lock ? true : false);
    BOOST_INTERPROCES_CHECK(data->notified == 3);
    data->awoken++;
    data->condition.notify_one();

    // Test predicate timed_wait.
    cond_predicate pred(data->notified, 4);
    bool ret = data->condition.timed_wait(lock, ptime_delay(5), pred);
    BOOST_INTERPROCES_CHECK(ret);(void)ret;
    BOOST_INTERPROCES_CHECK(lock ? true : false);
    BOOST_INTERPROCES_CHECK(pred());
    BOOST_INTERPROCES_CHECK(data->notified == 4);
    data->awoken++;
    data->condition.notify_one();
}

template <class Condition, class Mutex>
void do_test_condition_notify_one()
{
   condition_test_data<Condition, Mutex> data;

   boost::thread thread(bind_function(&condition_test_thread<Condition, Mutex>, &data));
   //Make sure thread is blocked
   boost::thread::sleep(delay(1));
   {
      boost::interprocess::scoped_lock<Mutex>
         lock(data.mutex);
      BOOST_INTERPROCES_CHECK(lock ? true : false);
      data.notified++;
      data.condition.notify_one();
   }

   thread.join();
   BOOST_INTERPROCES_CHECK(data.awoken == 1);
}

template <class Condition, class Mutex>
void do_test_condition_notify_all()
{
   const int NUMTHREADS = 3;
   boost::thread_group threads;
   condition_test_data<Condition, Mutex> data;

   for (int i = 0; i < NUMTHREADS; ++i){
       threads.create_thread(bind_function(&condition_test_thread<Condition, Mutex>, &data));
   }
   //Make sure all threads are blocked
   boost::thread::sleep(delay(1));
   {
      boost::interprocess::scoped_lock<Mutex>
         lock(data.mutex);
      BOOST_INTERPROCES_CHECK(lock ? true : false);
      data.notified++;
   }
   data.condition.notify_all();

   threads.join_all();
   BOOST_INTERPROCES_CHECK(data.awoken == NUMTHREADS);
}

template <class Condition, class Mutex>
void do_test_condition_waits()
{
   condition_test_data<Condition, Mutex> data;

   boost::thread thread(bind_function(&condition_test_waits<Condition, Mutex>, &data));

   {
      boost::interprocess::scoped_lock<Mutex>
         lock(data.mutex);
      BOOST_INTERPROCES_CHECK(lock ? true : false);

      boost::thread::sleep(delay(1));
      data.notified++;
      data.condition.notify_one();
      while (data.awoken != 1)
         data.condition.wait(lock);
      BOOST_INTERPROCES_CHECK(lock ? true : false);
      BOOST_INTERPROCES_CHECK(data.awoken == 1);

      boost::thread::sleep(delay(1));
      data.notified++;
      data.condition.notify_one();
      while (data.awoken != 2)
         data.condition.wait(lock);
      BOOST_INTERPROCES_CHECK(lock ? true : false);
      BOOST_INTERPROCES_CHECK(data.awoken == 2);

      boost::thread::sleep(delay(1));
      data.notified++;
      data.condition.notify_one();
      while (data.awoken != 3)
         data.condition.wait(lock);
      BOOST_INTERPROCES_CHECK(lock ? true : false);
      BOOST_INTERPROCES_CHECK(data.awoken == 3);

      boost::thread::sleep(delay(1));
      data.notified++;
      data.condition.notify_one();
      while (data.awoken != 4)
         data.condition.wait(lock);
      BOOST_INTERPROCES_CHECK(lock ? true : false);
      BOOST_INTERPROCES_CHECK(data.awoken == 4);
   }

   thread.join();
   BOOST_INTERPROCES_CHECK(data.awoken == 4);
}
/*
//Message queue simulation test
template <class Condition>
inline Condition &cond_empty()
{
   static Condition cond_empty;
   return cond_empty;
}

template <class Condition>
inline Condition &cond_full()
{
   static Condition cond_full;
   return cond_full;
}

template <class Mutex>
inline Mutex &mutex()
{
   static Mutex mut;
   return mut;
}
*/
static volatile int count = 0;
static volatile int waiting_readers = 0;
static volatile int waiting_writer  = 0;
const int queue_size    = 3;
const int thread_factor = 10;
const int NumThreads    = thread_factor*queue_size;

//Function that removes items from queue
template <class Condition, class Mutex>
struct condition_func
{
   condition_func(Condition &cond_full, Condition &cond_empty, Mutex &mutex)
      :  cond_full_(cond_full), cond_empty_(cond_empty), mutex_(mutex)
   {}

   void operator()()
   {
      boost::interprocess::scoped_lock<Mutex>lock(mutex_);
      while(count == 0){
         ++waiting_readers;
         cond_empty_.wait(lock);
         --waiting_readers;
      }
      --count;
      if(waiting_writer)
         cond_full_.notify_one();
   }
   Condition &cond_full_;
   Condition &cond_empty_;
   Mutex     &mutex_;
};

//Queue functions
template <class Condition, class Mutex>
void do_test_condition_queue_notify_one(void)
{
   //Force mutex and condition creation
   Condition cond_empty;
   Condition cond_full;
   Mutex mutex;

   //Create threads that will decrease count
   {
      //Initialize counters
      count = 0;
      waiting_readers = 0;
      waiting_writer  = 0;

      boost::thread_group thgroup;
      int i;
      for(i = 0; i< NumThreads; ++i){
         condition_func<Condition, Mutex> func(cond_full, cond_empty, mutex);
         thgroup.create_thread(func);
      }

      //Add 20 elements one by one in the queue simulation
      //The sender will block if it fills the queue
      for(i = 0; i < NumThreads; ++i){
         boost::interprocess::scoped_lock<Mutex> lock(mutex);
         while(count == queue_size){
            ++waiting_writer;
            cond_full.wait(lock);
            --waiting_writer;
         }
         count++;

         if(waiting_readers)
            cond_empty.notify_one();
      }
      thgroup.join_all();
      BOOST_INTERPROCES_CHECK(count == 0);
      BOOST_INTERPROCES_CHECK(waiting_readers == 0);
      BOOST_INTERPROCES_CHECK(waiting_writer  == 0);
   }
}

//Queue functions
template <class Condition, class Mutex>
void do_test_condition_queue_notify_all(void)
{
   //Force mutex and condition creation
   Condition cond_empty;
   Condition cond_full;
   Mutex mutex;

   //Create threads that will decrease count
   {
      //Initialize counters
      count = 0;
      waiting_readers = 0;
      waiting_writer  = 0;

      boost::thread_group thgroup;
      int i;
      for(i = 0; i< NumThreads; ++i){
         condition_func<Condition, Mutex> func(cond_full, cond_empty, mutex);
         thgroup.create_thread(func);
      }

      //Fill queue to the max size and notify all several times
      for(i = 0; i < NumThreads; ++i){
         boost::interprocess::scoped_lock<Mutex>lock(mutex);
         while(count == queue_size){
            ++waiting_writer;
            cond_full.wait(lock);
            --waiting_writer;
         }
         count++;

         if(waiting_readers)
            cond_empty.notify_all();
      }
      thgroup.join_all();
      BOOST_INTERPROCES_CHECK(count == 0);
      BOOST_INTERPROCES_CHECK(waiting_readers == 0);
      BOOST_INTERPROCES_CHECK(waiting_writer  == 0);
   }
}

template <class Condition, class Mutex>
bool do_test_condition()
{
   std::cout << "do_test_condition_notify_one<" << typeid(Condition).name() << "," << typeid(Mutex).name() << '\n' << std::endl;
   do_test_condition_notify_one<Condition, Mutex>();
   std::cout << "do_test_condition_notify_all<" << typeid(Condition).name() << "," << typeid(Mutex).name() << '\n' << std::endl;
   do_test_condition_notify_all<Condition, Mutex>();
   std::cout << "do_test_condition_waits<" << typeid(Condition).name() << "," << typeid(Mutex).name() << '\n' << std::endl;
   do_test_condition_waits<Condition, Mutex>();
   std::cout << "do_test_condition_queue_notify_one<" << typeid(Condition).name() << "," << typeid(Mutex).name() << '\n' << std::endl;
   do_test_condition_queue_notify_one<Condition, Mutex>();
   std::cout << "do_test_condition_queue_notify_all<" << typeid(Condition).name() << "," << typeid(Mutex).name() << '\n' << std::endl;
   do_test_condition_queue_notify_all<Condition, Mutex>();
   return true;
}

}  //namespace test
}  //namespace interprocess{
}  //namespace boost{

#include <boost/interprocess/detail/config_end.hpp>

#endif   //#ifndef BOOST_INTERPROCESS_CONDITION_TEST_TEMPLATE_HPP


text:
import stream from 'stream';
import csvWriter from 'csv-write-stream';

class json extends stream.Transform {
  constructor() {
    super({ objectMode: true });
  }

  _transform(data, encoding, cb) {
    data = `${JSON.stringify(data)}\r\n`;
    this.push(data);
    cb();
  }
}

export default {
  bson: collection => Promise.resolve(collection),
  json: collection => {
    const parserJson = new json();
    parserJson.filename = collection.filename;
    return Promise.resolve(collection.pipe(parserJson));
  },
  csv: collection => {
    const writer = csvWriter();
    writer.filename = collection.filename;
    return Promise.resolve(collection.pipe(writer));
  }
};

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <title>Kiosk</title>

    <link rel="stylesheet" href="stylesheets/style.css" />
    <link rel="stylesheet" href="stylesheets/kioskmap.css" />


text:
<?xml version="1.0" encoding="utf-8"?>
<ldml xmlns:sil="urn://www.sil.org/ldml/0.1">
	<identity>
		<version number="0.0.1"/>
		<generation date="2018-11-20 22:21:37"/>
		<language type="nou"/>
		<special>
			<sil:identity defaultRegion="PG" script="Latn" draft="generated"/>
		</special>
	</identity>
	<localeDisplayNames>
		<special>
			<sil:names>
				<sil:name xml:lang="en">Ewage-Notu</sil:name>
			</sil:names>
		</special>
	</localeDisplayNames>
	<layout>
		<orientation>
			<characterOrder>left-to-right</characterOrder>
		</orientation>
	</layout>
	<characters>
		<exemplarCharacters draft="unconfirmed">[a b d e g i j k m {mb} n {nd} {ng} {nj} {ny} o p r s t u v w y]</exemplarCharacters>
		<exemplarCharacters alt="proposed-dbl" draft="suspect">[A-Za-z]</exemplarCharacters>
		<exemplarCharacters type="auxiliary" draft="unconfirmed">[c f h l q x z]</exemplarCharacters>
		<exemplarCharacters type="punctuation">[! ( ) , \- . ? \[ \] ' ' " "]</exemplarCharacters>
		<exemplarCharacters type="punctuation" alt="proposed-dbl" draft="suspect">[!(),-/\:?\[\]\u00A9\u200C\u200D\u2014\u2018\u2019\u201C\u201D\u2022]</exemplarCharacters>
		<exemplarCharacters type="index">[A B C D E F G H I J K L M N O P Q R S T U V W X Y Z]</exemplarCharacters>
	</characters>
	<delimiters>
		<quotationStart>"</quotationStart>
		<quotationEnd>"</quotationEnd>
		<alternateQuotationStart>'</alternateQuotationStart>
		<alternateQuotationEnd>'</alternateQuotationEnd>
		<special>
			<sil:matched-pairs>
				<sil:matched-pair open="(" close=")" paraClose="false"/>
				<sil:matched-pair open="[" close="]" paraClose="false"/>
				<sil:matched-pair open="{" close="}" paraClose="false"/>
			</sil:matched-pairs>
			<sil:punctuation-patterns>
				<sil:punctuation-pattern pattern="!_" context="final"/>
				<sil:punctuation-pattern pattern=")_" context="final"/>
				<sil:punctuation-pattern pattern="," context="medial"/>
				<sil:punctuation-pattern pattern=",_" context="final"/>
				<sil:punctuation-pattern pattern="-" context="medial"/>
				<sil:punctuation-pattern pattern="." context="medial"/>
				<sil:punctuation-pattern pattern="._" context="final"/>
				<sil:punctuation-pattern pattern="/" context="medial"/>
				<sil:punctuation-pattern pattern=":" context="medial"/>
				<sil:punctuation-pattern pattern=":_" context="final"/>
				<sil:punctuation-pattern pattern="?" context="medial"/>
				<sil:punctuation-pattern pattern="?_" context="final"/>
				<sil:punctuation-pattern pattern="[" context="medial"/>
				<sil:punctuation-pattern pattern="]" context="medial"/>
				<sil:punctuation-pattern pattern="]_" context="final"/>
				<sil:punctuation-pattern pattern="_(" context="init"/>
				<sil:punctuation-pattern pattern="_(_" context="isolate"/>
				<sil:punctuation-pattern pattern="_)_" context="isolate"/>
				<sil:punctuation-pattern pattern="_-_" context="isolate"/>
				<sil:punctuation-pattern pattern="_[" context="init"/>
				<sil:punctuation-pattern pattern="_©_" context="isolate"/>
				<sil:punctuation-pattern pattern="_—_" context="isolate"/>
				<sil:punctuation-pattern pattern="_'" context="init"/>
				<sil:punctuation-pattern pattern="_"" context="init"/>
				<sil:punctuation-pattern pattern="_•_" context="isolate"/>
				<sil:punctuation-pattern pattern="" context="medial"/>
				<sil:punctuation-pattern pattern="" context="medial"/>
				<sil:punctuation-pattern pattern="'" context="medial"/>
				<sil:punctuation-pattern pattern="'_" context="final"/>
				<sil:punctuation-pattern pattern=""_" context="final"/>
			</sil:punctuation-patterns>
			<sil:quotation-marks paraContinueType="all">
				<sil:quotationContinue>"</sil:quotationContinue>
				<sil:alternateQuotationContinue>'</sil:alternateQuotationContinue>
				<sil:quotation open=""" close=""" continue=""" level="3"/>
			</sil:quotation-marks>
		</special>
	</delimiters>
	<special>
		<sil:external-resources>
			<sil:font name="Charis SIL" types="default">
				<sil:url>https://wirl.api.sil.org/CharisSILReg&type=ttf</sil:url>
			</sil:font>
			<sil:font name="Noto Sans"><!--types="ui"-->
				<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSans/NotoSans-Regular.ttf</sil:url>
			</sil:font>
			<sil:font name="Noto Serif">
				<sil:url>https://github.com/googlefonts/noto-fonts/raw/main/hinted/ttf/NotoSerif/NotoSerif-Regular.ttf</sil:url>
			</sil:font>
		</sil:external-resources>
	</special>
</ldml>


text:
package nilgiri.physics;

import nilgiri.math.RealNumber;
import nilgiri.math.autodiff.DifferentialFunction;

public class OrbitalElements <X extends RealNumber<X>> {

	private DifferentialFunction<X> m_epoch;
	private DifferentialFunction<X> m_e;
	private DifferentialFunction<X> m_a;
	private DifferentialFunction<X> m_inclination;
	private DifferentialFunction<X> m_node;
	private DifferentialFunction<X> m_perigee;
	private DifferentialFunction<X> m_manomaly;

	public OrbitalElements(
			DifferentialFunction<X> i_epoch, //epoch
			DifferentialFunction<X> i_a, //semi-major axis
			DifferentialFunction<X> i_e, //eccentricity
			DifferentialFunction<X> i_inclination, // inclination. 0 for 2D
			DifferentialFunction<X> i_node, // right ascension of the ascending node.  0 for 2D
			DifferentialFunction<X> i_perigee, //argument of perigee
			DifferentialFunction<X> i_manomaly //mean anomaly
			){
		m_epoch = i_epoch;
		m_a = i_a;
		m_e = i_e;
		m_inclination = i_inclination;
		m_node = i_node;
		m_perigee = i_perigee;
		m_manomaly = i_manomaly;
	}

	public DifferentialFunction<X> epoch(){
		return m_epoch;
	}
	public DifferentialFunction<X> a(){
		return m_a;
	}
	public DifferentialFunction<X> e(){
		return m_e;
	}
	public DifferentialFunction<X> inclination(){
		return m_inclination;
	}
	public DifferentialFunction<X> node(){
		return m_node;
	}
	public DifferentialFunction<X> perigee(){
		return m_perigee;
	}
	public DifferentialFunction<X> meanAnomaly(){
		return m_manomaly;
	}

}


text:
[Documentation](https://github.com/fdaciuk/js-components/wiki)

## Modules
[Google Maps](https://github.com/fdaciuk/js-components/wiki/Google-Maps)
[Infinite Scroll](https://github.com/fdaciuk/js-components/wiki/Infinite-Scroll)
[Featured Label](https://github.com/fdaciuk/js-components/wiki/Featured-Label)
[Storage](https://github.com/fdaciuk/js-components/wiki/Storage)

## License
[MIT License](https://github.com/fdaciuk/js-components/blob/master/LICENSE) © Fernando Daciuk


text:
package org.notificationengine.notificator.mail;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;

import org.apache.log4j.Logger;
import org.bson.types.ObjectId;
import org.joda.time.DateTime;
import org.notificationengine.constants.Constants;
import org.notificationengine.domain.DecoratedNotification;
import org.notificationengine.domain.PhysicalNotification;
import org.notificationengine.domain.Recipient;
import org.notificationengine.domain.Topic;
import org.notificationengine.mail.MailOptionsUtils;
import org.notificationengine.mail.Mailer;
import org.notificationengine.notificator.INotificator;
import org.notificationengine.persistance.Persister;
import org.notificationengine.spring.SpringUtils;
import org.notificationengine.templating.TemplateEngine;
import org.springframework.stereotype.Component;

@Component(value=Constants.SINGLE_MULTI_TOPIC_MAIL_BY_RECIPIENT_NOTIFICATOR)
public class SingleMultiTopicMailByRecipientNotificator implements INotificator {

	private static Logger LOGGER = Logger.getLogger(SingleMultiTopicMailByRecipientNotificator.class);

	private Boolean activated;

	private Map<String, MailTemplateConfiguration> mailTemplateAndTopics;

	private Collection<DecoratedNotification> decoratedNotificationsToProcess;

    private Boolean urgentEnabled;

	public SingleMultiTopicMailByRecipientNotificator() {

		this.activated = Boolean.FALSE;

        this.urgentEnabled = Boolean.FALSE;

		this.mailTemplateAndTopics = new HashMap<>();

		this.decoratedNotificationsToProcess = new HashSet<>();
	}

    @Override
    public void setUrgentEnabled(Boolean urgentEnabled) {
        this.urgentEnabled = urgentEnabled;
    }

    public Boolean getUrgentEnabled() {
        return urgentEnabled;
    }

    public Boolean isActivated() {

		return this.activated;
	}

	public void activate() {

		this.activated = Boolean.TRUE;
	}

	@Override
	public void process() {

		TemplateEngine templateEngine = (TemplateEngine)SpringUtils.getBean(Constants.TEMPLATE_ENGINE);

		Mailer mailer = (Mailer)SpringUtils.getBean(Constants.MAILER);

        // Get the actual date and the date x days before to add it to the context
        // This part is specific for our customer
        DateTime now = new DateTime();
        String today = now.toString("dd/MM/yyyy");

        DateTime lastTime = now.minusDays(Constants.DAYS_BETWEEN_NOTIFICATION);
        String lastTimeString = lastTime.toString("dd/MM/yyyy");

		// for each mailTemplate, get decoratedNotifications to process and send them in a single multi topic mail
		for (String mailTemplate : this.mailTemplateAndTopics.keySet()) {

			templateEngine.loadTemplate(mailTemplate);

			MailTemplateConfiguration topicsForThisMailTemplate = this.mailTemplateAndTopics.get(mailTemplate);

			LOGGER.debug("Topics for this MailTemplate : " + topicsForThisMailTemplate);

			Collection<Recipient> recipientsForTheseTopics = this.retrieveRecipientsForTopics(topicsForThisMailTemplate.getTopics());

			LOGGER.debug("Recipients for these topics : " + recipientsForTheseTopics);

            Persister persister = (Persister)SpringUtils.getBean(Constants.PERSISTER);

			for (Recipient recipient : recipientsForTheseTopics) {

				LOGGER.debug("Recipient : " + recipient);

				Collection<DecoratedNotification> decoratedNotificationsForThisRecipient = new HashSet<>();

                Collection<File> filesToAttach = new HashSet<>();

                Collection<ObjectId> allFileIds = new HashSet<>();

				Collection<Map<String, Object>> rawNotificationContexts = new ArrayList<>();

				// build and send mail for these notifications
				Map<String, Object> globalContext = new HashMap<>();

				globalContext.put(Constants.RECIPIENT, recipient.getAddress());
				globalContext.put(Constants.DISPLAY_NAME, recipient.getDisplayName());
				globalContext.put(Constants.BEGIN_DATE, lastTimeString);
				globalContext.put(Constants.END_DATE, today);

				Collection<Map<String, Object>> topicContexts = new HashSet<>();

				for (Topic topicForThisMailTemplate : topicsForThisMailTemplate.getTopics()) {

					LOGGER.debug("Topic : " + topicForThisMailTemplate);

					Map<String, Object> topicContext = new HashMap<>();

					topicContext.put(Constants.TOPIC, topicForThisMailTemplate.getName());

					Collection<DecoratedNotification> decoratedNotificationsForThisTopicAndRecipient = this.retrieveDecoratedNotificationsToProcessForTopicAndRecipient(topicForThisMailTemplate,
																																							recipient);

					decoratedNotificationsForThisRecipient.addAll(decoratedNotificationsForThisTopicAndRecipient);

					Collection<Map<String, Object>> contexts = new ArrayList<>();
					for (DecoratedNotification decoratedNotificationForThisTopicAndRecipient : decoratedNotificationsForThisTopicAndRecipient) {

						contexts.add(decoratedNotificationForThisTopicAndRecipient.getRawNotification().getContext());

						rawNotificationContexts.add(decoratedNotificationForThisTopicAndRecipient.getRawNotification().getContext());

                        Map<String, Object> context = decoratedNotificationForThisTopicAndRecipient.getRawNotification().getContext();

                        Collection<ObjectId> fileIds = (Collection<ObjectId>) context.get("fileIds");

                        if(fileIds != null) {

                            for(ObjectId fileId : fileIds) {

                                allFileIds.add(fileId);

                                File file = persister.retrieveFileFromId(fileId);

                                filesToAttach.add(file);
                            }
                        }
					}

					topicContext.put(Constants.NOTIFICATIONS_FOR_TOPIC, contexts);

					topicContexts.add(topicContext);
				}

				globalContext.put(Constants.TOPICS, topicContexts);

				String notificationText = templateEngine.processTemplate(mailTemplate, globalContext);

				LOGGER.debug("Notification text after merge : " + notificationText);

				Map<String, String> options = MailOptionsUtils.buildMailOptionsFromContexts(rawNotificationContexts);

				// sent a mail to the recipient
				Boolean sentCorrectly = mailer.sendMail(recipient.getAddress(), notificationText, topicsForThisMailTemplate.getHtmlTemplate(), filesToAttach, options);

				LOGGER.debug("Mail sent? " + sentCorrectly);

				if (sentCorrectly) {

					this.markAsSent(decoratedNotificationsForThisRecipient);

                    this.savePhysicalNotification(recipient, mailer.getSubject(options), notificationText, allFileIds);

				}
				else {
					this.markAsNotSent(decoratedNotificationsForThisRecipient);
				}

                //delete files created after sending (or not)
                //even if it has not been sent, the file will be created next time
                for(File file : filesToAttach) {
                    file.delete();
                }
			}
		}
	}

	private void markAsNotSent(
			Collection<DecoratedNotification> decoratedNotifications) {

		for (DecoratedNotification decoratedNotification : decoratedNotifications) {

			this.markAsNotSent(decoratedNotification);
		}
	}

	private void markAsNotSent(DecoratedNotification decoratedNotification) {

		Persister persister = (Persister)SpringUtils.getBean(Constants.PERSISTER);

		Integer attempts = decoratedNotification.getSendingAttempts();

        attempts = attempts + 1;

        decoratedNotification.setSendingAttempts(attempts);

        if(attempts >= Constants.MAX_ATTEMPTS) {

        	persister.moveFailedDecoratedNotification(decoratedNotification);
        }
        else {
        	persister.saveDecoratedNotification(decoratedNotification);
        }
	}

	private void markAsSent(
			Collection<DecoratedNotification> decoratedNotifications) {

		for (DecoratedNotification decoratedNotification : decoratedNotifications) {

			this.markAsSent(decoratedNotification);
		}
	}

	private void markAsSent(DecoratedNotification decoratedNotification) {

		Persister persister = (Persister)SpringUtils.getBean(Constants.PERSISTER);

		persister.markDecoratedNotificationAsSent(decoratedNotification);
	}

    public void savePhysicalNotification(
            Recipient recipient, String subject, String notificationContent, Collection<ObjectId> filesAttachedIds) {

        PhysicalNotification physicalNotification =
                new PhysicalNotification(recipient, subject, notificationContent, filesAttachedIds);

        Persister persister = (Persister) SpringUtils.getBean(Constants.PERSISTER);

        persister.savePhysicalNotification(physicalNotification);

    }

	public Collection<Recipient> retrieveRecipientsForTopics(
			Collection<Topic> topics) {

		Collection<Recipient> result = new HashSet<>();

		for (DecoratedNotification decoratedNotification : this.decoratedNotificationsToProcess) {

			Topic decoratedNotificationTopic = decoratedNotification.getRawNotification().getTopic();

			for (Topic topic : topics) {

				if (decoratedNotificationTopic.isSonOfTopic(topic)) {

					result.add(decoratedNotification.getRecipient());

					break;
				}
			}
		}

		return result;
	}

	public Collection<DecoratedNotification> retrieveDecoratedNotificationsToProcessForTopicAndRecipient(Topic topic, Recipient recipient) {

		Collection<DecoratedNotification> result = new HashSet<>();

		Collection<DecoratedNotification> decoratedNotificationsToRemove = new HashSet<>();

		for (DecoratedNotification decoratedNotification : this.decoratedNotificationsToProcess) {

			Topic decoratedNotificationTopic = decoratedNotification.getRawNotification().getTopic();

			Recipient decoratedNotificationRecipient = decoratedNotification.getRecipient();

			if (decoratedNotificationTopic.isSonOfTopic(topic)
					&& decoratedNotificationRecipient.equals(recipient)) {

				result.add(decoratedNotification);

				decoratedNotificationsToRemove.add(decoratedNotification);
			}
		}

		for (DecoratedNotification decoratedNotification : decoratedNotificationsToRemove) {

			this.decoratedNotificationsToProcess.remove(decoratedNotification);
		}

		return result;
	}

	public void add(String mailTemplate, Boolean isHtmlTemplate, Topic topic) {

		MailTemplateConfiguration topicsForMailTemplate = this.mailTemplateAndTopics.get(mailTemplate);

		if (topicsForMailTemplate == null) {

			topicsForMailTemplate = new MailTemplateConfiguration();

			this.mailTemplateAndTopics.put(mailTemplate, topicsForMailTemplate);
		}

		topicsForMailTemplate.add(isHtmlTemplate, topic);
	}

	public void addDecoratedNotificationsToProcess(
			Collection<DecoratedNotification> notSentDecoratedNotifications) {

		this.decoratedNotificationsToProcess.addAll(notSentDecoratedNotifications);
	}

	public Map<String, MailTemplateConfiguration> getMailTemplateAndTopics() {
		return mailTemplateAndTopics;
	}

	public void setMailTemplateAndTopics(Map<String, MailTemplateConfiguration> mailTemplateAndTopics) {
		this.mailTemplateAndTopics = mailTemplateAndTopics;
	}

	public Collection<DecoratedNotification> getDecoratedNotificationsToProcess() {
		return decoratedNotificationsToProcess;
	}

	public void setDecoratedNotificationsToProcess(
			Collection<DecoratedNotification> decoratedNotificationsToProcess) {
		this.decoratedNotificationsToProcess = decoratedNotificationsToProcess;
	}
}


text:
package madgik.exareme.common.schema;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author herald
 */
public class Query implements Serializable {
    private static final long serialVersionUID = 1L;
    private int id = -1;
    private String databaseDir = null;
    private String query = null;
    private String comments = null;
    private String mappings;

    private ArrayList<Integer> runOnParts = null;
    private List<Integer> runOnPartsView = null;
    private boolean sorted = false;

    public Query(int id, String query, String comments) {
        this.id = id;
        this.query = query;
        this.comments = comments;
        this.runOnParts = new ArrayList<Integer>();
        this.runOnPartsView = Collections.unmodifiableList(runOnParts);
    }

    public int getId() {
        return id;
    }

    public String getComments() {
        return comments;
    }

    public String getMappings() {
        return mappings;
    }

    public void setMappings(String mappings) {
        this.mappings = mappings;
    }

    public String getDatabaseDir() {
        return databaseDir;
    }

    public void setDatabaseDir(String databaseDir) {
        this.databaseDir = databaseDir;
    }

    public String getQuery() {
        return query;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public void addRunOnPart(int pNum) {
        runOnParts.add(pNum);
        sorted = false;
    }

    /**
     * @return a sorted list with the partitions that are used.
     */
    public List<Integer> getRunOnParts() {
        if (sorted == false) {
            Collections.sort(runOnParts);
            sorted = true;
        }

        return runOnPartsView;
    }
}


text:
package orm.handler;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import orm.DatasourceFactory;
import orm.handler.retO.SaveRet;
import orm.util.SQLUtil;
import util.StringUtil;

import javax.persistence.*;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

public class SaveHandler implements InvocationHandler {

    private static final Logger logger = LogManager.getLogger(SaveHandler.class);

    private final Class<?> tableClass;

    public SaveHandler(Class<?> tableClass) {
        this.tableClass = tableClass;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Class<?> type = args[0].getClass();
        if (!this.tableClass.isAssignableFrom(type)) {
            throw new RuntimeException("saving incorrect type : " + args[0].getClass());
        }

        SaveRet generatedSQL = this.generateSQL(this.tableClass, args[0]);
        if (null == generatedSQL) {
            throw new RuntimeException("generate sql error.");
        }

        Connection conn = null;
        try {
            conn = DatasourceFactory.getConnection();
            PreparedStatement preparedStatement = conn.prepareStatement(generatedSQL.getSql(), Statement.RETURN_GENERATED_KEYS);
            logger.info(generatedSQL.getSql());

            int i = 1;
            for (Method getterMethod : generatedSQL.getGetters()) {
                SQLUtil.setPSbyFieldAtIndex(preparedStatement, i++,
                        getterMethod.invoke(args[0]),
                        getterMethod.getReturnType().getTypeName());
            }

            int affectedRows = preparedStatement.executeUpdate();

            if (affectedRows == 0) {
                return false;
            }

            if (!generatedSQL.isInsert()) {
                return true;
            }

            try (ResultSet generatedKeys = preparedStatement.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    SQLUtil.fill(generatedSQL.getIdSetter().getParameterTypes()[0].getTypeName(),
                            args[0], generatedSQL.getIdSetter(), generatedKeys, true, 1, null);
                    return true;
                } else {
                    return false;
                }
            }
        } finally {
            DatasourceFactory.closeConnection(conn);
        }
    }

    private SaveRet generateSQL(Class<?> type, Object arg) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        Entity entity = type.getDeclaredAnnotation(Entity.class);
        if (null == entity) {
            throw new RuntimeException("lack of Entity.class definition.");
        }
        String tableName = entity.name();

        Boolean isInsert = null;
        Method idSetter = null;
        for (Method method : type.getMethods()) {
            Id id = method.getDeclaredAnnotation(Id.class);
            if (null == id) {
                continue;
            }

            Column column = method.getDeclaredAnnotation(Column.class);
            Object idValue = method.invoke(arg);

            isInsert = null == idValue;
            String setterName = "set" + StringUtil.cutPrefix(method.getName(), "get", "is");
            idSetter = type.getMethod(setterName, method.getReturnType());
            break;
        }

        SaveRet generatedSQL = null;
        if (isInsert) {
            generatedSQL = this.generateInsert(type, tableName);
        } else {
            generatedSQL = this.generateUpdate(type, tableName);
        }

        return new SaveRet().setInsert(isInsert).setIdSetter(idSetter)
                .setSql(generatedSQL.getSql())
                .setGetters(generatedSQL.getGetters());
    }

    private SaveRet generateUpdate(Class<?> type, String tableName) {
        String idColumn = null;
        StringJoiner columnSetters = new StringJoiner(",");

        Method idGetter = null;
        List<Method> getters = new ArrayList<>();
        for (Method method : type.getMethods()) {
            Column column = method.getDeclaredAnnotation(Column.class);
            if (null == column) {
                continue;
            }

            Id id = method.getDeclaredAnnotation(Id.class);
            if (null != id) {
                idColumn = column.name();
                idGetter = method;
                continue;
            }

            columnSetters.add(String.format("`%s`=?", column.name()));
            getters.add(method);
        }
        getters.add(idGetter);

        return new SaveRet().setSql(String.format(
                "UPDATE `%s` SET %s WHERE `%s`=?", tableName,
                columnSetters.toString(), idColumn
        )).setGetters(getters);
    }

    private SaveRet generateInsert(Class<?> type, String tableName) {
        StringJoiner columns = new StringJoiner("`,`", "`", "`");
        StringJoiner valuePlaceHolders = new StringJoiner(",");

        List<Method> getters = new ArrayList<>();
        for (Method method : type.getMethods()) {
            Column column = method.getDeclaredAnnotation(Column.class);
            if (null == column) {
                continue;
            }

            Id id = method.getDeclaredAnnotation(Id.class);
            if (null == id) {
                columns.add(column.name());
                valuePlaceHolders.add("?");
                getters.add(method);
                continue;
            }

            GeneratedValue generatedValue = method.getDeclaredAnnotation(GeneratedValue.class);
            if (null != generatedValue) {
                if (!generatedValue.strategy().equals(GenerationType.IDENTITY)) {
                    throw new RuntimeException("don't know how to insert, id is null");
                }
            }
        }

        return new SaveRet().setSql(String.format(
                "INSERT INTO `%s`(%s) VALUES (%s)", tableName,
                columns.toString(), valuePlaceHolders.toString()
        )).setGetters(getters);
    }
}


text:
#pragma once

#include <atomic>
#include <cassert>
#include <chrono>
#include <cstdint>
#include <limits>
#include <type_traits>

#include <folly/portability/Unistd.h>

namespace folly {
namespace detail {

enum class FutexResult {
  VALUE_CHANGED, /* futex value didn't match expected */
  AWOKEN, /* wakeup by matching futex wake, or spurious wakeup */
  INTERRUPTED, /* wakeup by interrupting signal */
  TIMEDOUT, /* wakeup by expiring deadline */
};

/**
 * Futex is an atomic 32 bit unsigned integer that provides access to the
 * futex() syscall on that value.  It is templated in such a way that it
 * can interact properly with DeterministicSchedule testing.
 *
 * If you don't know how to use futex(), you probably shouldn't be using
 * this class.  Even if you do know how, you should have a good reason
 * (and benchmarks to back you up).
 *
 * Because of the semantics of the futex syscall, the futex family of
 * functions are available as free functions rather than member functions
 */
template <template <typename> class Atom = std::atomic>
using Futex = Atom<std::uint32_t>;

/**
 * Puts the thread to sleep if this->load() == expected.  Returns true when
 * it is returning because it has consumed a wake() event, false for any
 * other return (signal, this->load() != expected, or spurious wakeup).
 */
template <typename Futex>
FutexResult futexWait(
    const Futex* futex, uint32_t expected, uint32_t waitMask = -1);

/**
 * Similar to futexWait but also accepts a deadline until when the wait call
 * may block.
 *
 * Optimal clock types: std::chrono::system_clock, std::chrono::steady_clock.
 * NOTE: On some systems steady_clock is just an alias for system_clock,
 * and is not actually steady.
 *
 * For any other clock type, now() will be invoked twice.
 */
template <typename Futex, class Clock, class Duration>
FutexResult futexWaitUntil(
    const Futex* futex,
    uint32_t expected,
    std::chrono::time_point<Clock, Duration> const& deadline,
    uint32_t waitMask = -1);

/**
 * Wakes up to count waiters where (waitMask & wakeMask) != 0, returning the
 * number of awoken threads, or -1 if an error occurred.  Note that when
 * constructing a concurrency primitive that can guard its own destruction, it
 * is likely that you will want to ignore EINVAL here (as well as making sure
 * that you never touch the object after performing the memory store that is
 * the linearization point for unlock or control handoff).  See
 * https://sourceware.org/bugzilla/show_bug.cgi?id=13690
 */
template <typename Futex>
int futexWake(
    const Futex* futex,
    int count = std::numeric_limits<int>::max(),
    uint32_t wakeMask = -1);

/** A std::atomic subclass that can be used to force Futex to emulate
 *  the underlying futex() syscall.  This is primarily useful to test or
 *  benchmark the emulated implementation on systems that don't need it. */
template <typename T>
struct EmulatedFutexAtomic : public std::atomic<T> {
  EmulatedFutexAtomic() noexcept = default;
  constexpr /* implicit */ EmulatedFutexAtomic(T init) noexcept
      : std::atomic<T>(init) {}
  // It doesn't copy or move
  EmulatedFutexAtomic(EmulatedFutexAtomic&& rhs) = delete;
};

} // namespace detail
} // namespace folly

#include <folly/detail/Futex-inl.h>


text:
var geocoder = require('geocoder')
var googleKey = process.env.GOOGLE_API
// NOTE TO VINCENT! ASK PHIL FOR EVENTBRIGHT KEY TO PUT IN HEROKU
var eventBrightKey = process.env.EVENTBRIGHT_API
console.log("eventbright key: "+eventBrightKey)
var mongoose = require('mongoose')
var http = require('request')

mongoose.connect(process.env.MONGO_URL)

var User = require('./app/models/user')

// call the packages we need
var express    = require('express');        // call express
var app        = express();                 // define our app using express
var bodyParser = require('body-parser');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(request, response, next) {
  response.header("Access-Control-Allow-Origin", "*");
  response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});
app.get('/', function(request, response, next) {
  // Handle the get for this route
});
app.post('/', function(request, response, next) {
 // Handle the post for this route
});

var port = process.env.PORT || 9090;        // set our port

// ROUTES FOR OUR API
// =============================================================================
var router = express.Router();              // get an instance of the express Router

router.use(function(request, response, next){
  console.log('Something is happening')
  next();
})

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(request, response) {
    response.json({ message: 'hooray! welcome to our api!' });
});

// User routes
// -------------------

//  POST USER:
router.route('/users')

.post(function(request, response) {

  var postUser = function(coordinates) {

    // The regex capitalizes the name and city properly.
    var user            = new User();
    user.name           = request.body.name.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    user.email          = request.body.email.toLowerCase();
    user.city           = request.body.city.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    user.departureDate  = request.body.departureDate
    user.geocoordinates = coordinates;

    user.save(function(error){
      if (error)
        response.send(error)
      else
        response.json({
          message:  'User created!',
          user:     user
        })
    })
  }

  var getUserGeocoordinates = function(city) {
    geocoder.geocode(city, function(results, status){
      // console.log(status.results[0].geometry.location)
      if (true) {
        var latLg = status.results[0].geometry.location
        // var latLongString = latLg
        // console.log(latLg.lat + "," + latLg.lng+"")
        var coords = (latLg.lat + "," + latLg.lng)
        // barf
        postUser(coords)
      } else {
        console.log('Geocode was not successful for the following reason: ' + status);
      }
    })
  }
  getUserGeocoordinates(request.body.city)
})

//  GET SPECIFIC USER
router.route('/users/:user_id')

.get(function(request, response){
  User.findById(request.params.user_id, function(error, user){
    if (error)
      response.send(error)
    // else
      response.json(user)
  })
})

//  GET USER BY EMAIL
//  Accepts user_email as params and returns a user object.
//  Note: email attribute is unique to all users.
router.route('/emails/:user_email')

.get(function(request, response){
  User.findOne({ email:request.params.user_email.toLowerCase()}, function(error, user){
    if (error)
      response.send(error)
    // else
      response.json(user)
  })
})

// ROUTES FOR EACH API:
//______________________________________________________________________

//WIKI ROUTE:
router.route('/wiki/:user_id')
  .get(function(request, response){
    User.findById(request.params.user_id, function(error, user){
      if (error)
        response.send(error)
      else
        console.log(user.city)
        var userCity = user.city // NEED TO TURN THIS INTO QUERY STRING (IF IT'S A CITY WITH TWO WORDS (CANT HAVE SPACES))
            http({
              url:'http://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&redirects&titles='+user.city+'&continue=',
              method:"GET"},
              function(error, res, body){
                var wiki_data = JSON.parse(body)
                var wiki_page_key = Object.keys(wiki_data.query.pages)
                var wiki_content = wiki_data.query.pages[wiki_page_key].extract
                response.json({wiki_content: wiki_content})
            })
    })
  })

// GOOGLE PHOTO ROUTE:

router.route('/google_photo/:user_id')
  .get(function(request, response){
    User.findById(request.params.user_id, function(error, user){
      if (error)
        response.send(error)
      else
        console.log(user.geocoordinates)
        var latLong = user.geocoordinates
          http({
            url:'https://maps.googleapis.com/maps/api/place/nearbysearch/json?key=AIzaSyAsmkkWTdFUhw8rXGd_Qa4rwTo-Bv80F_A&location='+latLong+'&radius=50000',
            method:"GET"
          },function(error, res, body){
            var arr = JSON.parse(body).results
            var photoArr = []
            for (var i=0;i<arr.length;i++){
              if (arr[i].photos !== undefined){
                if (arr[i].photos[0]['width'] > 1000) {
                  photoArr.push(arr[i].photos[0]['photo_reference'])
                }
              }
            }
            var photoUrlArr = []
            for (var i=0;i<photoArr.length;i++){
              photoUrlArr.push('https://maps.googleapis.com/maps/api/place/photo?maxwidth=1600&photoreference='+photoArr[i]+'&key='+googleKey+'')
            }
            response.json({photos: photoUrlArr})
          })
    })
  })

// PANARAMIO PHOTO ROUTE:

router.route('/panaramio/:user_id')
  .get(function(request, response){
    User.findById(request.params.user_id, function(error, user){
      if (error)
        response.send(error)
      else
        console.log(user.geocoordinates)
        var lat     = user.geocoordinates.split(",")[0]
        var lng     = user.geocoordinates.split(",")[1]

        var latMin  = (parseFloat(lat) - 0.5).toString()
        var latMax  = (parseFloat(lat) + 0.5).toString()
        var lngMin  = (parseFloat(lng) - 0.5).toString()
        var lngMax  = (parseFloat(lng) + 0.5).toString()

          http({
            url:'http://www.panoramio.com/map/get_panoramas.php?set=public&from=0&to=20&minx='+lngMin+'&miny='+latMin+'&maxx='+lngMax+'&maxy='+latMax+'&size=original&mapfilter=false',
            method:"GET"
          },function(error, res, body){
            // console.log(JSON.parse(body).photos[0].photo_file_url)
            var photoArr = JSON.parse(body).photos
            var filteredPhotos = []
            for (var i = 0; i < photoArr.length; i++) {
              if (photoArr[i].width > 1000 && photoArr[i].width < 2000) {
                filteredPhotos.push(photoArr[i])
              }
            }
            var photoListCollection = []
            for (var i=0;i<filteredPhotos.length;i++){
              photoListCollection.push({
                photo_title:  filteredPhotos[i].photo_title,
                photo_url:    filteredPhotos[i].photo_file_url,
                owner_name:   filteredPhotos[i].owner_name,
                owner_url:    filteredPhotos[i].owner_url
              })
            }
            response.json({photos: photoListCollection})
          })
    })
  })

//WEATHER ROUTE:

router.route('/weather/:user_id')
  .get(function(request, response) {
    User.findById(request.params.user_id, function(error, user){
      var city = user.city
      http({
        url: 'http://api.openweathermap.org/data/2.5/weather?q='+city+'',
        method: "GET"
      }, function(error, res, body){
        response.json({weather: JSON.parse(body)})
      })
    })
  })

//TIME ROUTE:

router.route('/time/:user_id')
  .get(function(request, response) {

    User.findById(request.params.user_id, function(error, user){
      var coordArr = user.geocoordinates.split(",")
      var lat = coordArr[0]
      var lng = coordArr[1]
      http({
        url: 'http://api.geonames.org/timezoneJSON?lat='+lat+'&lng='+lng+'&username=fantastic_nomadr',
        method: "GET"
      }, function(error, res, body){
        // FFFFF
        response.json({time: JSON.parse(body).time.substring(11)})
      })
    })
  })

//EVENTBRIGHT ROUTE
router.route('/events/:user_id')
  .get(function(request, response){
    console.log(request.params.user_id)
    User.findById(request.params.user_id, function(error, user){

      http({
        url: 'https://www.eventbrite.com/json/event_search?app_key=' + eventBrightKey + '&city=' + user.city + '&date=This+month',
        method: 'GET'
      }, function(error, resp, body){
        var eventArr = JSON.parse(body)
        eventArr.events.shift()
        var filteredArr = []

        // console.log(eventArr.events)
        for(var i=0;i<eventArr.events.length;i++){
          filteredArr.push({
            url:    eventArr.events[i].event.url,
            title:  eventArr.events[i].event.title
          })
        }
        response.json({events: filteredArr})
      })
    })
  })

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);


text:
    module.exports = header: 'OpenLDAP Client Wait', handler: ({options}) ->

      @connection.wait
        header: 'TCP'
        servers: options.tcp


text:
<?php

/*
 * This file is part of php-task library.
 *
 * (c) php-task
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Task\Tests\Unit\Lock;

use PHPUnit\Framework\TestCase;
use Task\Lock\Exception\LockConflictException;
use Task\Lock\Lock;
use Task\Lock\LockInterface;
use Task\Lock\LockStorageInterface;

class LockTest extends TestCase
{
    /**
     * @var LockStorageInterface
     */
    private $storage;

    /**
     * @var int
     */
    private $ttl = 300;

    /**
     * @var LockInterface
     */
    private $lock;

    /**
     * @var string
     */
    private $key = 'test-key';

    protected function setUp(): void
    {
        $this->storage = $this->prophesize(LockStorageInterface::class);

        $this->lock = new Lock($this->storage->reveal(), $this->ttl);
    }

    public function testAcquire()
    {
        $this->storage->exists($this->key)->willReturn(false);
        $this->storage->save($this->key, $this->ttl)->shouldBeCalled()->willReturn(true);

        $this->assertTrue($this->lock->acquire($this->key));
    }

    public function testAcquireAlreadyAcquired()
    {
        $this->expectException(LockConflictException::class);

        $this->storage->exists($this->key)->willReturn(true);
        $this->storage->save($this->key, $this->ttl)->shouldNotBeCalled();

        $this->lock->acquire($this->key);
    }

    public function testRefresh()
    {
        $this->storage->exists($this->key)->willReturn(true);
        $this->storage->save($this->key, $this->ttl)->shouldBeCalled()->willReturn(true);

        $this->assertTrue($this->lock->refresh($this->key));
    }

    public function testRefreshNotAcquired()
    {
        $this->expectException(LockConflictException::class);

        $this->storage->exists($this->key)->willReturn(false);
        $this->storage->save($this->key, $this->ttl)->shouldNotBeCalled();

        $this->assertTrue($this->lock->refresh($this->key));
    }

    public function testRelease()
    {
        $this->storage->exists($this->key)->willReturn(true);
        $this->storage->delete($this->key)->shouldBeCalled()->willReturn(true);

        $this->assertTrue($this->lock->release($this->key));
    }

    public function testReleaseNotAcquired()
    {
        $this->expectException(LockConflictException::class);

        $this->storage->exists($this->key)->willReturn(false);
        $this->storage->delete($this->key)->shouldNotBeCalled();

        $this->assertTrue($this->lock->release($this->key));
    }
}


text:
/*****************************************************************************
 * CVS File Information :
 *    $RCSfile$
 *    Author: kddevin $
 *    Date: 2008/09/26 03:29:02 $
 *    Revision: 1.2 $
 ****************************************************************************/
/* mpi_config.h generated by Karen Devine  1 March 2005 */
/* For now, just manually define the values.  We may do
 * something more intelligent later (particularly wrt fortran mangling)
 * based on Mitchell's F90 interface for Zoltan.
 *
 * Only values that appear to actually be used in the code are defined here.
 */

/* C equivalent of FORTRAN DOUBLE PRECISION */
#define MPI_FORTRAN_DOUBLE double

/* C equivalent of FORTRAN INTEGER */
#define MPI_FORTRAN_INTEGER int

/* Mangling template */
#define MPI_FORTRAN_MANGLING_PATTERNS "_"

/* Version number of package */
#define SIMPI_VERSION 0.1a9


text:
using System.Collections.Generic;

namespace Azure.Management.Compute.Models
{
    /// <summary> Describes a virtual machine scale set network profile. </summary>
    public partial class VirtualMachineScaleSetUpdateNetworkProfile
    {
        /// <summary> Initializes a new instance of VirtualMachineScaleSetUpdateNetworkProfile. </summary>
        public VirtualMachineScaleSetUpdateNetworkProfile()
        {
        }

        /// <summary> Initializes a new instance of VirtualMachineScaleSetUpdateNetworkProfile. </summary>
        /// <param name="healthProbe"> A reference to a load balancer probe used to determine the health of an instance in the virtual machine scale set. The reference will be in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}'. </param>
        /// <param name="networkInterfaceConfigurations"> The list of network configurations. </param>
        internal VirtualMachineScaleSetUpdateNetworkProfile(ApiEntityReference healthProbe, IList<VirtualMachineScaleSetUpdateNetworkConfiguration> networkInterfaceConfigurations)
        {
            HealthProbe = healthProbe;
            NetworkInterfaceConfigurations = networkInterfaceConfigurations;
        }

        /// <summary> A reference to a load balancer probe used to determine the health of an instance in the virtual machine scale set. The reference will be in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/loadBalancers/{loadBalancerName}/probes/{probeName}'. </summary>
        public ApiEntityReference HealthProbe { get; set; }
        /// <summary> The list of network configurations. </summary>
        public IList<VirtualMachineScaleSetUpdateNetworkConfiguration> NetworkInterfaceConfigurations { get; set; }
    }
}


text:
import upperFirst from '../src/upperFirst';

describe('upperFirst', () => {
  test('should return undefined for undefined', () => {
    expect(upperFirst(undefined)).toBe(undefined);
  });

  test('should return null for null', () => {
    expect(upperFirst(null)).toBe(null);
  });

  test('should return empty string when empty string', () => {
    expect(upperFirst('')).toBe('');
  });

  test('should return string with first char upperFirstd', () => {
    expect(upperFirst('reactpdf')).toBe('Reactpdf');
  });
});


text:
import { RootFolderNode as Tree } from "./interfaces";
import { cloneAndClimb } from "./climb";
import { Color, SpecialStatus, TaggedSequence } from "farmbot";
import { store } from "../redux/store";
import { initSave, destroy, edit, save, init } from "../api/crud";
import { Folder } from "farmbot/dist/resources/api_resources";
import { DeepPartial } from "redux";
import { findFolderById } from "../resources/selectors_by_id";
import { Actions } from "../constants";
import { t } from "../i18next_wrapper";
import { push } from "../history";
import { urlFriendly } from "../util";
import { setActiveSequenceByName } from "../sequences/set_active_sequence_by_name";
import { stepGet, STEP_DATATRANSFER_IDENTIFER } from "../draggable/actions";
import { joinKindAndId } from "../resources/reducer_support";
import { maybeGetSequence } from "../resources/selectors";
import { sequencesUrlBase } from "./component";

type TreePromise = Promise<Tree>;

export const collapseAll = (tree: Tree): TreePromise => {
  return Promise.resolve(cloneAndClimb(tree, (node) => {
    node.open = false;
  }));
};

export const setFolderColor = (id: number, color: Color) => {
  const d = store.dispatch as Function;
  const f = findFolderById(store.getState().resources.index, id);

  d(edit(f, { color }));
  d(save(f.uuid));
};

export const setFolderName = (id: number, folderName: string) => {
  const d = store.dispatch as Function;
  const { index } = store.getState().resources;
  const folder = findFolderById(index, id);
  const action = edit(folder, { name: folderName });
  d(action);
  return d(save(folder.uuid)) as Promise<{}>;
};

const DEFAULTS = (): Folder => ({
  name: t("New Folder"),
  color: "gray",
  parent_id: 0,
});

export const addNewSequenceToFolder = (folder_id?: number) => {
  const uuidMap = store.getState().resources.index.byKind["Sequence"];
  const seqCount = Object.keys(uuidMap).length;
  const newSequence = {
    name: t("new sequence {{ num }}", { num: seqCount }),
    args: {
      version: -999,
      locals: { kind: "scope_declaration", args: {} },
    },
    color: "gray",
    folder_id,
    kind: "sequence",
    body: []
  };
  store.dispatch(init("Sequence", newSequence));
  push(sequencesUrlBase() + urlFriendly(newSequence.name));
  setActiveSequenceByName();
};

export const createFolder = (config: DeepPartial<Folder> = {}) => {
  const d: Function = store.dispatch;
  const folder: Folder = { ...DEFAULTS(), ...config };
  const action = initSave("Folder", folder);
  // tslint:disable-next-line:no-any
  const p: Promise<{}> = d(action);
  return p;
};

export const deleteFolder = (id: number) => {
  const d: Function = store.dispatch;
  const { index } = store.getState().resources;
  const folder = findFolderById(index, id);
  const action = destroy(folder.uuid);

  return d(action) as ReturnType<typeof action>;
};

export const updateSearchTerm = (payload: string | undefined) =>
  store.dispatch({ type: Actions.FOLDER_SEARCH, payload });

export const toggleFolderOpenState = (id: number) =>
  store.dispatch({ type: Actions.FOLDER_TOGGLE, payload: { id } });

export const toggleFolderEditState = (id: number) =>
  store.dispatch({ type: Actions.FOLDER_TOGGLE_EDIT, payload: { id } });

export const toggleAll = (payload: boolean) =>
  store.dispatch({ type: Actions.FOLDER_TOGGLE_ALL, payload });

export const sequenceEditMaybeSave =
  (sequence: TaggedSequence, update: Partial<TaggedSequence["body"]>) => {
    const dispatch: Function = store.dispatch;
    dispatch(edit(sequence, update));
    if (sequence.specialStatus == SpecialStatus.SAVED) {
      dispatch(save(sequence.uuid));
    }
  };

export function moveSequence(sequenceUuid: string, folder_id: number) {
  const s = store.getState().resources.index.references[sequenceUuid];
  if (s && s.kind === "Sequence") {
    sequenceEditMaybeSave(s, { folder_id });
  }
}

export const dropSequence = (folder_id: number) =>
  (e: React.DragEvent<HTMLElement>) => {
    const key = e.dataTransfer.getData(STEP_DATATRANSFER_IDENTIFER);
    const dispatch: Function = store.dispatch;
    const dataXferObj = dispatch(stepGet(key));
    const { sequence_id } = dataXferObj.value.args;
    const ri = store.getState().resources.index;
    const seqUuid = dataXferObj.resourceUuid ||
      ri.byKindAndId[joinKindAndId("Sequence", sequence_id)];
    const sequence = maybeGetSequence(ri, seqUuid);
    if (sequence) { sequenceEditMaybeSave(sequence, { folder_id }); }
  };


text:
<?php

require __DIR__.'/autoload.php';

use LaravelLb\LogicBoxesTransaction;

use Carbon\Carbon;

// Setup user id and api key
$userId = getenv('LB_AUTH_USERID');
$apiKey = getenv('LB_API_KEY');

$transaction = new LogicBoxesTransaction();

/** No need to set user id if you're using Laravel, it will automatically get the credential from config/logicboxes.php */
$transaction->setUserId($userId)->setApiKey($apiKey);

$from = Carbon::parse('01/01/2016');
$to = Carbon::parse('01/31/2016');

$response = $transaction->getCustomerTransactions($from, $to);
print_r($response);


text:
<link rel="import" href="fab-behavior.html">
<link rel="import" href="fab-container.html">
<link rel="import" href="fab-element.html">


text:
using System;
using System.Threading;

namespace Issuna.Core
{
    [Serializable]
    public struct CatkinId : IComparable<CatkinId>, IEquatable<CatkinId>
    {
        public const int ReservedBits = 1;   // 1 bit reserved, 0 by default
        public const int TimestampBits = 41; // 41 bits timestamp with milliseconds, max 2199023255551, 2199023255551/31536000000 = 69.73 years
        public const int RegionBits = 4;     // 4 bits covers 16 regions
        public const int MachineBits = 5;    // 5 bits covers 32 servers
        public const int SequenceBits = 13;  // 13 bits covers 8192/millisecond

        public const int SequenceShift = 0;
        public const int MachineShift = SequenceShift + SequenceBits;
        public const int RegionShift = MachineShift + MachineBits;
        public const int TimestampShift = RegionShift + RegionBits;
        public const int ReservedShift = TimestampShift + TimestampBits;

        public const int ReservedMask = -1 ^ (-1 << ReservedBits);
        public const long TimestampMask = -1L ^ (-1L << TimestampBits);
        public const int RegionMask = -1 ^ (-1 << RegionBits);
        public const int MachineMask = -1 ^ (-1 << MachineBits);
        public const int SequenceMask = -1 ^ (-1 << SequenceBits);

        public const int MaxReserved = -1 ^ (-1 << ReservedBits);
        public const long MaxTimestamp = -1L ^ (-1L << TimestampBits);
        public const int MaxRegion = -1 ^ (-1 << RegionBits);
        public const int MaxMachine = -1 ^ (-1 << MachineBits);
        public const int MaxSequence = -1 ^ (-1 << SequenceBits);

        private static int __staticSequence = (new Random()).Next();

        private byte _reserved;
        private byte _region;
        private ushort _machine;
        private long _timestamp;
        private int _sequence;

        public CatkinId(long id)
        {
            Unpack(id, out _reserved, out _timestamp, out _region, out _machine, out _sequence);
        }

        public CatkinId(byte reserved, long timestamp, byte region, ushort machine, int sequence)
        {
            SanityCheck(reserved, timestamp, region, machine, sequence);

            _reserved = reserved;
            _timestamp = timestamp;
            _region = region;
            _machine = machine;
            _sequence = sequence;
        }

        public byte Reserved { get { return _reserved; } }
        public long Timestamp { get { return _timestamp; } }
        public byte Region { get { return _region; } }
        public ushort Machine { get { return _machine; } }
        public int Sequence { get { return _sequence; } }
        public DateTime CreationTime { get { return CatkinIdTimer.ToDateTimeFromMillisecondsSinceCatkinIdEpoch(Timestamp); } }

        public long ToLong()
        {
            return Pack(Reserved, Timestamp, Region, Machine, Sequence);
        }

        public static long Pack(byte reserved, long timestamp, byte region, ushort machine, int sequence)
        {
            SanityCheck(reserved, timestamp, region, machine, sequence);

            long id = 0;

            id |= ((long)(reserved & ReservedMask)) << ReservedShift;
            id |= ((long)(timestamp & TimestampMask)) << TimestampShift;
            id |= ((long)(region & RegionMask)) << RegionShift;
            id |= ((long)(machine & MachineMask)) << MachineShift;
            id |= ((long)(sequence & SequenceMask)) << SequenceShift;

            return id;
        }

        public static void Unpack(long catkinId, out byte reserved, out long timestamp, out byte region, out ushort machine, out int sequence)
        {
            reserved = (byte)((catkinId >> ReservedShift) & ReservedMask);
            timestamp = (long)((catkinId >> TimestampShift) & TimestampMask);
            region = (byte)((catkinId >> RegionShift) & RegionMask);
            machine = (ushort)((catkinId >> MachineShift) & MachineMask);
            sequence = (int)((catkinId >> SequenceShift) & SequenceMask);
        }

        public static CatkinId Parse(string value)
        {
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            CatkinId catkinId;
            if (TryParse(value, out catkinId))
            {
                return catkinId;
            }
            else
            {
                var message = string.Format("'{0}' is not a valid CatkinId string.", value);
                throw new FormatException(message);
            }
        }

        public static CatkinId Parse(long value)
        {
            return new CatkinId(value);
        }

        public static bool TryParse(string value, out CatkinId catkinId)
        {
            if (!string.IsNullOrEmpty(value))
            {
                long id;
                if (long.TryParse(value, out id))
                {
                    catkinId = new CatkinId(id);
                    return true;
                }
            }

            catkinId = default(CatkinId);
            return false;
        }

        public static bool TryParse(long value, out CatkinId catkinId)
        {
            try
            {
                catkinId = new CatkinId(value);
                return true;
            }
            catch
            {
                catkinId = default(CatkinId);
                return false;
            }
        }

        private static void SanityCheck(byte reserved, long timestamp, byte region, ushort machine, int sequence)
        {
            if (reserved < 0 || MaxReserved < reserved)
            {
                throw new ArgumentOutOfRangeException("reserved",
                    string.Format("The 'reserved' value must be between 0 and {0} (it must fit in {1} bits).",
                        MaxReserved, ReservedBits));
            }
            if (timestamp < 0 || MaxTimestamp < timestamp)
            {
                throw new ArgumentOutOfRangeException("timestamp",
                    string.Format("The 'timestamp' value must be between 0 and {0} (it must fit in {1} bits).",
                        MaxTimestamp, TimestampBits));
            }
            if (region < 0 || MaxRegion < region)
            {
                throw new ArgumentOutOfRangeException("region",
                    string.Format("The 'region' value must be between 0 and {0} (it must fit in {1} bits).",
                        MaxRegion, RegionBits));
            }
            if (machine < 0 || MaxMachine < machine)
            {
                throw new ArgumentOutOfRangeException("machine",
                    string.Format("The 'machine' value must be between 0 and {0} (it must fit in {1} bits).",
                        MaxMachine, MachineBits));
            }
            if (sequence < 0 || MaxSequence < sequence)
            {
                throw new ArgumentOutOfRangeException("sequence",
                    string.Format("The 'sequence' value must be between 0 and {0} (it must fit in {1} bits).",
                        MaxSequence, SequenceBits));
            }
        }

        public static CatkinId GenerateNewId()
        {
            return GenerateNewId(timestamp: (DateTime?)null);
        }

        public static CatkinId GenerateNewId(byte reserved = 0, DateTime? timestamp = null, byte region = 0, ushort machine = 0, int? sequence = null)
        {
            long timestampLong = CatkinIdTimer.GetMillisecondsSinceCatkinIdEpochFromDateTime(timestamp.HasValue ? timestamp.Value : DateTime.UtcNow);

            return GenerateNewId(reserved: reserved, timestamp: timestampLong, region: region, machine: machine, sequence: sequence);
        }

        public static CatkinId GenerateNewId(byte reserved = 0, long? timestamp = null, byte region = 0, ushort machine = 0, int? sequence = null)
        {
            long timestampLong = timestamp.HasValue ? timestamp.Value : CatkinIdTimer.GetMillisecondsSinceCatkinIdEpochFromDateTime(DateTime.UtcNow);

            int sequenceInt = -1;
            if (sequence.HasValue)
            {
                sequenceInt = sequence.Value;
            }
            else
            {
                int increment = Interlocked.Increment(ref __staticSequence);
                sequenceInt = increment & SequenceMask;
            }

            return new CatkinId(reserved, timestampLong, region, machine, sequenceInt);
        }

        public int CompareTo(CatkinId other)
        {
            return ((long)this).CompareTo((long)other);
        }

        public bool Equals(CatkinId other)
        {
            return ((long)this).Equals((long)other);
        }

        public override bool Equals(object obj)
        {
            if (obj is CatkinId)
            {
                return Equals((CatkinId)obj);
            }
            else
            {
                return false;
            }
        }

        public override int GetHashCode()
        {
            return ((long)this).GetHashCode();
        }

        public override string ToString()
        {
            return ((long)this).ToString();
        }

        public string ToText()
        {
            return string.Format("Reserved[{0}], Timestamp[{1}], Region[{2}], Machine[{3}], Sequence[{4}]",
                Reserved, Timestamp, Region, Machine, Sequence);
        }

        public static explicit operator long(CatkinId catkinId)
        {
            return catkinId.ToLong();
        }

        public static explicit operator string(CatkinId catkinId)
        {
            return catkinId.ToString();
        }

        public static bool operator <(CatkinId left, CatkinId right)
        {
            return left.CompareTo(right) < 0;
        }

        public static bool operator <=(CatkinId left, CatkinId right)
        {
            return left.CompareTo(right) <= 0;
        }

        public static bool operator ==(CatkinId left, CatkinId right)
        {
            return left.Equals(right);
        }

        public static bool operator !=(CatkinId left, CatkinId right)
        {
            return !(left == right);
        }

        public static bool operator >=(CatkinId left, CatkinId right)
        {
            return left.CompareTo(right) >= 0;
        }

        public static bool operator >(CatkinId left, CatkinId right)
        {
            return left.CompareTo(right) > 0;
        }

        internal static class CatkinIdTimer
        {
            private static readonly DateTime __unixEpoch;
            private static readonly long __dateTimeMaxValueSecondsSinceEpoch;
            private static readonly long __dateTimeMinValueSecondsSinceEpoch;
            private static readonly long __dateTimeMaxValueMillisecondsSinceEpoch;
            private static readonly long __dateTimeMinValueMillisecondsSinceEpoch;

            private static readonly DateTime __catkinIdEpoch;
            private static readonly long __catkinIdEpochOffsetBySeconds; // 1483228800

            static CatkinIdTimer()
            {
                __unixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                __dateTimeMaxValueSecondsSinceEpoch = (DateTime.MaxValue - __unixEpoch).Ticks / 10000 / 1000;
                __dateTimeMinValueSecondsSinceEpoch = (DateTime.MinValue - __unixEpoch).Ticks / 10000 / 1000;
                __dateTimeMaxValueMillisecondsSinceEpoch = (DateTime.MaxValue - __unixEpoch).Ticks / 10000;
                __dateTimeMinValueMillisecondsSinceEpoch = (DateTime.MinValue - __unixEpoch).Ticks / 10000;

                __catkinIdEpoch = new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                __catkinIdEpochOffsetBySeconds = (__catkinIdEpoch - __unixEpoch).Ticks / 10000 / 1000;
            }

            public static long DateTimeMaxValueSecondsSinceEpoch
            {
                get { return __dateTimeMaxValueSecondsSinceEpoch; }
            }

            public static long DateTimeMinValueSecondsSinceEpoch
            {
                get { return __dateTimeMinValueSecondsSinceEpoch; }
            }

            public static long DateTimeMaxValueMillisecondsSinceEpoch
            {
                get { return __dateTimeMaxValueMillisecondsSinceEpoch; }
            }

            public static long DateTimeMinValueMillisecondsSinceEpoch
            {
                get { return __dateTimeMinValueMillisecondsSinceEpoch; }
            }

            public static DateTime UnixEpoch { get { return __unixEpoch; } }

            public static DateTime CatkinIdEpoch { get { return __catkinIdEpoch; } }

            public static long CatkinIdEpochOffsetBySeconds { get { return __catkinIdEpochOffsetBySeconds; } }

            public static DateTime ToUniversalTime(DateTime dateTime)
            {
                if (dateTime == DateTime.MinValue)
                {
                    return DateTime.SpecifyKind(DateTime.MinValue, DateTimeKind.Utc);
                }
                else if (dateTime == DateTime.MaxValue)
                {
                    return DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc);
                }
                else
                {
                    return dateTime.ToUniversalTime();
                }
            }

            public static DateTime ToDateTimeFromSecondsSinceEpoch(long secondsSinceEpoch)
            {
                if (secondsSinceEpoch < DateTimeMinValueSecondsSinceEpoch ||
                    secondsSinceEpoch > DateTimeMaxValueSecondsSinceEpoch)
                {
                    throw new ArgumentOutOfRangeException("secondsSinceEpoch");
                }

                if (secondsSinceEpoch == DateTimeMaxValueSecondsSinceEpoch)
                {
                    return DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc);
                }
                else
                {
                    return UnixEpoch.AddTicks(secondsSinceEpoch * 1000 * 10000);
                }
            }

            public static DateTime ToDateTimeFromMillisecondsSinceEpoch(long millisecondsSinceEpoch)
            {
                if (millisecondsSinceEpoch < DateTimeMinValueMillisecondsSinceEpoch ||
                    millisecondsSinceEpoch > DateTimeMaxValueMillisecondsSinceEpoch)
                {
                    throw new ArgumentOutOfRangeException("millisecondsSinceEpoch");
                }

                if (millisecondsSinceEpoch == DateTimeMaxValueMillisecondsSinceEpoch)
                {
                    return DateTime.SpecifyKind(DateTime.MaxValue, DateTimeKind.Utc);
                }
                else
                {
                    return UnixEpoch.AddTicks(millisecondsSinceEpoch * 10000);
                }
            }

            public static long GetSecondsSinceEpochFromDateTime(DateTime dateTime)
            {
                var secondsSinceEpoch = (long)Math.Floor((ToUniversalTime(dateTime) - UnixEpoch).TotalSeconds);
                if (secondsSinceEpoch < long.MinValue || secondsSinceEpoch > long.MaxValue)
                {
                    throw new ArgumentOutOfRangeException("dateTime");
                }
                return secondsSinceEpoch;
            }

            public static long GetMillisecondsSinceEpochFromDateTime(DateTime dateTime)
            {
                var millisecondsSinceEpoch = (long)Math.Floor((ToUniversalTime(dateTime) - UnixEpoch).TotalMilliseconds);
                if (millisecondsSinceEpoch < long.MinValue || millisecondsSinceEpoch > long.MaxValue)
                {
                    throw new ArgumentOutOfRangeException("dateTime");
                }
                return millisecondsSinceEpoch;
            }

            public static DateTime ToDateTimeFromSecondsSinceCatkinIdEpoch(long secondsSinceCatkinIdEpoch)
            {
                return ToDateTimeFromSecondsSinceEpoch(CatkinIdEpochOffsetBySeconds + secondsSinceCatkinIdEpoch);
            }

            public static DateTime ToDateTimeFromMillisecondsSinceCatkinIdEpoch(long millisecondsSinceCatkinIdEpoch)
            {
                return ToDateTimeFromMillisecondsSinceEpoch((CatkinIdEpochOffsetBySeconds * 1000) + millisecondsSinceCatkinIdEpoch);
            }

            public static long GetSecondsSinceCatkinIdEpochFromDateTime(DateTime dateTime)
            {
                return GetSecondsSinceEpochFromDateTime(dateTime) - CatkinIdEpochOffsetBySeconds;
            }

            public static long GetMillisecondsSinceCatkinIdEpochFromDateTime(DateTime dateTime)
            {
                return GetMillisecondsSinceEpochFromDateTime(dateTime) - (CatkinIdEpochOffsetBySeconds * 1000);
            }
        }
    }
}


text:
<?php

namespace ZFTest\ApiProblem\Listener;

use PHPUnit_Framework_TestCase as TestCase;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\Mvc\Application;
use Zend\Mvc\MvcEvent;
use ZF\ApiProblem\Listener\RenderErrorListener;

class RenderErrorListenerTest extends TestCase
{
    /**
     * @var RenderErrorListener
     */
    protected $listener;

    public function setUp()
    {
        $this->listener = new RenderErrorListener();
    }

    public function testOnRenderErrorCreatesAnApiProblemResponse()
    {
        $response = new Response();
        $request  = new Request();
        $request->getHeaders()->addHeaderLine('Accept', 'application/json');

        $event = new MvcEvent();
        $event->setError(Application::ERROR_EXCEPTION);
        $event->setRequest($request);
        $event->setResponse($response);
        $this->listener->onRenderError($event);

        $this->assertTrue($event->propagationIsStopped());
        $this->assertSame($response, $event->getResponse());

        $this->assertEquals(406, $response->getStatusCode());
        $headers = $response->getHeaders();
        $this->assertTrue($headers->has('Content-Type'));
        $this->assertEquals('application/problem+json', $headers->get('content-type')->getFieldValue());
        $content = json_decode($response->getContent(), true);
        $this->assertArrayHasKey('status', $content);
        $this->assertArrayHasKey('title', $content);
        $this->assertArrayHasKey('describedBy', $content);
        $this->assertArrayHasKey('detail', $content);

        $this->assertEquals(406, $content['status']);
        $this->assertEquals('Not Acceptable', $content['title']);
        $this->assertContains('www.w3.org', $content['describedBy']);
        $this->assertContains('accept', $content['detail']);
    }

    public function testOnRenderErrorHideDetailIfNotApiExeption()
    {
        $code = 500;
        $exception = new \Exception('hidden message', $code);

        $response = new Response();

        $event = new MvcEvent();
        $event->setResponse($response);
        $event->setParam('exception', $exception);

        $this->listener->onRenderError($event);

        $content = json_decode($response->getContent(), true);

        $this->assertFalse(isset($content['detail']));
        $this->assertEquals($code, $content['status']);
    }

    public function testOnRenderErrorShowDetailIfApiExeption()
    {
        $message = 'hidden message';
        $code = 500;
        $exception = new \ZF\ApiProblem\Exception\InvalidArgumentException($message, $code);

        $response = new Response();

        $event = new MvcEvent();
        $event->setResponse($response);
        $event->setParam('exception', $exception);

        $this->listener->onRenderError($event);

        $content = json_decode($response->getContent(), true);

        $this->assertTrue(isset($content['detail']));
        $this->assertEquals($message, $content['detail']);
        $this->assertEquals($code, $content['status']);
    }

}


text:
@{{username}}

{{badges}} Badges earned

{{javascriptPoints}} JavaScript points

search again


text:
package com.sam.neo4j.repository;

import java.util.List;

import org.springframework.data.neo4j.repository.GraphRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.sam.neo4j.domain.Person;

@Service
@Transactional
public interface PersonRepository extends GraphRepository<Person> {

    List<Person> findByLastName(@Param("name") String name);

}


text:
/* Configuration */
export const CONFIG_FILE_TEXT_ENCODING = 'utf8'
export const CONFIG_FILE_NAME = 'RedisViewer.config.json'
export const ENCRYPTED_CONFIG_FILE_NAME = CONFIG_FILE_NAME + '.enc'

/* Encryption */
export const USER_KEY_STORAGE_CONFIG_ENCRYPTION_PASSPHRASE_KEY = 'ConfigEncryptionPassphrase'
export const CONFIG_ENCRYPTION_PASSPHRASE_LENGTH_BYTES = 32

/* Server settings */
export const DEFAULT_SERVER_CONFIG_LIST = []

/* Server list */
export const ROOT_FOLDER_NAME = 'Servers'

/* Output format */
export const JSON_FORMAT_LEADING_SPACE = 2
export const KEY_DATA_LAST_UPDATE_DATE_FORMAT = 'YYYY-MM-DD HH:mm:ss.SSS'

export default {
  CONFIG_FILE_TEXT_ENCODING,
  CONFIG_FILE_NAME,
  ENCRYPTED_CONFIG_FILE_NAME,

  USER_KEY_STORAGE_CONFIG_ENCRYPTION_PASSPHRASE_KEY,
  CONFIG_ENCRYPTION_PASSPHRASE_LENGTH_BYTES,

  DEFAULT_SERVER_CONFIG_LIST,

  ROOT_FOLDER_NAME,

  JSON_FORMAT_LEADING_SPACE,
  KEY_DATA_LAST_UPDATE_DATE_FORMAT
}