text:
 /* global document, window, CustomEvent */
 'use strict';

 var vcr = function(config, options) {
     this.set(config, options);
 };

 vcr.prototype = {

     vimeo: require('./lib/vimeo'),

     youtube: require('./lib/yt'),

     parser: require('./lib/parser'),

     parsedData: null,

     videoData: null,

     el: null,

     player: null,

     config: '',

     setVideoType: function() {
         if (this.parsedData !== undefined) {
             this.videoData = (this.parsedData.type === 'vimeo') ? new this.vimeo() : (this.parsedData.type === 'youtube') ? new this.youtube() : '';
         }
     },

     setListeners: function() {
         var self = this,
             events = ['play', 'pause', 'seek', 'volume', 'mute', 'stop'];

         for (var i = 0; i < events.length; i++) {
             makeListener(events[i]);
         }

         function makeListener(arg1) {
             self.player.addEventListener('vcr:' + arg1, function() {
                 self[arg1]();
             });
         }

         //Event listener to start playing
         this.player.addEventListener('vcr:play', function() {
             self.play();
         });

         this.player.addEventListener('vcr:pause', function() {
             self.pause();
         });

         this.player.addEventListener('vcr:stop', function() {
             self.stop();
         });

         this.player.addEventListener('vcr:seek', function(e) {
             self.seek(e.detail.seek);
         });

         this.player.addEventListener('vcr:volume', function(e) {
             self.seek(e.detail.volume);
         });

         this.player.addEventListener('vcr:currentTime', function(e) {
             return self.currentTime();
         });

         this.player.addEventListener('vcr:duration', function(e) {
             return self.duration();
         });
     },

     set: function(config, options) {
         var url, element;
         this.config = config;
         // if it's an object, then we know it doesn't have
         if (config instanceof Object) {
             // If an element is given, then keep it, otherwise make up a vcr name and create the element!
             element = (config.el) ? config.el : 'vcrPlayer' + Math.floor(Math.random() * 6000) + 1;
             url = (config.url) ? config.url : '';
             if (element && config.url && document.querySelector('#' + config.el) === null) {
                 this.whereToPut(element, config);
             } else if (element && !config.url) {
                 element = config.el;
                 url = document.getElementById(element).src;
             } else {
                 console.error('Hmm, I don\'t think you added an element id or url...');
             }
             this.el = element;

             // If the user inputted a URL, that means we want to create an iframe, otherwise, config is just an element ID that we can use
         } else {
             element = config;
             url = document.getElementById(element).src;
             this.el = element;
         }

         var self = this,
             playerParams = (options && options.parameters) ? options.parameters : {};

         // First we'll parse the data properly, then see if it's a youtube/ vimeo/html5 video.
         this.parsedData = this.parser.parse(url);

         this.setVideoType();

         var type = this.videoData,
             id = this.parsedData.id;

         if (options && options.autoplay) {
             playerParams.autoplay = 1;
         }
         if (type !== '') {

             this.player = document.getElementById(this.el);
             // Initial viewport check

             this.player.addEventListener('vcr:ready',
                 function() {
                     if (options && options.scrollStop) {
                         self.throttleVideo();
                         var throttler = self.debounce(self.throttleVideo, 250);
                         window.addEventListener('scroll', throttler);
                     }
                 });
             playerParams = this.setOptions(playerParams);

             this.videoData.setPlayer(id, element, playerParams);
             this.setListeners();
             this.setConfigDimensions();

         }
     },

     setConfigDimensions: function() {
         if (this.player) {
             var iframe = this.player,
                 config = this.config;
             iframe.width = (config.width && !iframe.width) ? config.width : iframe.width;
             iframe.height = (config.height && !iframe.height) ? config.height : iframe.height;
         }
     },

     whereToPut: function(el, config) {

         var c = config,
             // Create a new iframe!
             frame = document.createElement('iframe');

         frame.id = el;
         frame = frame.outerHTML;
         // Probably could be refactored somehow. Suggestions welcome!
         if (c.insertBefore) {
             document.querySelector(c.insertBefore).insertAdjacentHTML('beforebegin', frame);
         } else if (c.insertAfter) {
             document.querySelector(c.insertAfter).insertAdjacentHTML('afterEnd', frame);
         } else if (c.appendTo) {
             document.querySelector(c.appendTo).insertAdjacentHTML('beforeend', frame);
         } else if (c.prependTo) {
             document.querySelector(c.prependTo).insertAdjacentHTML('afterbegin', frame);
         } else {
             document.body.insertAdjacentHTML('afterbegin', frame);
         }
     },

     setOptions: function(params) {
         var queso = require('queso');
         return queso.stringify(params, true);
     },

     play: function() {
         // Event emitted when played
         this.fireEvent('playing');
         this.videoData.play();
     },

     pause: function() {
         this.fireEvent('paused');
         this.videoData.pause();
     },

     seek: function(duration) {
         this.fireEvent('sought');
         this.videoData.seek(duration);
     },

     volume: function(value) {
         this.fireEvent('volumeChanged');
         this.videoData.setVolume(value);
     },

     currentTime: function() {
         this.fireEvent('currentTime');
         return this.videoData.getCurrentTime();
     },

     duration: function() {
         this.fireEvent('durationTime');
         return this.videoData.getDuration();
     },

     mute: function() {
         this.fireEvent('muted');
         this.volume(0);
     },

     stop: function() {
         this.fireEvent('stopped');
         var self = this;
         self.videoData.stop();
     },

     customFn: function(functionName, argArray) {
         argArray = (argArray.length > 0) ? argArray : [];
         this.videoData.customFn(functionName, argArray);
     },

     fireEvent: function(arg) {
         var e = new CustomEvent('vcr:' + arg);
         this.player.dispatchEvent(e);
     },

     // MIGHT PUT IN SEPARATE UTIL FOLDER

     throttleVideo: function() {
         if (this.withinViewport(this.el) === false) {
             this.pause();
         } else {
             this.play();
         }

     },

     debounce: function(func, wait, immediate) {
         var timeout, context = this;
         return function() {
             var args = arguments;
             var later = function() {
                 timeout = null;
                 if (!immediate) {
                     func.apply(context, args);
                 }
             };
             var callNow = immediate && !timeout;
             clearTimeout(timeout);
             timeout = setTimeout(later, wait);
             if (callNow) {
                 func.apply(context, args);
             }
         };
     },

     // TODO: FIX THIS FOR SMALLER SCREENS
     withinViewport: function(el) {
         var element = document.getElementById(el),
             rect = element.getBoundingClientRect(),
             oneThird = element.offsetHeight / 3,
             leftover = window.innerHeight - rect.top;
         return (rect.top > 0 && leftover > (element.offsetHeight / 2) || (rect.top < (element.offsetHeight - oneThird) && rect.bottom >= oneThird));
     }

     // TODO: Implement this at some other time
     // rewind: function(value){},

     // fastForward: function(value) {
     //     var self = this;

     //     this.pause();

     //     this.currentTime();

     //     document.addEventListener('vcr:getCurrentTime', function(event) {
     //         self.seek(event.detail.time + value);
     //     });

     //     // document.addEventListener('vcr:fastForward', function(e) {
     //     //     console.log(e.detail);
     //     // });
     //     //});
     //     // In second

     // }
 };

 window.vcr = vcr;

 module.exports = vcr;


text:
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

#nullable enable

using Microsoft.CodeAnalysis.LanguageServices;

namespace Microsoft.CodeAnalysis.Shared.Extensions
{
    internal static class SpecialTypeExtensions
    {
        public static PredefinedType ToPredefinedType(this SpecialType specialType)
        {
            switch (specialType)
            {
                case SpecialType.System_Object:
                    return PredefinedType.Object;
                case SpecialType.System_Void:
                    return PredefinedType.Void;
                case SpecialType.System_Boolean:
                    return PredefinedType.Boolean;
                case SpecialType.System_Char:
                    return PredefinedType.Char;
                case SpecialType.System_SByte:
                    return PredefinedType.SByte;
                case SpecialType.System_Byte:
                    return PredefinedType.Byte;
                case SpecialType.System_Int16:
                    return PredefinedType.Int16;
                case SpecialType.System_UInt16:
                    return PredefinedType.UInt16;
                case SpecialType.System_Int32:
                    return PredefinedType.Int32;
                case SpecialType.System_UInt32:
                    return PredefinedType.UInt32;
                case SpecialType.System_Int64:
                    return PredefinedType.Int64;
                case SpecialType.System_UInt64:
                    return PredefinedType.UInt64;
                case SpecialType.System_Decimal:
                    return PredefinedType.Decimal;
                case SpecialType.System_Single:
                    return PredefinedType.Single;
                case SpecialType.System_Double:
                    return PredefinedType.Double;
                case SpecialType.System_String:
                    return PredefinedType.String;
                case SpecialType.System_DateTime:
                    return PredefinedType.DateTime;
                default:
                    return PredefinedType.None;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.spacechase0.minecraft.toxicrain;

public class CommonProxy
{
}


text:
SPI2C
=========

Project to use SPI and I2C in Arduino boards


text:
<?php

namespace CampaignChain\CoreBundle\Entity;

interface LinkInterface extends \Mremi\UrlShortener\Model\LinkInterface
{

}


text:
const PRODUCTION = 'production';
const DEVELOPMENT = 'development';

/*
Mode priority:
    - Mode flag
    - Mode from config
    - Mode form NODE_ENV
*/

/**
 *
 * @param {string} mode - mode flag value
 * @param {Object} configObject - contains relevant loaded config
 */
const assignMode = (mode, configObject) => {
    const {
        env: { NODE_ENV },
    } = process;
    const { mode: configMode } = configObject;
    let finalMode;
    if (mode) {
        finalMode = mode;
    } else if (configMode) {
        finalMode = configMode;
    } else if (NODE_ENV && (NODE_ENV === PRODUCTION || NODE_ENV === DEVELOPMENT)) {
        finalMode = NODE_ENV;
    } else {
        finalMode = PRODUCTION;
    }
    return { mode: finalMode };
};

/**
 *
 * @param {Object} args - parsedArgs from the CLI
 * @param {Object | Array} configOptions - Contains loaded config or array of configs
 */
const resolveMode = (args, configOptions) => {
    const { mode } = args;
    let resolvedMode;
    if (Array.isArray(configOptions)) {
        resolvedMode = configOptions.map((configObject) => assignMode(mode, configObject));
    } else resolvedMode = assignMode(mode, configOptions);

    return { options: resolvedMode };
};

module.exports = resolveMode;


text:
<!DOCTYPE html>

By accessing or using this site, you agree to the following terms and conditions:

Participation in Online Anxiety Intervention Study

These Terms and Conditions supplement the Consent Agreement that you will sign as a research study
                    participant, during the term of your active participation in the Study.  If any provision in the
                    Consent Agreement conflicts with these Terms and Conditions, the provision in the Consent Agreement
                    applies to your participation in the Study, not the conflicting provision in these Terms and
                    Conditions.  If you are a former participant in the research study and are accessing this site to do
                    the exercises on your own, please see "Information for Former Study Participants" below.

Diagnostic & Treatment Information

Please see the Consent Agreement if you are a current research study participant.  If you are a former participant in the research study and are accessing this site to do the exercises on your own, please see "Information for Former Study Participants" below.

Gift Cards

The awarding of gift cards for completion of the research study assessments will be
                    available while supplies lasts.

Links to Other Sites

Some MindTrails web pages may link to those of other organizations. Appearance of a website link here
                    does not imply an endorsement of their views, policies or products. Once you click on a link to
                    another site, you are subject to its privacy policy. MindTrails has not participated in the
                    development of the sites of other organizations and does not exert any control over the content of
                    those sites. MindTrails is not responsible for the accuracy or content of information contained in
                    those sites.

Links From Other Sites

MindTrails does not exert any control over the content of sites linking to the MindTrails website.
                    MindTrails is not responsible for the accuracy or content of information contained in those sites.

Pop-Up Advertisements

When visiting our site, your Web browser may produce "pop-up" advertisements (advertisements that
                    spontaneously appear on your computer screen).  The most likely source of such an advertisement is
                    another website you visited or third-party software on your computer. MindTrails does not endorse or
                    recommend products or services featured in advertisements that "pop up" during your visit to our
                    site.

Ownership and Use of this Site

The Mindtrails website and all intellectual property associated with it is owned by the University of
                    Virginia, and may not be used, reproduced or distributed for any commercial purpose. It may be used
                    for non-commercial purposes, such as educational or research purposes, only with prior written
                    permission. To apply for permission, contact studyteam@mindtrails.org.

Information for Former Study Participants

If you are a former research study participant and wish to access mental health resources, please
                    click on the "Mental Health Resources" tab at the top of this webpage. If you need to contact the MindTrails team, please email studyteam@mindtrails.org.

Diagnosis and Treatment

This site does not provide personalized diagnostic, medical or treatment advice.  You should
                        consult with a qualified mental health or health care provider for diagnosis and treatment
                        information.  We do not offer crisis management or real-time monitoring of email.  If you are
                        experiencing a medical or mental health emergency, you should not rely on any information on
                        this website, and should seek appropriate emergency medical assistance, such as by calling
                        911.

Disclaimer

The creators and owner of Mindtrails are not responsible for, and disclaim all liability for
                        damages of any kind arising out of participation in the tests, the training programs, and other
                        general interest and educational use of this site, or reference to or reliance on any
                        information contained within this site.  The user's use of this website is at the user's sole
                        risk.

Release

In consideration for being permitted to use this site, you agree that all use of this site shall
                        be undertaken at your own risk, and that the University of Virginia, its officers, agents and
                        employees shall not be liable for any claims, damages, injuries, actions, or causes of action
                        whatsoever, to you or to your executors, heirs, or assigns, arising out of or connected with
                        access to or use of this site.


text:
namespace webrtc {
namespace {
constexpr base::TimeDelta kTaskLatencySampleDuration = base::Seconds(3);
}

// Class intended to conditionally live for the duration of ThreadWrapper
// that periodically captures task latencies (definition in docs for
// SetLatencyAndTaskDurationCallbacks).
class ThreadWrapper::PostTaskLatencySampler {
 public:
  PostTaskLatencySampler(
      scoped_refptr<base::SingleThreadTaskRunner> task_runner,
      SampledDurationCallback task_latency_callback)
      : task_runner_(task_runner),
        task_latency_callback_(std::move(task_latency_callback)) {
    ScheduleDelayedSample();
  }

  bool ShouldSampleNextTaskDuration() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(current_);
    bool time_to_sample = should_sample_next_task_duration_;
    should_sample_next_task_duration_ = false;
    return time_to_sample;
  }

 private:
  void ScheduleDelayedSample() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(current_);
    task_runner_->PostDelayedTask(
        FROM_HERE,
        base::BindOnce(&PostTaskLatencySampler::TakeSample,
                       base::Unretained(this)),
        kTaskLatencySampleDuration);
  }

  void TakeSample() {
    DCHECK_CALLED_ON_VALID_SEQUENCE(current_);
    task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&PostTaskLatencySampler::FinishSample,
                       base::Unretained(this), base::TimeTicks::Now()));
  }

  void FinishSample(base::TimeTicks post_timestamp) {
    DCHECK_CALLED_ON_VALID_SEQUENCE(current_);
    task_latency_callback_.Run(base::TimeTicks::Now() - post_timestamp);
    ScheduleDelayedSample();
    should_sample_next_task_duration_ = true;
  }

  SEQUENCE_CHECKER(current_);
  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
  base::RepeatingCallback<void(base::TimeDelta)> task_latency_callback_
      GUARDED_BY_CONTEXT(current_);
  bool should_sample_next_task_duration_ GUARDED_BY_CONTEXT(current_) = false;
};

struct ThreadWrapper::PendingSend {
  explicit PendingSend(rtc::FunctionView<void()> functor)
      : functor(functor),
        done_event(base::WaitableEvent::ResetPolicy::MANUAL,
                   base::WaitableEvent::InitialState::NOT_SIGNALED) {}

  rtc::FunctionView<void()> functor;
  base::WaitableEvent done_event;
};

base::LazyInstance<base::ThreadLocalPointer<ThreadWrapper>>::DestructorAtExit
    g_jingle_thread_wrapper = LAZY_INSTANCE_INITIALIZER;

// static
void ThreadWrapper::EnsureForCurrentMessageLoop() {
  if (ThreadWrapper::current() == nullptr) {
    std::unique_ptr<ThreadWrapper> wrapper =
        ThreadWrapper::WrapTaskRunner(base::ThreadTaskRunnerHandle::Get());
    base::CurrentThread::Get()->AddDestructionObserver(wrapper.release());
  }

  DCHECK_EQ(rtc::Thread::Current(), current());
}

std::unique_ptr<ThreadWrapper> ThreadWrapper::WrapTaskRunner(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
  DCHECK(!ThreadWrapper::current());
  DCHECK(task_runner->BelongsToCurrentThread());

  std::unique_ptr<ThreadWrapper> result(new ThreadWrapper(task_runner));
  g_jingle_thread_wrapper.Get().Set(result.get());
  return result;
}

// static
ThreadWrapper* ThreadWrapper::current() {
  return g_jingle_thread_wrapper.Get().Get();
}

void ThreadWrapper::SetLatencyAndTaskDurationCallbacks(
    SampledDurationCallback task_latency_callback,
    SampledDurationCallback task_duration_callback) {
  task_latency_callback_ = std::move(task_latency_callback);
  task_duration_callback_ = std::move(task_duration_callback);
}

ThreadWrapper::ThreadWrapper(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : Thread(std::make_unique<rtc::PhysicalSocketServer>()),
      task_runner_(task_runner),
      send_allowed_(false),
      last_task_id_(0),
      pending_send_event_(base::WaitableEvent::ResetPolicy::MANUAL,
                          base::WaitableEvent::InitialState::NOT_SIGNALED) {
  DCHECK(task_runner->BelongsToCurrentThread());
  DCHECK(!rtc::Thread::Current());
  weak_ptr_ = weak_ptr_factory_.GetWeakPtr();
  rtc::ThreadManager::Add(this);
  SafeWrapCurrent();
}

ThreadWrapper::~ThreadWrapper() {
  DCHECK_EQ(this, ThreadWrapper::current());
  DCHECK_EQ(this, rtc::Thread::Current());

  UnwrapCurrent();
  rtc::ThreadManager::Instance()->SetCurrentThread(nullptr);
  rtc::ThreadManager::Remove(this);
  g_jingle_thread_wrapper.Get().Set(nullptr);

  Clear(nullptr, rtc::MQID_ANY, nullptr);
  CHECK(pending_send_messages_.empty());
  coalesced_tasks_.Clear();
}

rtc::SocketServer* ThreadWrapper::SocketServer() {
  return rtc::Thread::socketserver();
}

void ThreadWrapper::WillDestroyCurrentMessageLoop() {
  delete this;
}

void ThreadWrapper::Post(const rtc::Location& posted_from,
                         rtc::MessageHandler* handler,
                         uint32_t message_id,
                         rtc::MessageData* data,
                         bool time_sensitive) {
  PostTaskInternal(posted_from, 0, handler, message_id, data);
}

void ThreadWrapper::PostDelayed(const rtc::Location& posted_from,
                                int delay_ms,
                                rtc::MessageHandler* handler,
                                uint32_t message_id,
                                rtc::MessageData* data) {
  PostTaskInternal(posted_from, delay_ms, handler, message_id, data);
}

void ThreadWrapper::Clear(rtc::MessageHandler* handler,
                          uint32_t id,
                          rtc::MessageList* removed) {
  base::AutoLock auto_lock(lock_);

  for (MessagesQueue::iterator it = messages_.begin(); it != messages_.end();) {
    MessagesQueue::iterator next = it;
    ++next;

    if (it->second.Match(handler, id)) {
      if (removed) {
        removed->push_back(it->second);
      } else {
        delete it->second.pdata;
      }
      messages_.erase(it);
    }

    it = next;
  }
}

void ThreadWrapper::Dispatch(rtc::Message* message) {
  TRACE_EVENT2("webrtc", "ThreadWrapper::Dispatch", "src_file_and_line",
               message->posted_from.file_and_line(), "src_func",
               message->posted_from.function_name());
  message->phandler->OnMessage(message);
}

void ThreadWrapper::BlockingCall(rtc::FunctionView<void()> functor) {
  ThreadWrapper* current_thread = ThreadWrapper::current();
  DCHECK(current_thread != nullptr) << "BlockingCall() can be called only from "
                                       "a thread that has ThreadWrapper.";

  if (current_thread == this) {
    functor();
    return;
  }

  // Send message from a thread different than |this|.

  // Allow inter-thread send only from threads that have
  // |send_allowed_| flag set.
  DCHECK(current_thread->send_allowed_)
      << "Send()'ing synchronous "
         "messages is not allowed from the current thread.";

  PendingSend pending_send(functor);
  {
    base::AutoLock auto_lock(lock_);
    pending_send_messages_.push_back(&pending_send);
  }

  // Need to signal |pending_send_event_| here in case the thread is
  // sending message to another thread.
  pending_send_event_.Signal();
  task_runner_->PostTask(
      FROM_HERE,
      base::BindOnce(&ThreadWrapper::ProcessPendingSends, weak_ptr_));

  while (!pending_send.done_event.IsSignaled()) {
    base::WaitableEvent* events[] = {&pending_send.done_event,
                                     &current_thread->pending_send_event_};
    size_t event = base::WaitableEvent::WaitMany(events, std::size(events));
    DCHECK(event == 0 || event == 1);

    if (event == 1)
      current_thread->ProcessPendingSends();
  }
}

void ThreadWrapper::ProcessPendingSends() {
  while (true) {
    PendingSend* pending_send = nullptr;
    {
      base::AutoLock auto_lock(lock_);
      if (!pending_send_messages_.empty()) {
        pending_send = pending_send_messages_.front();
        pending_send_messages_.pop_front();
      } else {
        // Reset the event while |lock_| is still locked.
        pending_send_event_.Reset();
        break;
      }
    }
    if (pending_send) {
      pending_send->functor();
      pending_send->done_event.Signal();
    }
  }
}

void ThreadWrapper::PostTaskInternal(const rtc::Location& posted_from,
                                     int delay_ms,
                                     rtc::MessageHandler* handler,
                                     uint32_t message_id,
                                     rtc::MessageData* data) {
  int task_id;
  rtc::Message message;
  message.posted_from = posted_from;
  message.phandler = handler;
  message.message_id = message_id;
  message.pdata = data;
  {
    base::AutoLock auto_lock(lock_);
    task_id = ++last_task_id_;
    messages_.insert(std::pair<int, rtc::Message>(task_id, message));
  }

  if (delay_ms <= 0) {
    task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&ThreadWrapper::RunTask, weak_ptr_, task_id));
  } else {
    task_runner_->PostDelayedTaskAt(
        base::subtle::PostDelayedTaskPassKey(), FROM_HERE,
        base::BindOnce(&ThreadWrapper::RunTask, weak_ptr_, task_id),
        base::TimeTicks::Now() + base::Milliseconds(delay_ms),
        base::subtle::DelayPolicy::kPrecise);
  }
}

void ThreadWrapper::PostTask(absl::AnyInvocable<void() &&> task) {
  task_runner_->PostTask(
      FROM_HERE, base::BindOnce(&ThreadWrapper::RunTaskQueueTask, weak_ptr_,
                                std::move(task)));
}

void ThreadWrapper::PostDelayedTask(absl::AnyInvocable<void() &&> task,
                                    TimeDelta delay) {
  base::TimeTicks target_time =
      base::TimeTicks::Now() + base::Microseconds(delay.us());
  // Coalesce low precision tasks onto the metronome.
  base::TimeTicks snapped_target_time =
      blink::MetronomeSource::TimeSnappedToNextTick(target_time);
  if (coalesced_tasks_.QueueDelayedTask(target_time, std::move(task),
                                        snapped_target_time)) {
    task_runner_->PostDelayedTaskAt(
        base::subtle::PostDelayedTaskPassKey(), FROM_HERE,
        base::BindOnce(&ThreadWrapper::RunCoalescedTaskQueueTasks, weak_ptr_,
                       snapped_target_time),
        snapped_target_time, base::subtle::DelayPolicy::kPrecise);
  }
}

void ThreadWrapper::PostDelayedHighPrecisionTask(
    absl::AnyInvocable<void() &&> task,
    webrtc::TimeDelta delay) {
  base::TimeTicks target_time =
      base::TimeTicks::Now() + base::Microseconds(delay.us());
  task_runner_->PostDelayedTaskAt(
      base::subtle::PostDelayedTaskPassKey(), FROM_HERE,
      base::BindOnce(&ThreadWrapper::RunTaskQueueTask, weak_ptr_,
                     std::move(task)),
      target_time, base::subtle::DelayPolicy::kPrecise);
}

absl::optional<base::TimeTicks> ThreadWrapper::PrepareRunTask() {
  if (!latency_sampler_ && task_latency_callback_) {
    latency_sampler_ = std::make_unique<PostTaskLatencySampler>(
        task_runner_, std::move(task_latency_callback_));
  }
  absl::optional<base::TimeTicks> task_start_timestamp;
  if (!task_duration_callback_.is_null() && latency_sampler_ &&
      latency_sampler_->ShouldSampleNextTaskDuration()) {
    task_start_timestamp = base::TimeTicks::Now();
  }
  return task_start_timestamp;
}

void ThreadWrapper::RunTaskQueueTask(absl::AnyInvocable<void() &&> task) {
  absl::optional<base::TimeTicks> task_start_timestamp = PrepareRunTask();

  std::move(task)();
  task = nullptr;

  FinalizeRunTask(std::move(task_start_timestamp));
}

void ThreadWrapper::RunCoalescedTaskQueueTasks(base::TimeTicks scheduled_time) {
  // base::Unretained(this) is safe here because these callbacks are only used
  // for the duration of the RunScheduledTasks() call.
  coalesced_tasks_.RunScheduledTasks(
      scheduled_time,
      base::BindRepeating(&ThreadWrapper::PrepareRunTask,
                          base::Unretained(this)),
      base::BindRepeating(&ThreadWrapper::FinalizeRunTask,
                          base::Unretained(this)));
}

void ThreadWrapper::RunTask(int task_id) {
  absl::optional<base::TimeTicks> task_start_timestamp = PrepareRunTask();

  RunTaskInternal(task_id);

  FinalizeRunTask(std::move(task_start_timestamp));
}

void ThreadWrapper::FinalizeRunTask(
    absl::optional<base::TimeTicks> task_start_timestamp) {
  if (task_start_timestamp.has_value())
    task_duration_callback_.Run(base::TimeTicks::Now() - *task_start_timestamp);
}

void ThreadWrapper::RunTaskInternal(int task_id) {
  bool have_message = false;
  rtc::Message message;
  {
    base::AutoLock auto_lock(lock_);
    MessagesQueue::iterator it = messages_.find(task_id);
    if (it != messages_.end()) {
      have_message = true;
      message = it->second;
      messages_.erase(it);
    }
  }

  if (have_message) {
    Dispatch(&message);
  }
}

bool ThreadWrapper::IsQuitting() {
  NOTIMPLEMENTED_LOG_ONCE();
  return false;
}

// All methods below are marked as not reached. See comments in the
// header for more details.
void ThreadWrapper::Quit() {
  NOTREACHED();
}

void ThreadWrapper::Restart() {
  NOTREACHED();
}

bool ThreadWrapper::Get(rtc::Message*, int, bool) {
  NOTREACHED();
  return false;
}

int ThreadWrapper::GetDelay() {
  NOTREACHED();
  return 0;
}

void ThreadWrapper::Stop() {
  NOTREACHED();
}

void ThreadWrapper::Run() {
  NOTREACHED();
}

}  // namespace webrtc


text:
package org.proton.plug.test.util;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.junit.Assert;
import org.junit.Test;
import org.proton.plug.util.CreditsSemaphore;

public class CreditsSemaphoreTest
{
   final CreditsSemaphore semaphore = new CreditsSemaphore(10);

   final AtomicInteger errors = new AtomicInteger(0);

   final AtomicInteger acquired = new AtomicInteger(0);

   final CountDownLatch waiting = new CountDownLatch(1);

   Thread thread = new Thread()
   {
      public void run()
      {
         try
         {
            for (int i = 0; i < 12; i++)
            {
               if (!semaphore.tryAcquire())
               {
                  waiting.countDown();
                  semaphore.acquire();
               }
               acquired.incrementAndGet();
            }
         }
         catch (Throwable e)
         {
            e.printStackTrace();
            errors.incrementAndGet();
         }
      }
   };

   @Test
   public void testSetAndRelease() throws Exception
   {
      thread.start();

      // 5 seconds would be an eternity here
      Assert.assertTrue(waiting.await(5, TimeUnit.SECONDS));

      Assert.assertEquals(0, semaphore.getCredits());

      long timeout = System.currentTimeMillis() + 1000;
      while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout)
      {
         Thread.sleep(10);
      }

      Assert.assertTrue(semaphore.hasQueuedThreads());

      semaphore.setCredits(2);

      thread.join();

      Assert.assertEquals(12, acquired.get());

      Assert.assertFalse(semaphore.hasQueuedThreads());
   }

   @Test
   public void testDownAndUp() throws Exception
   {
      thread.start();

      // 5 seconds would be an eternity here
      Assert.assertTrue(waiting.await(5, TimeUnit.SECONDS));

      Assert.assertEquals(0, semaphore.getCredits());

      long timeout = System.currentTimeMillis() + 1000;
      while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout)
      {
         Thread.sleep(10);
      }

      Assert.assertTrue(semaphore.hasQueuedThreads());

      semaphore.release(2);

      thread.join();

      Assert.assertEquals(12, acquired.get());

      Assert.assertFalse(semaphore.hasQueuedThreads());
   }

   @Test
   public void testStartedZeroedSetLater() throws Exception
   {
      semaphore.setCredits(0);

      thread.start();

      // 5 seconds would be an eternity here
      Assert.assertTrue(waiting.await(5, TimeUnit.SECONDS));

      Assert.assertEquals(0, semaphore.getCredits());

      long timeout = System.currentTimeMillis() + 1000;
      while (!semaphore.hasQueuedThreads() && System.currentTimeMillis() < timeout)
      {
         Thread.sleep(10);
      }

      Assert.assertTrue(semaphore.hasQueuedThreads());

      Assert.assertEquals(0, acquired.get());

      semaphore.setCredits(12);

      thread.join();

      Assert.assertEquals(12, acquired.get());

      Assert.assertFalse(semaphore.hasQueuedThreads());
   }

}


text:
import os
import sys
import subprocess
from setuptools import setup, find_packages
from distutils.version import LooseVersion

if sys.version_info.major != 3:
    print('This Python is only compatible with Python 3, but you are running '
          'Python {}. The installation will likely fail.'.format(sys.version_info.major))

# Read version from file
with open(os.path.join('stable_baselines', 'version.txt'), 'r') as file_handler:
    __version__ = file_handler.read().strip()

# Check tensorflow installation to avoid
# breaking pre-installed tf gpu
def find_tf_dependency():
    install_tf, tf_gpu = False, False
    try:
        import tensorflow as tf
        if tf.__version__ < LooseVersion('1.8.0'):
            install_tf = True
            # check if a gpu version is needed
            tf_gpu = tf.test.is_gpu_available()
    except ImportError:
        install_tf = True
        # Check if a nvidia gpu is present
        for command in ['nvidia-smi', '/usr/bin/nvidia-smi', 'nvidia-smi.exe']:
            try:
                if subprocess.call([command]) == 0:
                    tf_gpu = True
                    break
            except IOError:  # command does not exist / is not executable
                pass
        if os.environ.get('USE_GPU') == 'True':  # force GPU even if not auto-detected
            tf_gpu = True

    tf_dependency = []
    if install_tf:
        tf_dependency = ['tensorflow-gpu>=1.8.0,<2.0.0'] if tf_gpu else ['tensorflow>=1.8.0,<2.0.0']
        if tf_gpu:
            print("A GPU was detected, tensorflow-gpu will be installed")

    return tf_dependency

long_description = """
**WARNING: This package is in maintenance mode, please use [Stable-Baselines3 (SB3)](https://github.com/DLR-RM/stable-baselines3) for an up-to-date version. You can find a [migration guide](https://stable-baselines3.readthedocs.io/en/master/guide/migration.html) in SB3 documentation.**

[![Build Status](https://travis-ci.com/hill-a/stable-baselines.svg?branch=master)](https://travis-ci.com/hill-a/stable-baselines) [![Documentation Status](https://readthedocs.org/projects/stable-baselines/badge/?version=master)](https://stable-baselines.readthedocs.io/en/master/?badge=master) [![Codacy Badge](https://api.codacy.com/project/badge/Grade/3bcb4cd6d76a4270acb16b5fe6dd9efa)](https://www.codacy.com/app/baselines_janitors/stable-baselines?utm_source=github.com&utm_medium=referral&utm_content=hill-a/stable-baselines&utm_campaign=Badge_Grade) [![Codacy Badge](https://api.codacy.com/project/badge/Coverage/3bcb4cd6d76a4270acb16b5fe6dd9efa)](https://www.codacy.com/app/baselines_janitors/stable-baselines?utm_source=github.com&utm_medium=referral&utm_content=hill-a/stable-baselines&utm_campaign=Badge_Coverage)

# Stable Baselines

Stable Baselines is a set of improved implementations of reinforcement learning algorithms based on OpenAI [Baselines](https://github.com/openai/baselines/).

These algorithms will make it easier for the research community and industry to replicate, refine, and identify new ideas, and will create good baselines to build projects on top of. We expect these tools will be used as a base around which new ideas can be added, and as a tool for comparing a new approach against existing ones. We also hope that the simplicity of these tools will allow beginners to experiment with a more advanced toolset, without being buried in implementation details.

## Main differences with OpenAI Baselines
This toolset is a fork of OpenAI Baselines, with a major structural refactoring, and code cleanups:

-   Unified structure for all algorithms
-   PEP8 compliant (unified code style)
-   Documented functions and classes
-   More tests & more code coverage
-   Additional algorithms: SAC and TD3 (+ HER support for DQN, DDPG, SAC and TD3)

## Links

Repository:
https://github.com/hill-a/stable-baselines

Medium article:
https://medium.com/@araffin/df87c4b2fc82

Documentation:
https://stable-baselines.readthedocs.io/en/master/

RL Baselines Zoo:
https://github.com/araffin/rl-baselines-zoo

## Quick example

Most of the library tries to follow a sklearn-like syntax for the Reinforcement Learning algorithms using Gym.

Here is a quick example of how to train and run PPO2 on a cartpole environment:

```python
import gym

from stable_baselines.common.policies import MlpPolicy
from stable_baselines.common.vec_env import DummyVecEnv
from stable_baselines import PPO2

env = gym.make('CartPole-v1')
# Optional: PPO2 requires a vectorized environment to run
# the env is now wrapped automatically when passing it to the constructor
# env = DummyVecEnv([lambda: env])

model = PPO2(MlpPolicy, env, verbose=1)
model.learn(total_timesteps=10000)

obs = env.reset()
for i in range(1000):
    action, _states = model.predict(obs)
    obs, rewards, dones, info = env.step(action)
    env.render()
```

Or just train a model with a one liner if [the environment is registered in Gym](https://github.com/openai/gym/wiki/Environments) and if [the policy is registered](https://stable-baselines.readthedocs.io/en/master/guide/custom_policy.html):

```python
from stable_baselines import PPO2

model = PPO2('MlpPolicy', 'CartPole-v1').learn(10000)
```

"""

setup(name='stable_baselines',
      packages=[package for package in find_packages()
                if package.startswith('stable_baselines')],
      package_data={
          'stable_baselines': ['py.typed', 'version.txt'],
      },
      install_requires=[
          'gym[atari,classic_control]==0.19.0',
          'scipy',
          'joblib',
          'cloudpickle>=0.5.5',
          'opencv-python',
          'numpy',
          'pandas',
          'matplotlib'
      ] + find_tf_dependency(),
      extras_require={
        'mpi': [
            'mpi4py',
        ],
        'tests': [
            'pytest',
            'pytest-cov',
            'pytest-env',
            'pytest-xdist',
            'pytype',
        ],
        'docs': [
            'sphinx',
            'sphinx-autobuild',
            'sphinx-rtd-theme'
        ]
      },
      description='A fork of OpenAI Baselines, implementations of reinforcement learning algorithms.',
      author='Ashley Hill',
      url='https://github.com/hill-a/stable-baselines',
      author_email='ashley.hill@u-psud.fr',
      keywords="reinforcement-learning-algorithms reinforcement-learning machine-learning "
               "gym openai baselines toolbox python data-science",
      license="MIT",
      long_description=long_description,
      long_description_content_type='text/markdown',
      version=__version__,
      )

# python setup.py sdist
# python setup.py bdist_wheel
# twine upload --repository-url https://test.pypi.org/legacy/ dist/*
# twine upload dist/*


text:
class GURL;

class InstalledWebappBridge {
 public:
  using PermissionResponseCallback =
      base::OnceCallback<void(ContentSetting, bool)>;

  InstalledWebappBridge() = delete;
  InstalledWebappBridge(const InstalledWebappBridge&) = delete;
  InstalledWebappBridge& operator=(const InstalledWebappBridge&) = delete;

  static InstalledWebappProvider::RuleList GetInstalledWebappPermissions(
      ContentSettingsType content_type);

  static void SetProviderInstance(InstalledWebappProvider* provider);

  static void DecidePermission(const GURL& origin_url,
                               PermissionResponseCallback callback);
};

#endif  // CHROME_BROWSER_INSTALLABLE_INSTALLED_WEBAPP_BRIDGE_H_


text:
package ca.ualberta.cs.oneclick_cookbook;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

/**
 * Class that allows the user to search for other recipes.
 * @author Kenneth Armstrong
 *
 */
public class SearchActivity extends Activity {

	ArrayList<Recipe> recipes = new ArrayList<Recipe>();
	private Pantry userRecipes = new Pantry();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search, menu);
		return true;
	}

	/**
	 * Function that handles and directs the clicks from the user.
	 *
	 * @param v
	 *            The view of the button that was clicked.
	 */
	public void clickHandler(View v) {
		Intent intent;
		switch(v.getId()) {
		case R.id.bHomeSReturn:
			finish();
			break;
		case R.id.bHomeSPantry:
			GlobalApplication app = (GlobalApplication) getApplication();
			userRecipes = app.getCurrentUser().getUserPantry();

			System.err.println("Ingreds: " + userRecipes.toSearchString());

			NetworkHandler nh = new NetworkHandler();
			try {
				recipes = nh.searchRecipes(userRecipes.toSearchString());
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			ListView listView = (ListView) findViewById(R.id.searchResults);

			// Convert them to a string list
			ArrayList<String> content = new ArrayList<String>();
			for(int i = 0; i < recipes.size(); i++) {
	    		content.add(recipes.get(i).toString());
	    	}

			ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
					android.R.layout.simple_list_item_1, content);
			listView.setAdapter(adapter);

			// Set the onclick action
			listView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> adapterView, View view,
						int position, long id) {
					// Get and set the current recipes based on position
					GlobalApplication app = (GlobalApplication) getApplication();
					Recipe currentRecipe = recipes.get(position);
					app.setCurrentRecipe(currentRecipe);
					//set up test to check user for the recipe
					if (currentRecipe.getOwner() != null) {
						if (currentRecipe.getOwner() == app.getCurrentUser().getUserName()){
							Intent intent = new Intent(
									app,
									ca.ualberta.cs.oneclick_cookbook.ViewFullRecipeActivity.class);
							intent.putExtra("position", position);
							startActivity(intent);
						}
						else {
							Intent intent = new Intent(
									app,
									ca.ualberta.cs.oneclick_cookbook.CreateRecipeActivity.class);
							intent.putExtra("position", position);
							startActivity(intent);
						}
					}
					//no current user allow for edit in the recipe
					else {
						Intent intent = new Intent(
								app,
								ca.ualberta.cs.oneclick_cookbook.CreateRecipeActivity.class);
						intent.putExtra("position", position);
						startActivity(intent);
					}
				}

			});

			// Set what happens when a user clicks on an item
			listView.setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View v,
						final int position, long arg3) {
					// Builds the alert dialog box
					AlertDialog.Builder prompt = new AlertDialog.Builder(v
							.getContext());
					prompt.setTitle("Delete Recipe");
					prompt.setMessage("Are you sure you want to delete this recipe? It "
							+ "will be gone... forever.");

					prompt.setNegativeButton("No",
							new DialogInterface.OnClickListener() {

								// User has changed their mind
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									return;
								}
							});
					prompt.setPositiveButton("Yes",
							new DialogInterface.OnClickListener() {

								// User does want to delete the recipe they are long
								// pressing
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// Get the global state
									GlobalApplication app = (GlobalApplication) getApplication();

									// Remove from ES
									NetworkHandler nh = new NetworkHandler();
									String id = recipes.get(position).getID();

									try {
										nh.deleteRecipe(id);
									} catch (IOException e) {
										e.printStackTrace();
									}

									// Delete from the user
									app.getCurrentUser().deleteRecipe(position);

								}
							});
					prompt.show();
					return false;
				}

			});
			break;
		case R.id.bHomeSSearch:
			intent = new Intent(this.getApplicationContext(),
					KeywordSearchActivity.class);
			startActivity(intent);
			break;
		}
	}

}


text:
package gov.va.ds4p.cas.providers;

import gov.va.ds4p.policy.reference.Addr;
import gov.va.ds4p.policy.reference.AssignedAuthor;
import gov.va.ds4p.policy.reference.AssignedAuthoringDevice;
import gov.va.ds4p.policy.reference.AssignedPerson;
import gov.va.ds4p.policy.reference.DefaultCustodianInfo;
import gov.va.ds4p.policy.reference.DefaultPatientDemographics;
import gov.va.ds4p.policy.reference.HumanReadibleText;
import gov.va.ds4p.policy.reference.ManufacturingModelName;
import gov.va.ds4p.policy.reference.Name;
import gov.va.ds4p.policy.reference.OrganizationConsentPolicyInfo;
import gov.va.ds4p.policy.reference.OrganizationPolicy;
import gov.va.ds4p.policy.reference.SoftwareName;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * The Class ConsentServiceImplTest.
 */
@RunWith(MockitoJUnitRunner.class)

public class PDFBuilderForCDATest {

	PDFBuilderForCDA pDFBuilderForCDA;

	@Test
	public void test() throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {
		OrganizationPolicy orgPolicy=new OrganizationPolicy();
		Field usPrivacyLaw=orgPolicy.getClass().getDeclaredField("usPrivacyLaw");
		usPrivacyLaw.setAccessible(true);
		usPrivacyLaw.set(orgPolicy, "Title38Section7332");

		List<String> maskingActions=new ArrayList<String>();
		maskingActions.add("action1");
		maskingActions.add("action2");

		List<String> allowedRecipients= new ArrayList<String>();
		allowedRecipients.add("recipient1");
		allowedRecipients.add("recipient2");

		List<String> allowedPOU=new ArrayList<String>();
		allowedPOU.add("POU1");
		allowedPOU.add("POU2");

		Addr addr=new Addr();
		addr.setCity("Columbia");
		addr.setCountry("United States");
		addr.setCounty("Howard");
		addr.setPostalCode("21044");
		addr.setState("MD");
		addr.setStreetAddressLine("7175 Columbia Gateway Dr.");
		Field organizationConsentPolicyInfo=orgPolicy.getClass().getDeclaredField("organizationConsentPolicyInfo");
		OrganizationConsentPolicyInfo organizationConsentPolicyInfoField=new OrganizationConsentPolicyInfo();
		DefaultPatientDemographics defaultPatientDemographics=new DefaultPatientDemographics();
		defaultPatientDemographics.setAddr(addr);
		organizationConsentPolicyInfoField.setDefaultPatientDemographics(defaultPatientDemographics);
		organizationConsentPolicyInfoField.setAddr(addr);

		HumanReadibleText humanReadibleText=new HumanReadibleText();
		humanReadibleText.setDisplayText("Human Readible Text");
		organizationConsentPolicyInfoField.setHumanReadibleText(humanReadibleText);

		Name name=new Name();
		name.setFamily("Smith");
		name.setGiven("Albert");
		AssignedPerson person=new AssignedPerson();
		person.setName(name);
		AssignedAuthor assignedAuthor=new AssignedAuthor();
		assignedAuthor.setAssignedPerson(person);

		ManufacturingModelName manufacturingModelName=new ManufacturingModelName();
		manufacturingModelName.setCode("1");
		manufacturingModelName.setDisplayName("Company One");
		SoftwareName softwareName=new SoftwareName();
		softwareName.setCode("2");
		softwareName.setDisplayName("Software Company");
		AssignedAuthoringDevice assignedAuthoringDevice=new AssignedAuthoringDevice();
		assignedAuthoringDevice.setManufacturingModelName(manufacturingModelName);
		assignedAuthoringDevice.setSoftwareName(softwareName);

		DefaultCustodianInfo defaultCustodianInfo=new DefaultCustodianInfo();
		defaultCustodianInfo.setTelcom("telcom");
		organizationConsentPolicyInfoField.setDefaultCustodianInfo(defaultCustodianInfo);

		organizationConsentPolicyInfoField.setAssignedAuthor(assignedAuthor);
		organizationConsentPolicyInfoField.setAssignedAuthoringDevice(assignedAuthoringDevice);
		organizationConsentPolicyInfo.setAccessible(true);
		organizationConsentPolicyInfo.set(orgPolicy, organizationConsentPolicyInfoField);

		List<String> redactActions=new ArrayList<String>();
		redactActions.add("action1");
		redactActions.add("action2");

		pDFBuilderForCDA=new PDFBuilderForCDA (orgPolicy, "1", "John Doe", "Permit", allowedPOU, allowedRecipients, redactActions, maskingActions);
		pDFBuilderForCDA.getPDFConsentDirective();
	}

}


text:
/*++

Module Name:

    ReadSupplierQueue.cpp

Abstract:

    Code for parallel queue of reads

Authors:

    Bill Bolosky, November, 2012

Environment:

    User mode service.

Revision History:

--*/

#include "stdafx.h"
#include "Read.h"
#include "Compat.h"
#include "ReadSupplierQueue.h"
#include "exit.h"
#include "SAM.h"

//#define PAIR_MATCH_DEBUG

 ReadSupplierQueue::ReadSupplierQueue(ReadReader *reader)
     : tracker(64)
{
    commonInit();

    singleReader[0] = reader;
}

ReadSupplierQueue::ReadSupplierQueue(ReadReader *firstHalfReader, ReadReader *secondHalfReader)
     : tracker(64)
{
    commonInit();

    singleReader[0] = firstHalfReader;
    singleReader[1] = secondHalfReader;
}

ReadSupplierQueue::ReadSupplierQueue(PairedReadReader *i_pairedReader)
     : tracker(128)
{
    commonInit();
    pairedReader = i_pairedReader;
}

void
ReadSupplierQueue::commonInit()
{
    nReadersRunning = 0;
    nSuppliersRunning = 0;
    allReadsQueued = false;

    balance = 0;

    emptyQueue->next = emptyQueue->prev = emptyQueue;
    readyQueue[0].next = readyQueue[0].prev = &readyQueue[0];
    readyQueue[1].next = readyQueue[1].prev = &readyQueue[1];

    InitializeExclusiveLock(&lock);
    CreateEventObject(&readsReady);
    CreateEventObject(&emptyBuffersAvailable);
    CreateEventObject(&allReadsConsumed);

    //
    // Create 2 buffers for the reader.  We'll add more buffers as we add suppliers.
    //
    for (int i = 0 ; i < 2; i++) {
        ReadQueueElement *element = new ReadQueueElement;
        element->addToTail(emptyQueue);
    }

    AllowEventWaitersToProceed(&emptyBuffersAvailable);

    for (int i = 0; i < 2; i++) {
        CreateEventObject(&throttle[i]);
        AllowEventWaitersToProceed(&throttle[i]);
        singleReader[i] = NULL;
    }
    pairedReader = NULL;
    elementSize = ReadQueueElement::MaxReadsPerElement;
}

ReadSupplierQueue::~ReadSupplierQueue()
{
    delete singleReader[0];
    delete singleReader[1];
    delete pairedReader;

    DestroyEventObject(&throttle[0]);
    DestroyEventObject(&throttle[1]);
    DestroyExclusiveLock(&lock);
}

    bool
ReadSupplierQueue::startReaders()
{
    bool worked = true;

    if (singleReader[1] == NULL) {
        nReadersRunning = 1;
    } else {
        nReadersRunning = 2;
    }

    ReaderThreadParams *readerParams = new ReaderThreadParams;
    readerParams->isSecondReader = false;
    readerParams->queue = this;
    if (!StartNewThread(ReaderThreadMain, readerParams)) {
        return false;
    }

    if (singleReader[1] == NULL) {
        return true;
    }

    readerParams = new ReaderThreadParams;
    readerParams->isSecondReader = true;
    readerParams->queue = this;
    return (StartNewThread(ReaderThreadMain, readerParams));
}

    void
ReadSupplierQueue::waitUntilFinished()
{
    WaitForEvent(&allReadsConsumed);
}

    ReadSupplier *
ReadSupplierQueue::generateNewReadSupplier()
{
    AcquireExclusiveLock(&lock);
    nSuppliersRunning++;
    //
    // Add more queue elements for this supplier.
    //
    for (int i = 0; i < 2; i++) {
        ReadQueueElement *element = new ReadQueueElement;
        element->addToTail(emptyQueue);
    }

    AllowEventWaitersToProceed(&emptyBuffersAvailable);
    ReleaseExclusiveLock(&lock);

    return new ReadSupplierFromQueue(this);
}

        PairedReadSupplier *
ReadSupplierQueue::generateNewPairedReadSupplier()
{
    const int addElements = (singleReader[1] == NULL) ? 2 : 4 + MaxImbalance;
    ReadQueueElement * newElements[MaxImbalance + 4];
    for (int i = 0 ; i < addElements; i++) {
        newElements[i] = new ReadQueueElement;
    }

    AcquireExclusiveLock(&lock);
    nSuppliersRunning++;
    //
    // Add two more queue elements (4+MaxImbalance for paired-end, double file).
    //
    for (int i = 0; i < addElements; i++) {
        ReadQueueElement *element = newElements[i];
        element->addToTail(emptyQueue);
    }

    AllowEventWaitersToProceed(&emptyBuffersAvailable);
    ReleaseExclusiveLock(&lock);

    return new PairedReadSupplierFromQueue(this, singleReader[1] != NULL);
}

    ReaderContext*
ReadSupplierQueue::getContext()
{
    return singleReader[0] != NULL ? singleReader[0]->getContext() : pairedReader->getContext();
}

    ReadQueueElement *
ReadSupplierQueue::getElement()
{
    _ASSERT(singleReader[1] == NULL);   // i.e., we're doing file (but possibly single or paired end) reads
    //WriteErrorMessage("Thread %u: getElement wait acquire lock\n", GetThreadId());
    AcquireExclusiveLock(&lock);
    //WriteErrorMessage("Thread %u: getElement acquired lock\n", GetThreadId());
    while (!areAnyReadsReady()) {
        //WriteErrorMessage("Thread %u: getElement loop releasing lock\n", GetThreadId());
        ReleaseExclusiveLock(&lock);
        //WriteErrorMessage("Thread %u: getElement loop released lock\n", GetThreadId());
        if (allReadsQueued) {
            //
            // Everything's queued and the queue is empty.  No more work.
            //
            //WriteErrorMessage("Thread %u: getElement loop exit allReadsQueued\n", GetThreadId());
            return NULL;
        }
        //WriteErrorMessage("Thread %u: getElement loop wait readsReady\n", GetThreadId());
        WaitForEvent(&readsReady);
        //WriteErrorMessage("Thread %u: getElement loop wait acquire lock\n", GetThreadId());
        AcquireExclusiveLock(&lock);
        //WriteErrorMessage("Thread %u: getElement loop acquired lock\n", GetThreadId());
    }

    ReadQueueElement *element = readyQueue[0].next;
    _ASSERT(element != &readyQueue[0]);
    element->removeFromQueue();

    if (!areAnyReadsReady() && !allReadsQueued) {
        //WriteErrorMessage("Thread %u: getElement block readsReady\n", GetThreadId());
        PreventEventWaitersFromProceeding(&readsReady);
    }
    ReleaseExclusiveLock(&lock);
    //WriteErrorMessage("Thread %u: getElement released lock\n", GetThreadId());

    return element;
}

        bool
ReadSupplierQueue::getElements(ReadQueueElement **element1, ReadQueueElement **element2)
{
   _ASSERT(singleReader[1] != NULL);   // i.e., we're doing paired file reads

   //WriteErrorMessage("Thread %u: getElements wait acquire lock\n", GetThreadId());
    AcquireExclusiveLock(&lock);
    //WriteErrorMessage("Thread %u: getElements acquired lock\n", GetThreadId());
    while (!areAnyReadsReady()) {
        //WriteErrorMessage("Thread %u: getElements loop releasing lock\n", GetThreadId());
        ReleaseExclusiveLock(&lock);
        //WriteErrorMessage("Thread %u: getElements loop released lock\n", GetThreadId());
        if (allReadsQueued) {
            //
            // Everything's queued and the queue is empty.  No more work.
            //
            //WriteErrorMessage("Thread %u: getElement loop exit allReadsQueued\n", GetThreadId());
            return NULL;
        }
        //WriteErrorMessage("Thread %u: getElements loop wait readsReady\n", GetThreadId());
        WaitForEvent(&readsReady);
        //WriteErrorMessage("Thread %u: getElements loop wait acquire lock\n", GetThreadId());
        AcquireExclusiveLock(&lock);
        //WriteErrorMessage("Thread %u: getElements loop acquired lock\n", GetThreadId());
    }

    ReadQueueElement* copyOut = NULL; // for adjusting sizes
    *element1 = readyQueue[0].next;
    *element2 = readyQueue[1].next;
    if ((*element1)->totalReads != (*element2)->totalReads) {
        copyOut = getEmptyElement(); // might release/acquire lock so state could change!
        *element1 = readyQueue[0].next;
        *element2 = readyQueue[1].next;
        if ((*element1)->totalReads == (*element2)->totalReads) {
            doneWithElement(copyOut);
        }
    }

    if ((*element1)->totalReads == (*element2)->totalReads) {
        (*element1)->removeFromQueue();
        (*element2)->removeFromQueue();
    } else {
        //fprintf(stderr,"getElements different sizes %d %d\n", (*element1)->totalReads, (*element2)->totalReads);
        // need to balance out reads between the two
        // make a copy of the min# of reads from larger element
        // shrink the larger element and leave it there
        ReadQueueElement* elements[2] = {*element1, *element2};
        int sizes[2] = {elements[0]->totalReads, elements[1]->totalReads};
        int largerOne = elements[1]->totalReads > elements[0]->totalReads;
        int minReads = elements[1-largerOne]->totalReads;
        memcpy(copyOut->reads, elements[largerOne]->reads, minReads * sizeof(Read));
        _ASSERT(elements[0]->totalReads == sizes[0] && elements[1]->totalReads == sizes[1] && elements[largerOne]->totalReads > elements[1-largerOne]->totalReads);
        copyOut->totalReads = minReads;
        _ASSERT(elements[0]->totalReads == sizes[0] && elements[1]->totalReads == sizes[1] && elements[largerOne]->totalReads > elements[1-largerOne]->totalReads);
        memmove(elements[largerOne]->reads, &elements[largerOne]->reads[minReads],
            (elements[largerOne]->totalReads - minReads) * sizeof(Read));
        elements[largerOne]->totalReads -= minReads;
        copyOut->batches.append(&elements[largerOne]->batches);
        for (BatchVector::iterator i = copyOut->batches.begin(); i != copyOut->batches.end(); i++) {
            holdBatch(*i);
        }
        if (largerOne == 0) {
            *element1 = copyOut;
            (*element2)->removeFromQueue();
        } else {
            (*element1)->removeFromQueue();
            *element2 = copyOut;
        }
        //WriteErrorMessage("Thread %u: balanced sizes %d %d\n", GetThreadId(), sizes[0], sizes[1]);
    }
    //fprintf(stderr,"getElements %x/%x with %d/%d reads\n", (int) (*element1), (int) (*element2), (*element1)->totalReads, (*element2)->totalReads);

    if (!areAnyReadsReady() && !allReadsQueued) {
        //WriteErrorMessage("Thread %u: getElements block readsReady\n", GetThreadId());
        PreventEventWaitersFromProceeding(&readsReady);
    }

    //WriteErrorMessage("Thread %u: getElements releasing lock\n", GetThreadId());
    ReleaseExclusiveLock(&lock);
    //WriteErrorMessage("Thread %u: getElements released lock", GetThreadId());
    return true;
}

    bool
ReadSupplierQueue::areAnyReadsReady() // must hold the lock to call this.
{
    if (readyQueue[0].next == &readyQueue[0]) {
        return false;
    }

    if (singleReader[1] == NULL) {
        return true;
    }

    return readyQueue[1].next != &readyQueue[1];
}

    void
ReadSupplierQueue::doneWithElement(ReadQueueElement *element)
{
    //WriteErrorMessage("Thread %u: doneWithElement wait acquire lock\n", GetThreadId());
    AcquireExclusiveLock(&lock);
    //WriteErrorMessage("Thread %u: doneWithElement acquired lock\n", GetThreadId());
    _ASSERT(element->totalReads > 0);
    VariableSizeVector<DataBatch> batches = element->batches;
    element->batches.clear();
    element->addToTail(emptyQueue);
    AllowEventWaitersToProceed(&emptyBuffersAvailable);
    //WriteErrorMessage("Thread %u: doneWithElement releasing lock\n", GetThreadId());
    ReleaseExclusiveLock(&lock);
    //WriteErrorMessage("Thread %u: doneWithElement released lock\n", GetThreadId());
    for (VariableSizeVector<DataBatch>::iterator b = batches.begin(); b != batches.end(); b++) {
        releaseBatch(*b);
    }
}

    void
ReadSupplierQueue::supplierFinished()
{
    //WriteErrorMessage("Thread %u: supplierFinished wait acquire lock\n", GetThreadId());
    AcquireExclusiveLock(&lock);
    //WriteErrorMessage("Thread %u: supplierFinished acquired lock\n", GetThreadId());
    _ASSERT(allReadsQueued);
    _ASSERT(nSuppliersRunning > 0);
    nSuppliersRunning--;
    if (0 == nSuppliersRunning) {
        AllowEventWaitersToProceed(&allReadsConsumed);
    }
    //WriteErrorMessage("Thread %u: supplierFinished releasing lock\n", GetThreadId());
    ReleaseExclusiveLock(&lock);
    //WriteErrorMessage("Thread %u: supplierFinished released lock\n", GetThreadId());
}

    void
ReadSupplierQueue::holdBatch(
    DataBatch batch)
{
    if (pairedReader != NULL) {
        pairedReader->holdBatch(batch);
    } else if (singleReader[1] == NULL) {
        singleReader[0]->holdBatch(batch);
    } else {
        singleReader[batch.fileID % 2]->holdBatch(DataBatch(batch.batchID, batch.fileID / 2));
    }
}

    bool
ReadSupplierQueue::releaseBatch(
    DataBatch batch)
{
    if (pairedReader != NULL) {
        return pairedReader->releaseBatch(batch);
    } else if (singleReader[1] == NULL) {
        return singleReader[0]->releaseBatch(batch);
    } else {
        return singleReader[batch.fileID % 2]->releaseBatch(DataBatch(batch.batchID, batch.fileID / 2));
    }
}

    void
ReadSupplierQueue::ReaderThreadMain(void *param)
{
    ReaderThreadParams *params = (ReaderThreadParams *)param;
    params->queue->ReaderThread(params);
    delete params;
}

    ReadQueueElement*
ReadSupplierQueue::getEmptyElement()
{
    while (emptyQueue->next == emptyQueue) {
        // Wait for a buffer.
        //WriteErrorMessage("Thread %u: getEmptyElement releasing lock\n", GetThreadId());
        ReleaseExclusiveLock(&lock);
        //WriteErrorMessage("Thread %u: getEmptyElement released lock\n", GetThreadId());
        WaitForEvent(&emptyBuffersAvailable);
        //WriteErrorMessage("Thread %u: getEmptyElement acquiring lock\n", GetThreadId());
        AcquireExclusiveLock(&lock);
        //WriteErrorMessage("Thread %u: getEmptyElement acquired lock\n", GetThreadId());
    }

    ReadQueueElement *element = emptyQueue->next;
    element->removeFromQueue();
    if (emptyQueue->next == emptyQueue) {
        PreventEventWaitersFromProceeding(&emptyBuffersAvailable);
    }

    return element;
}

    void
ReadSupplierQueue::ReaderThread(ReaderThreadParams *params)
{
    AcquireExclusiveLock(&lock);
    bool done = false;
    ReadReader *reader;
    if (params->isSecondReader) {
        reader = singleReader[1];
    } else {
        reader = singleReader[0]; // In the pairedReader case, this will just be NULL
    }
    int increment = (NULL == reader) ? 2 : 1;
    int balanceIncrement = params->isSecondReader ? -1 : 1;
    int firstOrSecond = params->isSecondReader ? 1 : 0;
    bool isSingleReader = (NULL == singleReader[1]);

    _int64 balanceTime = 0;
    _int64 bufferWaitTime = 0;
    _int64 processingTime = 0;
    _int64 startTime = timeInNanos();

    // may pass reads forward from element loops to maintain batching or element size
    Read firstReadForNextElement[2];
    bool hasFirstReadForNextElement = false;

    while (!done) {
        if ((!isSingleReader) && balance * balanceIncrement > MaxImbalance) {
            //
            // We're over full.  Wait to get back in balance.
            //
            ReleaseExclusiveLock(&lock);

            _int64 now = timeInNanos();
            processingTime += now - startTime;
            startTime = now;

            WaitForEvent(&throttle[firstOrSecond]);

            now = timeInNanos();
            balanceTime += now - startTime;
            startTime = now;

            AcquireExclusiveLock(&lock);
            _ASSERT(balance * balanceIncrement <= MaxImbalance);
        }

        // pull an empty element from the queue
        _int64 now = timeInNanos();
        processingTime += now - startTime;
        startTime = now;
        ReadQueueElement* element = getEmptyElement();
        now = timeInNanos();
        bufferWaitTime += now - startTime;
        startTime = now;

        //
        // Now fill in the reads from the reader into the element until it's
        // full or the reader finishes or it exceeds batch count
        //
        ReleaseExclusiveLock(&lock);
        element->totalReads = 0;
        for (; element->totalReads <= (int) elementSize - increment; element->totalReads += increment) {

            if (NULL != reader) {
                Read* read = &element->reads[element->totalReads];
                if (hasFirstReadForNextElement) {
                    _ASSERT(element->totalReads == 0);
                    *read = firstReadForNextElement[0];
                    // already called holdBatch when firstReadForNextElement set
                    element->batches.push_back(read->getBatch());
                    hasFirstReadForNextElement = false;
                } else {
                    done = ! reader->getNextRead(read);
                    if (done) {
                        break;
                    }
                    if (! isSingleReader) {
                        read->setBatch(DataBatch(read->getBatch().batchID, read->getBatch().fileID * 2 + firstOrSecond));
                    }
                    bool newBatch = element->totalReads == 0 ||
                        (read->getBatch() != read[-1].getBatch() && element->batches.search(read->getBatch()) == element->batches.end());
                    if (element->batches.size() + newBatch <= BatchesPerElement) {
                        // won't exceed limit for this element
                        if (newBatch && element->batches.add(read->getBatch())) {
                            holdBatch(read->getBatch());
                        }
                    } else {
                        // too many batches, hold for next queue element
                        firstReadForNextElement[0] = *read;
                        hasFirstReadForNextElement = true;
                        holdBatch(read->getBatch());
                        break;
                    }
                }
            } else if (NULL != pairedReader) {
                Read* read = &element->reads[element->totalReads];
                if (hasFirstReadForNextElement) {
                    _ASSERT(element->totalReads == 0);
                    read[0] = firstReadForNextElement[0];
                    read[1] = firstReadForNextElement[1];
                    // already called holdBatch when firstReadForNextElement set
                    element->batches.push_back(read[0].getBatch());
                    if (read[1].getBatch() != read[0].getBatch()) {
                        element->batches.push_back(read[1].getBatch());
                    }
                    hasFirstReadForNextElement = false;
                } else {
                    done = !pairedReader->getNextReadPair(&read[0], &read[1]);
                    if (done) {
                        break;
                    }
                    DataBatch b[2] = {read[0].getBatch(), read[1].getBatch()};
                    bool newBatch[2] =
                        {(element->totalReads == 0 || read[-2].getBatch() != b[0]) &&
                            element->batches.search(b[0]) == element->batches.end(),
                        b[0] != b[1] && (element->totalReads == 0 || read[-1].getBatch() != b[1]) &&
                            element->batches.search(b[1]) == element->batches.end()};
                    if (element->batches.size() + newBatch[0] + newBatch[1] <= BatchesPerElement) {
                        if (newBatch[0] && element->batches.add(b[0])) {
                            holdBatch(b[0]);
                        }
                        if (newBatch[1] && element->batches.add(b[1])) {
                            holdBatch(b[1]);
                        }
                    } else {
                        firstReadForNextElement[0] = read[0];
                        firstReadForNextElement[1] = read[1];
                        holdBatch(b[0]);
                        if (b[1] != b[0]) {
                            holdBatch(b[1]);
                        }
                        hasFirstReadForNextElement = true;
                        break;
                    }
                    //WriteErrorMessage("ReadSupplierQueue::ReaderThread element %x batches %d:%d, %d:%d\n", (int) element, b[0].fileID, b[0].batchID, b[1].fileID, b[1].batchID);
                }
           }
        }

        //WriteErrorMessage("ReadSupplierQueue element[%d] %x with %d reads %d batches\n", firstOrSecond, (int) element, element->totalReads, element->batches.size());

        AcquireExclusiveLock(&lock);

        // do this before AllowEventWaitersToProceed to avoid race condition
        if (done && 1 == nReadersRunning) {
            //WriteErrorMessage("Thread %u: set allReadsQueued (%d) in ReaderThread...\n", GetThreadId(), element->totalReads);
            allReadsQueued = true;
            AllowEventWaitersToProceed(&readsReady);    // Even if we have nothing to queue, allow the consumers to wake up so they can exit
        }

        if (element->totalReads > 0) {
            element->addToTail(&readyQueue[firstOrSecond]);
            if (isSingleReader || &readyQueue[1-firstOrSecond] != readyQueue[1-firstOrSecond].next) {
                //
                // Signal that an element is ready.
                //
                //WriteErrorMessage("Thread %u: signal readsReady in ReaderThread...\n", GetThreadId());
                AllowEventWaitersToProceed(&readsReady);
            }

            if (!isSingleReader) {
                //WriteErrorMessage("Thread %u: balance %d %+d = %d...\n", GetThreadId(), balance, balanceIncrement, balance + balanceIncrement);
                balance += balanceIncrement;
                if (balance * balanceIncrement > MaxImbalance) {
                    _ASSERT(balance * balanceIncrement == MaxImbalance + 1);  // We can get at most one past the limit
                    //
                    // We're too far ahead.  Close our throttle.
                    //
		    //WriteErrorMessage("Thread %u: close throttle %d in ReaderThread...\n", GetThreadId(), firstOrSecond);
                    PreventEventWaitersFromProceeding(&throttle[firstOrSecond]);
                } else if (balance * -1 * balanceIncrement == MaxImbalance) {
                    //
                    // We just pushed it back into balance (barely) for the other guy.  Allow him to
                    // proceed.
                    //
		    //WriteErrorMessage("Thread %u: release throttle %d in ReaderThread...\n", GetThreadId(), 1-firstOrSecond);
                    AllowEventWaitersToProceed(&throttle[1-firstOrSecond]);
                }
            }
        }
    } // While ! done

    processingTime += timeInNanos() - startTime;

    //WriteErrorMessage("ReadSupplier: %llds processing, %llds waiting for balance, %llds waiting for buffer\n", processingTime / 1000000000, balanceTime / 1000000000, bufferWaitTime / 1000000000);

    _ASSERT(nReadersRunning > 0);
    nReadersRunning--;
    ReleaseExclusiveLock(&lock);
}

ReadSupplierFromQueue::ReadSupplierFromQueue(
    ReadSupplierQueue *i_queue)
    :
    queue(i_queue),
    outOfReads(false),
    currentElement(NULL),
    nextReadIndex(0),
    done(false)
{
}

    Read *
ReadSupplierFromQueue::getNextRead()
{
    if (done) {
        return NULL;
    }

    ReadQueueElement* doneElement = NULL;
    if (NULL != currentElement && nextReadIndex >= currentElement->totalReads) {
        doneElement = currentElement;
        currentElement = NULL;
    }

    if (NULL == currentElement) {
        currentElement = queue->getElement();
        if (doneElement != NULL) {
            queue->doneWithElement(doneElement);
        }
        if (NULL == currentElement) {
            done = true;
            queue->supplierFinished();
            return NULL;
        }
        nextReadIndex = 0;
    }

    return &currentElement->reads[nextReadIndex++]; // Note the post increment.
}

PairedReadSupplierFromQueue::PairedReadSupplierFromQueue(ReadSupplierQueue *i_queue, bool i_twoFiles) :
    queue(i_queue), twoFiles(i_twoFiles), done(false),
    currentElement(NULL), currentSecondElement(NULL), nextReadIndex(0) {}

PairedReadSupplierFromQueue::~PairedReadSupplierFromQueue()
{}

    bool
PairedReadSupplierFromQueue::getNextReadPair(Read **read0, Read **read1)
{
    if (done) {
        *read0 = NULL;
        *read1 = NULL;
        return false;
    }

    if (NULL != currentElement && nextReadIndex >= currentElement->totalReads) {
        //fprintf(stderr,"PairedReadSupplierFromQueue finished element %x with %d reads %d batches:", (int) currentElement, currentElement->totalReads, currentElement->batches.size()); for (BatchVector::iterator i = currentElement->batches.begin(); i != currentElement->batches.end(); i++) { fprintf(stderr," %d:%d", i->fileID, i->batchID); } fprintf(stderr,"\n");
        queue->doneWithElement(currentElement);
        currentElement = NULL;
        if (twoFiles) {
            //fprintf(stderr,"PairedReadSupplierFromQueue finished 2nd element %x with %d reads %d batches:", (int) currentSecondElement, currentSecondElement->totalReads, currentSecondElement->batches.size()); for (BatchVector::iterator i = currentSecondElement->batches.begin(); i != currentSecondElement->batches.end(); i++) { printf(" %d:%d", i->fileID, i->batchID); } printf("\n");
            queue->doneWithElement(currentSecondElement);
            currentSecondElement = NULL;
        }
    }

    if (NULL == currentElement) {
        if ((twoFiles && !queue->getElements(&currentElement, &currentSecondElement)) ||
            (!twoFiles && NULL == (currentElement = queue->getElement()))) {

            done = true;
            queue->supplierFinished();
            *read0 = NULL;
            *read1 = NULL;
            return false;
        }
		nextReadIndex = 0;
    }
    if (twoFiles) {
        // Assert that both elements match.
        _ASSERT(currentSecondElement->totalReads == currentElement->totalReads);
#ifdef PAIR_MATCH_DEBUG
        for (int i = 0; i < currentElement->totalReads; i++) {
            Read::checkIdMatch(&currentElement->reads[i], &currentSecondElement->reads[i]);
        }
#endif
    } else {
        //
        // Assert that there are an even number of reads (since they're in pairs)
        //
        _ASSERT(currentElement->totalReads % 2 == 0);
#ifdef PAIR_MATCH_DEBUG
        for (int i = 0; i < currentElement->totalReads; i += 2) {
            Read::checkIdMatch(&currentElement->reads[i], &currentElement->reads[i+1]);
        }
#endif
    }

    if (twoFiles) {
        *read0 = &currentElement->reads[nextReadIndex];
        *read1 = &currentSecondElement->reads[nextReadIndex];
#ifdef PAIR_MATCH_DEBUG
		Read::checkIdMatch(*read0, *read1);
#endif
        nextReadIndex++;
    } else {
        *read0 = &currentElement->reads[nextReadIndex];
        *read1 = &currentElement->reads[nextReadIndex+1];
#ifdef PAIR_MATCH_DEBUG
		Read::checkIdMatch(*read0, *read1);
#endif
        nextReadIndex += 2;
    }

    return true;
}


text:
package app.services;

import app.model.Role;
import app.model.User;
import app.repository.RoleRepository;
import app.repository.UserRepository;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.async.Callback;
import com.mashape.unirest.http.exceptions.UnirestException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Future;

/**
 * Created by Pavel on 26.03.2018.
 */
@Service
public class EmailNotifierService {

    private String DOMAIN_NAME;
    private String API_KEY;

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private UserRepository userRepository;

    public EmailNotifierService(Environment environment) {
        this.DOMAIN_NAME = environment.getProperty("notify.domain");
        this.API_KEY = environment.getProperty("notify.apiKey");
    }

    private String getAdminEmail() {
        List<Role> roles = new ArrayList<Role>() {{
            add(roleRepository.findByRole("ADMIN"));
        }};
        String email = "";
        Optional<User> optionalAdmin = userRepository.findByRoles(roles);
        if (optionalAdmin.isPresent()) {
            email = optionalAdmin.get().getEmail();
        }
        return email;
    }

    public void notifyAdmin(String entity) {

        Future<HttpResponse<JsonNode>> future = Unirest.post("https://api.mailgun.net/v3/" + DOMAIN_NAME + "/messages")
                .basicAuth("api", API_KEY)
                .queryString("from", "My library <beworm.readedbooks@gmail.com>")
                .queryString("to", getAdminEmail())
                .queryString("subject", "Notify Admin")
                .queryString("text", "The new " + entity + " was add")
                .asJsonAsync(new Callback<JsonNode>() {
                    @Override
                    public void completed(HttpResponse<JsonNode> httpResponse) {
                        int code = httpResponse.getStatus();
                        JsonNode body = httpResponse.getBody();
                        InputStream rawBody = httpResponse.getRawBody();
                        System.out.println("NOTIFY Admin: The notify admin and with status " + code);
                    }

                    @Override
                    public void failed(UnirestException e) {
                        System.out.println(e.getMessage());
                    }

                    @Override
                    public void cancelled() {
                        System.out.println("NOTIFY Admin: The request notify admin has been cancelled");
                    }
                });

    }
}


text:
<!DOCTYPE html>

    <title>CoreDataPlus Enumeration Reference</title>
    <link rel="stylesheet" type="text/css" href="../../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../../css/highlight.css" />
    <meta charset='utf-8'>

CoreDataPlus 2.3.0 Docs (88% documented)

        CoreDataPlus Reference

        CoreDataPlus Enumeration Reference

            Enumerations

                FetchedResultsObjectChange

                FetchedResultsSectionChange

            Extensions

                Collection

                NSBatchDeleteResult

                NSBatchInsertResult

                NSBatchUpdateResult

                NSFetchRequest

                NSFetchRequestResult

                NSManagedObject

                NSManagedObjectContext

                NSPersistentStoreCoordinator

                NSSet

                Notification

                – CoreDataPlus

            Functions

                isMigrationNecessary(for:to:)

            Protocols

                CoreDataModelVersion

                ManagedObjectContextChangePayload

                ManagedObjectContextNotificationPayload

                NotificationPayload

            Structures

                CoreDataMigration

                – Step

                FetchedResultsSectionInfo

            Type Aliases

                CoreDataMigrationStep

                Payload

CoreDataPlus

enum CoreDataPlus

Undocumented

                    Payload

Undocumented

                        See more

Declaration

Swift

public enum Payload

© 2020 Alessandro Marzoli. All rights reserved. (Last updated: 2020-08-10)

Generated by jazzy ♪♫ v0.13.4, a Realm project.


text:
function Controller() {
    function __alloyId119() {
        __alloyId119.opts || {};
        var models = filtrado(__alloyId118);
        var len = models.length;
        var rows = [];
        for (var i = 0; len > i; i++) {
            var __alloyId114 = models[i];
            __alloyId114.__transform = transform(__alloyId114);
            var __alloyId115 = Alloy.createController("CursoRow", {
                $model: __alloyId114
            });
            rows.push(__alloyId115.getViewEx({
                recurse: true
            }));
        }
        $.__views.TablaCursos.setData(rows);
    }
    function filtrado(collection) {
        var coleccion_filtrada = collection.where({
            Grado: data.IdGrado
        });
        return coleccion_filtrada;
    }
    function transform(model) {
        var transform = model.toJSON();
        var colGrupos = Alloy.Collections.Clase;
        colGrupos.fetch();
        var arrayGrupos = colGrupos.where({
            Curso: transform.IdCurso
        });
        if (0 == arrayGrupos.length) transform.Grupos = "No hay clases creadas"; else {
            var texto = "Clases ";
            for (var i = 0; arrayGrupos.length > i; i++) {
                var modelo = arrayGrupos[i].toJSON();
                "Clases " == texto ? texto += modelo.Nombre : texto = texto + ", " + modelo.Nombre;
            }
            transform.Grupos = texto;
        }
        return transform;
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "WinCursos";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    $.__views.WinCursos = Ti.UI.createWindow({
        barColor: "#e7effa",
        translucent: "false",
        backgroundColor: "e2effa",
        id: "WinCursos",
        title: "Cursos"
    });
    $.__views.WinCursos && $.addTopLevelView($.__views.WinCursos);
    $.__views.TablaCursos = Ti.UI.createTableView({
        style: Ti.UI.iPhone.TableViewStyle.GROUPED,
        backgroundImage: "backGround320x416Base.png",
        top: "0dp",
        id: "TablaCursos"
    });
    $.__views.WinCursos.add($.__views.TablaCursos);
    $.__views.__alloyId112 = Ti.UI.createImageView({
        image: "library/images/iphone/helpScreen/02HeaderCursos.png",
        height: "70dp",
        id: "__alloyId112"
    });
    $.__views.TablaCursos.headerView = $.__views.__alloyId112;
    $.__views.__alloyId117 = Ti.UI.createImageView({
        image: "library/images/iphone/helpScreen/02FooterCursos.png",
        id: "__alloyId117"
    });
    $.__views.TablaCursos.footerView = $.__views.__alloyId117;
    var __alloyId118 = Alloy.Collections["Curso"] || Curso;
    __alloyId118.on("fetch destroy change add remove reset", __alloyId119);
    exports.destroy = function() {
        __alloyId118.off("fetch destroy change add remove reset", __alloyId119);
    };
    _.extend($, $.__views);
    var arg1 = arguments[0] || {};
    var data = [];
    data = arg1;
    $.WinCursos.addEventListener("focus", function() {
        $.WinCursos.title = data.NombreGrado;
        var cursos = Alloy.Collections.Curso;
        cursos.fetch();
        if ("1" == Ti.App.Properties.getString("Ayuda")) {
            var alertDialog = Ti.UI.createAlertDialog({
                title: "Ayuda",
                message: "En esta pantalla se pueden visualizar los cursos pertenecientes a " + data.NombreGrado + ". Se puede acceder a los diferentes grupos del curso o a través del detalle a las asignaturas existentes para ese curso.",
                buttonNames: [ "OK" ],
                cancel: 0
            });
            alertDialog.show();
        }
    });
    $.WinCursos.addEventListener("close", function() {
        $.destroy();
    });
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;


text:
package com.twitter.finagle.thrift

import com.twitter.finagle.{Service, SimpleFilter}
import com.twitter.io.Buf
import com.twitter.util.Future
import org.apache.thrift.{TApplicationException, TException}
import org.apache.thrift.protocol.{TMessage, TMessageType, TProtocolFactory}
import scala.util.control.NoStackTrace

private[finagle] object UncaughtAppExceptionFilter {

  /**
   * Creates a Thrift exception message for the given `exception` and thrift `thriftRequest`
   * message using the given [[org.apache.thrift.protocol.TProtocolFactory]].
   */
  def writeExceptionMessage(
    thriftRequest: Buf,
    throwable: Throwable,
    protocolFactory: TProtocolFactory
  ): Buf = {
    val reqBytes = Buf.ByteArray.Owned.extract(thriftRequest)
    // NB! This is technically incorrect for one-way calls,
    // but we have no way of knowing it here. We may
    // consider simply not supporting one-way calls at all.
    val msg = InputBuffer.readMessageBegin(reqBytes, protocolFactory)
    val name = msg.name

    val buffer = new OutputBuffer(protocolFactory)
    buffer().writeMessageBegin(new TMessage(name, TMessageType.EXCEPTION, msg.seqid))

    // Note: The wire contents of the exception message differ from Apache's Thrift in that here,
    // e.toString is appended to the error message.
    // As it is the only place where the TApplicationException is constructed with this error code
    // and the stack trace is not serialised, it doesn't make any sense to populate the stack
    // trace at all

    val x = new TApplicationException(
      TApplicationException.INTERNAL_ERROR,
      s"Internal error processing $name: '$throwable'"
    ) with NoStackTrace

    x.write(buffer())
    buffer().writeMessageEnd()
    Buf.ByteArray.Owned(buffer.toArray)
  }

}

private[finagle] class UncaughtAppExceptionFilter(protocolFactory: TProtocolFactory)
    extends SimpleFilter[Array[Byte], Array[Byte]] {
  import UncaughtAppExceptionFilter.writeExceptionMessage

  def apply(request: Array[Byte], service: Service[Array[Byte], Array[Byte]]): Future[Array[Byte]] =
    service(request).handle {
      case e if !e.isInstanceOf[TException] =>
        val buf = Buf.ByteArray.Owned(request)
        val msg = writeExceptionMessage(buf, e, protocolFactory)
        Buf.ByteArray.Owned.extract(msg)
    }
}


text:
require 'spec_helper'

describe Mappington::Path do
	subject {Mappington::Path.new :stroke_color => :blue, :stroke_weight => 5}
	it 'can have a stroke color' do
		subject.stroke_color.should eq :blue
	end
	it 'can have a stroke weight' do
		subject.stroke_weight.should eq 5
	end
	it 'should have some points' do
		subject.points << 'the Eiffel Tower'
		subject.points << [0, 0]
		subject.points.count.should eq 2
	end
	context 'Becoming a URI fragment' do
		let(:path) {Mappington::Path.new}
		it 'should raise an error if the Path has no locations' do
			expect {path.to_s}.to raise_error Mappington::PathError
		end
		it 'should raise an error if the Path only has 1 location' do
			path.points << 'the Eiffel Tower'
			expect {path.to_s}.to raise_error Mappington::PathError
		end
		it 'should become a URI fragment' do
			path.points << 'the Eiffel Tower'
			path.points << [0, 0]
			path.to_s.should eq 'path=color%3Ablack%7Cweight%3A1%7Cthe+Eiffel+Tower%7C0%2C0'
		end
	end
end


text:
<?php

namespace Harbor\DoctrineBundle\DQL;

use \Doctrine\ORM\Query\AST\Functions\FunctionNode;
use \Doctrine\ORM\Query\Lexer;

/**
 * MysqlRand
 *
 * @uses FunctionNode
 * @author Simone Fumagalli - www.iliveinperego.com
 */
class MysqlDateFormat extends FunctionNode
{

    /*
    * holds the date of the DATE_FORMAT statement
    * @var mixed
    */
    protected $dateExpression;

    /**
    * holds the '%format' parameter of the DATE_FORMAT statement
    * @var string
    */
    protected $formatChar;

    /**
     * getSql
     *
     * @param \Doctrine\ORM\Query\SqlWalker $sqlWalker
     * @access public
     * @return string
     */
    public function getSql(\Doctrine\ORM\Query\SqlWalker $sqlWalker)
    {
        return 'DATE_FORMAT(' .
                $sqlWalker->walkArithmeticExpression($this->dateExpression) .
                ','.
                $sqlWalker->walkStringPrimary($this->formatChar) .
                ')';
    }

    /**
     * parse
     *
     * @param \Doctrine\ORM\Query\Parser $parser
     * @access public
     * @return void
     */
    public function parse(\Doctrine\ORM\Query\Parser $parser)
    {
        $parser->match(Lexer::T_IDENTIFIER);
        $parser->match(Lexer::T_OPEN_PARENTHESIS);
        $this->dateExpression = $parser->ArithmeticExpression();
        $parser->match(Lexer::T_COMMA);
        $this->formatChar = $parser->StringPrimary();
        $parser->match(Lexer::T_CLOSE_PARENTHESIS);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Lecidea subramosa J. Lowe

### Remarks
null


text:
// The MIT License (MIT)
//
// Copyright (c) 2016-2022 Camptocamp SA
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import angular from 'angular';
import './contextualdata.css';
import gmfContextualdataModule from 'gmf/contextualdata/module';

import gmfMapComponent from 'gmf/map/component';
import ngeoMiscFilters from 'ngeo/misc/filters';
import ngeoMapModule from 'ngeo/map/module';
import EPSG2056 from 'ngeo/proj/EPSG_2056';
import 'ngeo/proj/EPSG_21781';
import olMap from 'ol/Map';
import olView from 'ol/View';
import olLayerTile from 'ol/layer/Tile';
import olSourceOSM from 'ol/source/OSM';
import options from './options';

/**
 * @type {angular.IModule}
 * @hidden
 */
const myModule = angular.module('gmfapp', [
  'gettext',
  gmfContextualdataModule.name,
  gmfMapComponent.name,
  ngeoMiscFilters.name,
  ngeoMapModule.name,
]);

myModule.value('gmfContextualdatacontentTemplateUrl', 'partials/contextualdata.html');

/**
 * @class
 * @ngInject
 */
function MainController() {
  /**
   * @type {import('ol/Map').default}
   */
  this.map = new olMap({
    layers: [
      new olLayerTile({
        source: new olSourceOSM(),
      }),
    ],
    view: new olView({
      projection: EPSG2056,
      resolutions: [200, 100, 50, 20, 10, 5, 2.5, 2, 1, 0.5],
      center: [2600000, 1200000],
      zoom: 3,
    }),
  });
}

/**
 * @param {import('ol/coordinate').Coordinate} coordinate The coordinate for the right-clicked
 *     point.
 * @param {Object<string, number>} data The data received from the raster service.
 * @returns {Object<string, number>} The additional data to add to the scope for the
 *     contextualdata popover.
 */
MainController.prototype.onRasterData = function (coordinate, data) {
  return {
    elelvation_diff: data.srtm - data.aster,
  };
};

myModule.controller('MainController', MainController);
myModule.constant('gmfContextualDataOptions', {
  projections: ['EPSG:2056', 'EPSG:21781', 'EPSG:4326'],
});

options(myModule);

export default MainController;