text:
#include "stdneb.h"
#include "framesync/framesynchandlerthread.h"
#include "framesync/framesynctimer.h"
#include "threading/interlocked.h"

namespace FrameSync
{
__ImplementClass(FrameSync::FrameSyncHandlerThread, 'FSHT', Messaging::HandlerThreadBase);
__ImplementImageSingleton(FrameSync::FrameSyncHandlerThread);

using namespace Util;
using namespace Threading;
using namespace Messaging;

//------------------------------------------------------------------------------
/**
*/
FrameSyncHandlerThread::FrameSyncHandlerThread() :
    lockStepMode(0),
    frameCount(0),
    curTime(0.0),
    fixedFrameTime(0.0),
    fixedFrameTimeMode(0),
    realTime(0.0)
{
    __ConstructImageSingleton;
    this->threadBarrier.Setup(NumSyncThreads);
    this->msgQueue.SetSignalOnEnqueueEnabled(false);
    this->masterTimer.Start();
}

//------------------------------------------------------------------------------
/**
*/
FrameSyncHandlerThread::~FrameSyncHandlerThread()
{
    __DestructImageSingleton;
}

//------------------------------------------------------------------------------
/**
    Enter lock-step mode, this method must only be called from the
    slave thread.
*/
void
FrameSyncHandlerThread::EnterLockStepMode()
{
    if (0 == this->lockStepMode)
    {
        Interlocked::Exchange(&this->lockStepMode, 1);
        this->ArriveAtSyncPoint(false);
    }
}

//------------------------------------------------------------------------------
/**
    Leave lock-step mode, this method must only be called from the
    slave thread.
*/
void
FrameSyncHandlerThread::LeaveLockStepMode()
{
    if (1 == this->lockStepMode)
    {
        this->ArriveAtSyncPoint(false);
        Interlocked::Exchange(&this->lockStepMode, 0);
    }
}

//------------------------------------------------------------------------------
/**
    This is the central sync point. Every thread will call this method
    at the start of a new frame to synchronize with the other lock-step
    frames. Once all threads have arrived, the master time will be advanced
    and the double-buffered message queues will be flipped.
*/
void
FrameSyncHandlerThread::ArriveAtSyncPoint(bool masterThread)
{
    if (0 != this->lockStepMode)
    {
        // lock-step mode enabled
        if (this->threadBarrier.Arrive())
        {
            // all thread have arrived, perform sync actions and signal other
            // threads to continue
            this->frameCritSect.Enter();
            this->SyncUpdateTime();
            this->SyncFlipMessageQueue();
            this->frameCritSect.Leave();
            this->threadBarrier.SignalContinue();
        }
        else
        {
            // other threads still need to finish their frame, wait until they arrive
            this->threadBarrier.Wait();
        }
    }
    else
    {
        // lock-step mode disabled, the master thread is allowed to run,
        // while client threads wait for the master thread's sync point
        if (masterThread)
        {
            this->frameCritSect.Enter();
            this->SyncUpdateTime();
            this->SyncFlipMessageQueue();
            this->frameSyncEvent.Signal();
            this->frameCritSect.Leave();
        }
        else
        {
            this->frameSyncEvent.Wait();
        }
    }

    // update the thread-local FrameSyncTimer object (if exists)
    this->SyncUpdateThreadLocalFrameSyncTimer();
}

//------------------------------------------------------------------------------
/**
    Start the master timer. This method may be called from any of the
    sync-threads, thus we need to protect with a critical section.
    DO NOT CALL FREQUENTLY!
*/
void
FrameSyncHandlerThread::StartMasterTime()
{
    this->frameCritSect.Enter();
    this->masterTimer.Start();
    this->frameCritSect.Leave();
}

//------------------------------------------------------------------------------
/**
    Stop the master timer, may be called from any of the sync-threads.
    DO NOT CALL FREQUENTLY!
*/
void
FrameSyncHandlerThread::StopMasterTime()
{
    this->frameCritSect.Enter();
    this->masterTimer.Stop();
    this->frameCritSect.Leave();
}

//------------------------------------------------------------------------------
/**
    Reset the master timer, may be called from any of the sync-threads.
    DO NOT CALL FREQUENTLY!
*/
void
FrameSyncHandlerThread::ResetMasterTime()
{
    this->frameCritSect.Enter();
    this->masterTimer.Reset();
    this->frameCritSect.Leave();
}

//------------------------------------------------------------------------------
/**
    Test if the master time is currently running. May be called from any
    of the sync-threads.
    DO NOT CALL FREQUENTLY!
*/
bool
FrameSyncHandlerThread::IsMasterTimeRunning() const
{
    this->frameCritSect.Enter();
    bool isRunning = this->masterTimer.Running();
    this->frameCritSect.Leave();
    return isRunning;
}

//------------------------------------------------------------------------------
/**
    Safely get the current frame time. This is only used for first-time
    init of FrameSyncTimer objects
    DO NOT CALL FREQUENTLY!
*/
Timing::Time
FrameSyncHandlerThread::SafeGetMasterTime() const
{
    this->frameCritSect.Enter();
    Timing::Time t = this->curTime;
    this->frameCritSect.Leave();
    return t;
}

//------------------------------------------------------------------------------
/**
    Update the master time. Since this method is called during the
    sync point, we don't need thread-synchronization.
*/
void
FrameSyncHandlerThread::SyncUpdateTime()
{
    Timing::Time timeDelta(0);
    Timing::Time masterTime = this->masterTimer.GetTime();
    if (1 == this->fixedFrameTimeMode)
    {
        // in fixed frame time mode increase current time
        // by a fixed value
        timeDelta = this->fixedFrameTime;
    }
    else
    {
        // in normal mode increase current time by the time passed
        // since the last SyncUpdateTime call
        timeDelta = masterTime - this->realTime;
    }
    this->curTime += timeDelta;
    this->realTime = masterTime;
    Interlocked::Increment(this->frameCount);
}

//------------------------------------------------------------------------------
/**
    Checks if the current thread has a FrameSyncTimer singleton, and if
    yes, update its time. Call this method from the frame-sync-point.
*/
void
FrameSyncHandlerThread::SyncUpdateThreadLocalFrameSyncTimer()
{
    if (FrameSyncTimer::HasInstance())
    {
        FrameSyncTimer::Instance()->Update(this->curTime);
    }
}

//------------------------------------------------------------------------------
/**
    Flip the message queues, this is called from the sync point.
*/
void
FrameSyncHandlerThread::SyncFlipMessageQueue()
{
    this->msgQueue.DequeueAll(this->msgArray);
}

//------------------------------------------------------------------------------
/**
    Add a message to the producer queue, since we're using double buffering
    so we don't need thread-synchronization.
*/
void
FrameSyncHandlerThread::AddMessage(const GPtr<Message>& msg)
{
    this->msgQueue.Enqueue(msg);
}

//------------------------------------------------------------------------------
/**
    Cancel a pending message from the producer queue. If the message is
    already in the consumer queue, then it's too late to cancel the
    message!
*/
void
FrameSyncHandlerThread::CancelMessage(const GPtr<Message>& msg)
{
    this->msgQueue.EraseMatchingElements(msg);
}

//------------------------------------------------------------------------------
/**
    Wait for a message to be handled.
*/
void
FrameSyncHandlerThread::WaitForMessage(const GPtr<Message>& msg)
{
    n_assert(!this->lockStepMode);
    while (!msg->Handled())
    {
        this->ArriveAtSyncPoint(false);
    }
}

//------------------------------------------------------------------------------
/**
    The central message processing loop.
*/
void
FrameSyncHandlerThread::DoWork()
{
    this->ThreadOpenHandlers();
    do
    {
        bool msgHandled = false;

        // update state of deferred messages
        msgHandled = this->ThreadUpdateDeferredMessages();

        // arrive at sync point as master thread
        this->ArriveAtSyncPoint(true);

        // process messages
        msgHandled |= this->ThreadHandleMessages(this->msgArray);
        this->msgArray.Clear();

        // signal if at least one message has been handled
        if (msgHandled)
        {
            this->ThreadSignalMessageHandled();
        }

        // do per-frame update on attached handlers
        this->ThreadUpdateHandlers();
		Thread::YieldThread();
    }
    while (!this->ThreadStopRequested());

    // cleanup and exit thread
    this->ThreadDiscardDeferredMessages();
    this->ThreadCloseHandlers();
}

//------------------------------------------------------------------------------
/**
    Start the fixed frame time mode. In this mode the current time is
    increased by a fixed value every frame.
*/
void
FrameSyncHandlerThread::StartFixedFrameTime(Timing::Time frameTime)
{
    if (0 == this->fixedFrameTimeMode)
    {
        Interlocked::Exchange(&this->fixedFrameTimeMode, 1);
        this->frameCritSect.Enter();
        this->fixedFrameTime = frameTime;
        this->frameCritSect.Leave();
    }
}

//------------------------------------------------------------------------------
/**
	Stop the fixed frame time mode.
*/
void
FrameSyncHandlerThread::StopFixedFrameTime()
{
    if (1 == this->fixedFrameTimeMode)
    {
        Interlocked::Exchange(&this->fixedFrameTimeMode, 0);
    }
}

} // namespace FrameSync


text:
.tweets-list-container{
    width: 100%;
    overflow: hidden;
}

.tweet-list {
    position: relative;
    list-style-type: none;
    padding: 0;
}

.tweet-list li {
    padding-bottom: 10px;
}

/* Twitter logo before tweet */

.tweet-list.twitter-logo li {
    background: url('../img/tweet.png') no-repeat;
    padding-left: 40px;
    background-position-y: 2px;
}

.tweet-list.twitter-logo li.profile-image{
    background: none;
}

.tweet-list li.profile-image{
    padding-left: 60px;
    min-height: 60px;
}

redpajama_set_name: RedPajamaGithub


text:
set :whenever_command, "bundle exec whenever"
require "bundler/capistrano"
require "whenever/capistrano"
require "thinking_sphinx/deploy/capistrano"

set :application, "railscasts.com"
role :app, application
role :web, application
role :db,  application, :primary => true

set :user, "rbates"
set :deploy_to, "/var/apps/railscasts"
set :deploy_via, :remote_cache
set :use_sudo, false

set :scm, "git"
set :repository, "git://github.com/ryanb/railscasts.git"
set :branch, "master"

namespace :deploy do
  desc "Tell Passenger to restart."
  task :restart, :roles => :web do
    run "touch #{deploy_to}/current/tmp/restart.txt"
  end

  desc "Do nothing on startup so we don't get a script/spin error."
  task :start do
    puts "You may need to restart Apache."
  end

  desc "Symlink extra configs and folders."
  task :symlink_extras do
    run "ln -nfs #{shared_path}/config/database.yml #{release_path}/config/database.yml"
    run "ln -nfs #{shared_path}/config/app_config.yml #{release_path}/config/app_config.yml"
    run "ln -nfs #{shared_path}/config/production.sphinx.conf #{release_path}/config/production.sphinx.conf"
    run "ln -nfs #{shared_path}/assets #{release_path}/public/assets"
    run "ln -nfs #{shared_path}/db/sphinx #{release_path}/db/sphinx"
  end

  desc "Setup shared directory."
  task :setup_shared do
    run "mkdir #{shared_path}/assets"
    run "mkdir #{shared_path}/config"
    run "mkdir #{shared_path}/db"
    run "mkdir #{shared_path}/db/sphinx"
    put File.read("config/examples/database.yml"), "#{shared_path}/config/database.yml"
    put File.read("config/examples/app_config.yml"), "#{shared_path}/config/app_config.yml"
    put File.read("config/examples/production.sphinx.conf"), "#{shared_path}/config/production.sphinx.conf"
    puts "Now edit the config files and fill assets folder in #{shared_path}."
  end

  desc "Sync the public/assets directory."
  task :assets do
    system "rsync -vr --exclude='.DS_Store' public/assets #{user}@#{application}:/var/apps/railscasts/shared/"
  end

  desc "Make sure there is something to deploy"
  task :check_revision, :roles => :web do
    unless `git rev-parse HEAD` == `git rev-parse origin/master`
      puts "WARNING: HEAD is not the same as origin/master"
      puts "Run `git push` to sync changes."
      exit
    end
  end
end

before "deploy", "deploy:check_revision"
after "deploy", "deploy:cleanup" # keeps only last 5 releases
after "deploy:setup", "deploy:setup_shared"
after "deploy:update_code", "deploy:symlink_extras"
before "deploy:update_code", "thinking_sphinx:stop"
after "deploy:update_code", "thinking_sphinx:start"


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.execution;

import com.facebook.airlift.configuration.Config;
import com.facebook.airlift.configuration.ConfigDescription;
import com.facebook.airlift.configuration.DefunctConfig;
import com.facebook.airlift.configuration.LegacyConfig;
import com.facebook.presto.util.PowerOfTwo;
import io.airlift.units.DataSize;
import io.airlift.units.DataSize.Unit;
import io.airlift.units.Duration;
import io.airlift.units.MaxDuration;
import io.airlift.units.MinDuration;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

@DefunctConfig({
        "experimental.big-query-max-task-memory",
        "task.max-memory",
        "task.http-notification-threads",
        "task.info-refresh-max-wait",
        "task.operator-pre-allocated-memory",
        "sink.new-implementation",
        "task.legacy-scheduling-behavior",
        "task.level-absolute-priority"})
public class TaskManagerConfig
{
    private boolean perOperatorCpuTimerEnabled = true;
    private boolean taskCpuTimerEnabled = true;
    private boolean statisticsCpuTimerEnabled = true;
    private boolean perOperatorAllocationTrackingEnabled;
    private boolean taskAllocationTrackingEnabled;
    private DataSize maxPartialAggregationMemoryUsage = new DataSize(16, Unit.MEGABYTE);
    private DataSize maxLocalExchangeBufferSize = new DataSize(32, Unit.MEGABYTE);
    private DataSize maxIndexMemoryUsage = new DataSize(64, Unit.MEGABYTE);
    private boolean shareIndexLoading;
    private int maxWorkerThreads = Runtime.getRuntime().availableProcessors() * 2;
    private Integer minDrivers;
    private Integer initialSplitsPerNode;
    private int minDriversPerTask = 3;
    private int maxDriversPerTask = Integer.MAX_VALUE;
    private int maxTasksPerStage = Integer.MAX_VALUE;
    private Duration splitConcurrencyAdjustmentInterval = new Duration(100, TimeUnit.MILLISECONDS);

    private DataSize sinkMaxBufferSize = new DataSize(32, Unit.MEGABYTE);
    private DataSize maxPagePartitioningBufferSize = new DataSize(32, Unit.MEGABYTE);

    private Duration clientTimeout = new Duration(2, TimeUnit.MINUTES);
    private Duration infoMaxAge = new Duration(15, TimeUnit.MINUTES);

    private Duration statusRefreshMaxWait = new Duration(1, TimeUnit.SECONDS);
    private Duration infoRefreshMaxWait = new Duration(0, TimeUnit.SECONDS);

    private Duration infoUpdateInterval = new Duration(3, TimeUnit.SECONDS);

    private int writerCount = 1;
    private Integer partitionedWriterCount;
    private int taskConcurrency = 16;
    private int httpResponseThreads = 100;
    private int httpTimeoutConcurrency = 3;
    private int httpTimeoutThreads = 3;

    private int taskNotificationThreads = 5;
    private int taskYieldThreads = 3;

    private BigDecimal levelTimeMultiplier = new BigDecimal(2.0);

    private boolean legacyLifespanCompletionCondition;
    private TaskPriorityTracking taskPriorityTracking = TaskPriorityTracking.TASK_FAIR;

    @MinDuration("1ms")
    @MaxDuration("10s")
    @NotNull
    public Duration getStatusRefreshMaxWait()
    {
        return statusRefreshMaxWait;
    }

    @Config("task.status-refresh-max-wait")
    public TaskManagerConfig setStatusRefreshMaxWait(Duration statusRefreshMaxWait)
    {
        this.statusRefreshMaxWait = statusRefreshMaxWait;
        return this;
    }

    @MinDuration("1ms")
    @MaxDuration("10s")
    @NotNull
    public Duration getInfoUpdateInterval()
    {
        return infoUpdateInterval;
    }

    @Config("task.info-update-interval")
    @ConfigDescription("Interval between updating task data")
    public TaskManagerConfig setInfoUpdateInterval(Duration infoUpdateInterval)
    {
        this.infoUpdateInterval = infoUpdateInterval;
        return this;
    }

    @NotNull
    public Duration getInfoRefreshMaxWait()
    {
        return infoRefreshMaxWait;
    }

    @Config("experimental.task.info-update-refresh-max-wait")
    @ConfigDescription("When this is set to non-zero, task info update request will be a long polling with " +
            "given maximum update refresh wait time. This is an experimental config to reduce unnecessary task info update.")
    public TaskManagerConfig setInfoRefreshMaxWait(Duration infoRefreshMaxWait)
    {
        this.infoRefreshMaxWait = infoRefreshMaxWait;
        return this;
    }

    public boolean isPerOperatorCpuTimerEnabled()
    {
        return perOperatorCpuTimerEnabled;
    }

    @LegacyConfig("task.verbose-stats")
    @Config("task.per-operator-cpu-timer-enabled")
    public TaskManagerConfig setPerOperatorCpuTimerEnabled(boolean perOperatorCpuTimerEnabled)
    {
        this.perOperatorCpuTimerEnabled = perOperatorCpuTimerEnabled;
        return this;
    }

    public boolean isTaskCpuTimerEnabled()
    {
        return taskCpuTimerEnabled;
    }

    @Config("task.cpu-timer-enabled")
    public TaskManagerConfig setTaskCpuTimerEnabled(boolean taskCpuTimerEnabled)
    {
        this.taskCpuTimerEnabled = taskCpuTimerEnabled;
        return this;
    }

    public boolean isStatisticsCpuTimerEnabled()
    {
        return statisticsCpuTimerEnabled;
    }

    @Config("task.statistics-cpu-timer-enabled")
    public TaskManagerConfig setStatisticsCpuTimerEnabled(boolean statisticsCpuTimerEnabled)
    {
        this.statisticsCpuTimerEnabled = statisticsCpuTimerEnabled;
        return this;
    }

    public boolean isPerOperatorAllocationTrackingEnabled()
    {
        return perOperatorAllocationTrackingEnabled;
    }

    @Config("task.per-operator-allocation-tracking-enabled")
    public TaskManagerConfig setPerOperatorAllocationTrackingEnabled(boolean perOperatorAllocationTrackingEnabled)
    {
        this.perOperatorAllocationTrackingEnabled = perOperatorAllocationTrackingEnabled;
        return this;
    }

    public boolean isTaskAllocationTrackingEnabled()
    {
        return taskAllocationTrackingEnabled;
    }

    @Config("task.allocation-tracking-enabled")
    public TaskManagerConfig setTaskAllocationTrackingEnabled(boolean taskAllocationTrackingEnabled)
    {
        this.taskAllocationTrackingEnabled = taskAllocationTrackingEnabled;
        return this;
    }

    @NotNull
    public DataSize getMaxPartialAggregationMemoryUsage()
    {
        return maxPartialAggregationMemoryUsage;
    }

    @Config("task.max-partial-aggregation-memory")
    public TaskManagerConfig setMaxPartialAggregationMemoryUsage(DataSize maxPartialAggregationMemoryUsage)
    {
        this.maxPartialAggregationMemoryUsage = maxPartialAggregationMemoryUsage;
        return this;
    }

    @NotNull
    public DataSize getMaxLocalExchangeBufferSize()
    {
        return maxLocalExchangeBufferSize;
    }

    @Config("task.max-local-exchange-buffer-size")
    public TaskManagerConfig setMaxLocalExchangeBufferSize(DataSize size)
    {
        this.maxLocalExchangeBufferSize = size;
        return this;
    }

    @NotNull
    public DataSize getMaxIndexMemoryUsage()
    {
        return maxIndexMemoryUsage;
    }

    @Config("task.max-index-memory")
    public TaskManagerConfig setMaxIndexMemoryUsage(DataSize maxIndexMemoryUsage)
    {
        this.maxIndexMemoryUsage = maxIndexMemoryUsage;
        return this;
    }

    @NotNull
    public boolean isShareIndexLoading()
    {
        return shareIndexLoading;
    }

    @Config("task.share-index-loading")
    public TaskManagerConfig setShareIndexLoading(boolean shareIndexLoading)
    {
        this.shareIndexLoading = shareIndexLoading;
        return this;
    }

    public BigDecimal getLevelTimeMultiplier()
    {
        return levelTimeMultiplier;
    }

    @Config("task.level-time-multiplier")
    @ConfigDescription("Factor that determines the target scheduled time for a level relative to the next")
    @Min(0)
    public TaskManagerConfig setLevelTimeMultiplier(BigDecimal levelTimeMultiplier)
    {
        this.levelTimeMultiplier = levelTimeMultiplier;
        return this;
    }

    @Min(1)
    public int getMaxWorkerThreads()
    {
        return maxWorkerThreads;
    }

    @LegacyConfig("task.shard.max-threads")
    @Config("task.max-worker-threads")
    public TaskManagerConfig setMaxWorkerThreads(int maxWorkerThreads)
    {
        this.maxWorkerThreads = maxWorkerThreads;
        return this;
    }

    @Min(1)
    public int getInitialSplitsPerNode()
    {
        if (initialSplitsPerNode == null) {
            return maxWorkerThreads;
        }
        return initialSplitsPerNode;
    }

    @Config("task.initial-splits-per-node")
    public TaskManagerConfig setInitialSplitsPerNode(int initialSplitsPerNode)
    {
        this.initialSplitsPerNode = initialSplitsPerNode;
        return this;
    }

    @MinDuration("1ms")
    public Duration getSplitConcurrencyAdjustmentInterval()
    {
        return splitConcurrencyAdjustmentInterval;
    }

    @Config("task.split-concurrency-adjustment-interval")
    public TaskManagerConfig setSplitConcurrencyAdjustmentInterval(Duration splitConcurrencyAdjustmentInterval)
    {
        this.splitConcurrencyAdjustmentInterval = splitConcurrencyAdjustmentInterval;
        return this;
    }

    @Min(1)
    public int getMinDrivers()
    {
        if (minDrivers == null) {
            return 2 * maxWorkerThreads;
        }
        return minDrivers;
    }

    @Config("task.min-drivers")
    public TaskManagerConfig setMinDrivers(int minDrivers)
    {
        this.minDrivers = minDrivers;
        return this;
    }

    @Min(1)
    public int getMaxDriversPerTask()
    {
        return maxDriversPerTask;
    }

    @Config("task.max-drivers-per-task")
    @ConfigDescription("Maximum number of drivers a task can run")
    public TaskManagerConfig setMaxDriversPerTask(int maxDriversPerTask)
    {
        this.maxDriversPerTask = maxDriversPerTask;
        return this;
    }

    @Min(1)
    public int getMinDriversPerTask()
    {
        return minDriversPerTask;
    }

    @Config("task.min-drivers-per-task")
    @ConfigDescription("Minimum number of drivers guaranteed to run per task given there is sufficient work to do")
    public TaskManagerConfig setMinDriversPerTask(int minDriversPerTask)
    {
        this.minDriversPerTask = minDriversPerTask;
        return this;
    }

    @Min(1)
    public int getMaxTasksPerStage()
    {
        return maxTasksPerStage;
    }

    @Config("stage.max-tasks-per-stage")
    @ConfigDescription("Maximum number of tasks for a non source distributed stage")
    public TaskManagerConfig setMaxTasksPerStage(int maxTasksPerStage)
    {
        this.maxTasksPerStage = maxTasksPerStage;
        return this;
    }

    @NotNull
    public DataSize getSinkMaxBufferSize()
    {
        return sinkMaxBufferSize;
    }

    @Config("sink.max-buffer-size")
    public TaskManagerConfig setSinkMaxBufferSize(DataSize sinkMaxBufferSize)
    {
        this.sinkMaxBufferSize = sinkMaxBufferSize;
        return this;
    }

    @NotNull
    public DataSize getMaxPagePartitioningBufferSize()
    {
        return maxPagePartitioningBufferSize;
    }

    @Config("driver.max-page-partitioning-buffer-size")
    public TaskManagerConfig setMaxPagePartitioningBufferSize(DataSize size)
    {
        this.maxPagePartitioningBufferSize = size;
        return this;
    }

    @MinDuration("5s")
    @NotNull
    public Duration getClientTimeout()
    {
        return clientTimeout;
    }

    @Config("task.client.timeout")
    public TaskManagerConfig setClientTimeout(Duration clientTimeout)
    {
        this.clientTimeout = clientTimeout;
        return this;
    }

    @NotNull
    public Duration getInfoMaxAge()
    {
        return infoMaxAge;
    }

    @Config("task.info.max-age")
    public TaskManagerConfig setInfoMaxAge(Duration infoMaxAge)
    {
        this.infoMaxAge = infoMaxAge;
        return this;
    }

    @Min(1)
    @PowerOfTwo
    public int getWriterCount()
    {
        return writerCount;
    }

    @Config("task.writer-count")
    @ConfigDescription("Number of writers per task")
    public TaskManagerConfig setWriterCount(int writerCount)
    {
        this.writerCount = writerCount;
        return this;
    }

    @Min(1)
    @PowerOfTwo
    public Integer getPartitionedWriterCount()
    {
        return partitionedWriterCount;
    }

    @Config("task.partitioned-writer-count")
    @ConfigDescription("Number of writers per task for partitioned writes. If not set, the number set by task.writer-count will be used")
    public TaskManagerConfig setPartitionedWriterCount(Integer partitionedWriterCount)
    {
        this.partitionedWriterCount = partitionedWriterCount;
        return this;
    }

    @Min(1)
    @PowerOfTwo
    public int getTaskConcurrency()
    {
        return taskConcurrency;
    }

    @Config("task.concurrency")
    @ConfigDescription("Default number of local parallel jobs per worker")
    public TaskManagerConfig setTaskConcurrency(int taskConcurrency)
    {
        this.taskConcurrency = taskConcurrency;
        return this;
    }

    @Min(1)
    public int getHttpResponseThreads()
    {
        return httpResponseThreads;
    }

    @Config("task.http-response-threads")
    public TaskManagerConfig setHttpResponseThreads(int httpResponseThreads)
    {
        this.httpResponseThreads = httpResponseThreads;
        return this;
    }

    @Min(1)
    public int getHttpTimeoutThreads()
    {
        return httpTimeoutThreads;
    }

    @Config("task.http-timeout-threads")
    @ConfigDescription("Total number of timeout threads across all timeout thread pools")
    public TaskManagerConfig setHttpTimeoutThreads(int httpTimeoutThreads)
    {
        this.httpTimeoutThreads = httpTimeoutThreads;
        return this;
    }

    @Min(1)
    public int getHttpTimeoutConcurrency()
    {
        return httpTimeoutConcurrency;
    }

    @Config("task.http-timeout-concurrency")
    @ConfigDescription("Number of thread pools to handle timeouts. Threads per pool is calculated by http-timeout-threads / http-timeout-concurrency")
    public TaskManagerConfig setHttpTimeoutConcurrency(int httpTimeoutConcurrency)
    {
        this.httpTimeoutConcurrency = httpTimeoutConcurrency;
        return this;
    }

    @Min(1)
    public int getTaskNotificationThreads()
    {
        return taskNotificationThreads;
    }

    @Config("task.task-notification-threads")
    @ConfigDescription("Number of threads used for internal task event notifications")
    public TaskManagerConfig setTaskNotificationThreads(int taskNotificationThreads)
    {
        this.taskNotificationThreads = taskNotificationThreads;
        return this;
    }

    @Min(1)
    public int getTaskYieldThreads()
    {
        return taskYieldThreads;
    }

    @Config("task.task-yield-threads")
    @ConfigDescription("Number of threads used for setting yield signals")
    public TaskManagerConfig setTaskYieldThreads(int taskYieldThreads)
    {
        this.taskYieldThreads = taskYieldThreads;
        return this;
    }

    @Deprecated
    public boolean isLegacyLifespanCompletionCondition()
    {
        return legacyLifespanCompletionCondition;
    }

    @Deprecated
    @Config("task.legacy-lifespan-completion-condition")
    public TaskManagerConfig setLegacyLifespanCompletionCondition(boolean legacyLifespanCompletionCondition)
    {
        this.legacyLifespanCompletionCondition = legacyLifespanCompletionCondition;
        return this;
    }

    @NotNull
    public TaskPriorityTracking getTaskPriorityTracking()
    {
        return taskPriorityTracking;
    }

    @Config("task.task-priority-tracking")
    public TaskManagerConfig setTaskPriorityTracking(TaskPriorityTracking taskPriorityTracking)
    {
        this.taskPriorityTracking = taskPriorityTracking;
        return this;
    }

    public enum TaskPriorityTracking
    {
        TASK_FAIR,
        QUERY_FAIR,
    }
}


text:
DV.Schema.states.ViewText = {

  enter: function(sourceState){
    this.dragReporter.unBind();
    this.helpers.resetNavigationState();
    this.elements.window.scrollTop(0);
    this.acceptInput.allow();
    this.pageSet.zoomText();
    return true;
  },
  ViewText: function(){
    this.helpers.toggleContent('viewText');
    this.events.loadText();

    return true;
  },
  exit: function(destinationState){
    this.helpers.resetNavigationState();
    this.elements.collection.width(this.models.pages.width + 110);
    return true;
  }
};


text:
<ion-side-menus>

  <ion-pane ion-side-menu-content>
    <ion-nav-bar class="bar-dark nav-title-slide-ios7">
      <ion-nav-back-button class="button-clear"></ion-nav-back-button>
    </ion-nav-bar>
    <ion-nav-view name="menuContent" animation="fade-in"></ion-nav-view>
  </ion-pane>

  <ion-side-menu side="left">

Left

    <ion-content class="has-header">
      <ion-list>
        <ion-item nav-clear menu-close ng-click="login()">
          Login
        </ion-item>
        <ion-item nav-clear menu-close href="#/app/search">
          Search
        </ion-item>
        <ion-item nav-clear menu-close href="#/app/browse">
          Browse
        </ion-item>
        <ion-item nav-clear menu-close href="#/app/planets">
          Planet
        </ion-item>
      </ion-list>
    </ion-content>
  </ion-side-menu>
</ion-side-menus>


text:
package com.google.template.soy;

import static com.google.common.truth.Truth.assertThat;
import static com.google.template.soy.MainClassUtils.runInternal;

import com.google.common.collect.ImmutableList;
import com.google.template.soy.MainClassUtils.Main;
import com.google.template.soy.base.SourceLocation;
import com.google.template.soy.error.SoyCompilationException;
import com.google.template.soy.error.SoyError;
import com.google.template.soy.error.SoyErrorKind;

import junit.framework.TestCase;

import java.io.IOException;

/**
 * Tests for {@link MainClassUtils}.
 *
 * @author brndn@google.com (Brendan Linn)
 */
public final class MainClassUtilsTest extends TestCase {

  public void testMainMethodThrowsNothing() {
    assertThat(
            runInternal(
                new Main() {
                  @Override
                  public void main() {}
                }))
        .isEqualTo(0);
  }

  public void testMainMethodThrowsIOException() {
    assertThat(
            runInternal(
                new Main() {
                  @Override
                  public void main() throws IOException {
                    throw new IOException();
                  }
                }))
        .isEqualTo(1);
  }

  public void testMainMethodThrowsUncheckedException() {
    assertThat(
            runInternal(
                new Main() {
                  @Override
                  public void main() throws IOException {
                    throw new RuntimeException();
                  }
                }))
        .isEqualTo(1);
  }

  public void testMainMethodReturnsSoyErrorKinds() {
    assertThat(
            runInternal(
                new Main() {
                  @Override
                  public void main() {
                    throw new SoyCompilationException(
                        ImmutableList.of(
                            SoyError.DEFAULT_FACTORY.create(
                                new SourceLocation("foo.soy"), SoyErrorKind.of(""))));
                  }
                }))
        .isEqualTo(1);
  }

}


text:
namespace apps {

// Handles network-related tasks for app_shell on Chrome OS.
class ShellNetworkController : public chromeos::NetworkStateHandlerObserver {
 public:
  // This class must be instantiated after chromeos::DBusThreadManager and
  // destroyed before it.
  ShellNetworkController();
  virtual ~ShellNetworkController();

  // chromeos::NetworkStateHandlerObserver overrides:
  virtual void NetworkListChanged() OVERRIDE;
  virtual void DefaultNetworkChanged(
      const chromeos::NetworkState* state) OVERRIDE;

 private:
  // Controls whether scanning is performed periodically.
  void SetScanningEnabled(bool enabled);

  // Asks shill to scan for networks.
  void RequestScan();

  // If not currently connected or connecting, chooses a wireless network and
  // asks shill to connect to it.
  void ConnectIfUnconnected();

  // Handles a successful or failed connection attempt.
  void HandleConnectionSuccess();
  void HandleConnectionError(
      const std::string& error_name,
      scoped_ptr<base::DictionaryValue> error_data);

  // True when ConnectIfUnconnected() has asked shill to connect but the attempt
  // hasn't succeeded or failed yet. This is tracked to avoid sending duplicate
  // requests before chromeos::NetworkStateHandler has acknowledged the initial
  // connection attempt.
  bool waiting_for_connection_result_;

  // Invokes RequestScan() periodically.
  base::RepeatingTimer<ShellNetworkController> scan_timer_;

  base::WeakPtrFactory<ShellNetworkController> weak_ptr_factory_;

  DISALLOW_COPY_AND_ASSIGN(ShellNetworkController);
};

}  // namespace apps

#endif  // APPS_SHELL_BROWSER_SHELL_NETWORK_CONTROLLER_CHROMEOS_H_


text:
// Copyright 2019 The SwiftShader Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef VK_DEBUG_VARIABLE_HPP_
#define VK_DEBUG_VARIABLE_HPP_

#include "ID.hpp"
#include "Value.hpp"

#include "System/Debug.hpp"

#include "marl/mutex.h"
#include "marl/tsa.h"

#include <algorithm>
#include <atomic>
#include <limits>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

namespace vk {
namespace dbg {

// Variable is a named value.
struct Variable
{
	std::string name;
	std::shared_ptr<Value> value;

	// operator bool returns true iff value is not nullptr.
	operator bool() const { return value != nullptr; }
};

// Variables is an interface to a collection of named values.
class Variables
{
public:
	using ID = dbg::ID<Variables>;

	using ForeachCallback = std::function<bool(const Variable &)>;
	using FindCallback = std::function<void(const Variable &)>;

	inline Variables();
	virtual ~Variables();

	// foreach() calls cb with each of the variables in the container, while cb
	// returns true.
	// foreach() will return when cb returns false.
	inline void foreach(const ForeachCallback &cb);

	// foreach() calls cb with each of the variables in the container within the
	// indexed range: [startIndex, startIndex+count), while cb returns true.
	// foreach() will return when cb returns false.
	virtual void foreach(size_t startIndex, size_t count, const ForeachCallback &cb) = 0;

	// get() looks up and returns the variable with the given name.
	virtual std::shared_ptr<Value> get(const std::string &name);

	// string() returns the list of variables formatted to a string using the
	// given flags.
	virtual std::string string(const FormatFlags &fmt /* = FormatFlags::Default */);

	// The unique identifier of the variables.
	const ID id;

private:
	static std::atomic<int> nextID;
};

Variables::Variables()
    : id(nextID++)
{}

void Variables::foreach(const ForeachCallback &cb)
{
	foreach(0, std::numeric_limits<size_t>::max(), cb);
}

// VariableContainer is mutable collection of named values.
class VariableContainer : public Variables
{
public:
	using ID = dbg::ID<VariableContainer>;

	inline void foreach(size_t startIndex, size_t count, const ForeachCallback &cb) override;
	inline std::shared_ptr<Value> get(const std::string &name) override;

	// put() places the variable var into the container.
	inline void put(const Variable &var);

	// put() places the variable with the given name and value into the container.
	inline void put(const std::string &name, const std::shared_ptr<Value> &value);

	// extend() adds base to the list of Variables that will be searched and
	// traversed for variables after those in this VariableContainer are
	// searched / traversed.
	inline void extend(const std::shared_ptr<Variables> &base);

private:
	struct ForeachIndex
	{
		size_t start;
		size_t count;
	};

	template<typename F>
	inline void foreach(ForeachIndex &index, const F &cb);

	mutable marl::mutex mutex;
	std::vector<Variable> variables GUARDED_BY(mutex);
	std::unordered_map<std::string, int> indices GUARDED_BY(mutex);
	std::vector<std::shared_ptr<Variables>> extends GUARDED_BY(mutex);
};

void VariableContainer::foreach(size_t startIndex, size_t count, const ForeachCallback &cb)
{
	auto index = ForeachIndex{ startIndex, count };
	foreach(index, cb);
}

template<typename F>
void VariableContainer::foreach(ForeachIndex &index, const F &cb)
{
	marl::lock lock(mutex);
	for(size_t i = index.start; i < variables.size() && i < index.count; i++)
	{
		if(!cb(variables[i]))
		{
			return;
		}
	}

	index.start -= std::min(index.start, variables.size());
	index.count -= std::min(index.count, variables.size());

	for(auto &base : extends)
	{
		base->foreach(index.start, index.count, cb);
	}
}

std::shared_ptr<Value> VariableContainer::get(const std::string &name)
{
	marl::lock lock(mutex);
	for(auto const &var : variables)
	{
		if(var.name == name)
		{
			return var.value;
		}
	}
	for(auto &base : extends)
	{
		if(auto val = base->get(name))
		{
			return val;
		}
	}
	return nullptr;
}

void VariableContainer::put(const Variable &var)
{
	ASSERT(var.value);

	marl::lock lock(mutex);
	auto it = indices.find(var.name);
	if(it == indices.end())
	{
		indices.emplace(var.name, variables.size());
		variables.push_back(var);
	}
	else
	{
		variables[it->second].value = var.value;
	}
}

void VariableContainer::put(const std::string &name,
                            const std::shared_ptr<Value> &value)
{
	put({ name, value });
}

void VariableContainer::extend(const std::shared_ptr<Variables> &base)
{
	marl::lock lock(mutex);
	extends.emplace_back(base);
}

}  // namespace dbg
}  // namespace vk

#endif  // VK_DEBUG_VARIABLE_HPP_


text:
package pe.joedayz.ventas.persistence;

import javax.persistence.Persistence;

public class CrearTablas {

	public static void main(String[] args) {
		Persistence.createEntityManagerFactory("VentasPU");

	}

}


text:
package debug

import "runtime/debug"

// LoudPanic panics in a way that gets all goroutine stacks printed on stderr.
func LoudPanic(x interface{}) {
	debug.SetTraceback("all")
	panic(x)
}


text:
package play.cache;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.Optional;

import javax.inject.Inject;
import javax.inject.Singleton;

import akka.Done;
import play.libs.Scala;
import scala.concurrent.duration.Duration;

import scala.compat.java8.OptionConverters;
import static scala.compat.java8.FutureConverters.toJava;

/**
 * Adapts a Scala AsyncCacheApi to a Java AsyncCacheApi. This is Play's default Java AsyncCacheApi implementation.
 */
@Singleton
public class DefaultAsyncCacheApi implements AsyncCacheApi {

    private final play.api.cache.AsyncCacheApi asyncCacheApi;

    @Inject
    public DefaultAsyncCacheApi(play.api.cache.AsyncCacheApi cacheApi) {
        this.asyncCacheApi = cacheApi;
    }

    @Override
    public SyncCacheApi sync() {
        return new SyncCacheApiAdapter(asyncCacheApi.sync());
    }

    @Override
    @Deprecated
    public <T> CompletionStage<T> get(String key) {
        return toJava(asyncCacheApi.get(key, Scala.<T>classTag())).thenApply(Scala::orNull);
    }

    @Override
    public <T> CompletionStage<Optional<T>> getOptional(String key) {
        return toJava(asyncCacheApi.get(key, Scala.<T>classTag())).thenApply(OptionConverters::toJava);
    }

    @Override
    public <T> CompletionStage<T> getOrElseUpdate(String key, Callable<CompletionStage<T>> block, int expiration) {
        return toJava(
            asyncCacheApi.getOrElseUpdate(key, intToDuration(expiration), Scala.asScalaWithFuture(block), Scala.<T>classTag()));
    }

    @Override
    public <T> CompletionStage<T> getOrElseUpdate(String key, Callable<CompletionStage<T>> block) {
        return toJava(asyncCacheApi.getOrElseUpdate(key, Duration.Inf(), Scala.asScalaWithFuture(block), Scala.<T>classTag()));
    }

    @Override
    public CompletionStage<Done> set(String key, Object value, int expiration) {
        return toJava(asyncCacheApi.set(key, value, intToDuration(expiration)));
    }

    @Override
    public CompletionStage<Done> set(String key, Object value) {
        return toJava(asyncCacheApi.set(key, value, Duration.Inf()));
    }

    @Override
    public CompletionStage<Done> remove(String key) {
        return toJava(asyncCacheApi.remove(key));
    }

    @Override
    public CompletionStage<Done> removeAll() {
        return toJava(asyncCacheApi.removeAll());
    }

    private Duration intToDuration(int seconds) {
      return seconds == 0 ? Duration.Inf() : Duration.apply(seconds, TimeUnit.SECONDS);
    }
}


text:
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Ajax - oblig 1</title>

Memberlist

<input type="button" id="addMemberBtn" value="Add member" onclick="ctrl.addMemberdialog()" />


text:
<?php

class nggMediaRss {

	/**
	 * Function called by the wp_head action to output the RSS link for medias
	 */
	function add_mrss_alternate_link() {
		echo "<link id='MediaRSS' rel='alternate' type='application/rss+xml' title='NextGEN Gallery RSS Feed' href='" . nggMediaRss::get_mrss_url() . "' />\n";
	}

	/**
	 * Add the javascript required to enable PicLens/CoolIris support
	 */
	function add_piclens_javascript() {
        if (is_ssl())
            wp_enqueue_script( 'piclens', 'https://lite.piclens.com/current/piclens_optimized.js', array(), false, true);
		else
            wp_enqueue_script( 'piclens', 'http://lite.piclens.com/current/piclens_optimized.js', array(), false, true);
	}

	/**
	 * Get the URL of the general media RSS
	 */
	function get_mrss_url() {
		return NGGALLERY_URLPATH . 'xml/media-rss.php';
	}

	/**
	 * Get the URL of a gallery media RSS
	 */
	function get_gallery_mrss_url($gid, $prev_next = false) {
		return nggMediaRss::get_mrss_url() . '?' . ('gid=' . $gid . ($prev_next ? '&prev_next=true' : '') . '&mode=gallery');
	}

	/**
	 * Get the URL of an album media RSS
	 */
	function get_album_mrss_url($aid) {
		return nggMediaRss::get_mrss_url() . '?' . ('aid=' . $aid . '&mode=album');
	}

	/**
	 * Get the URL of the media RSS for last pictures
	 */
	function get_last_pictures_mrss_url($page = 0, $show = 30) {
		return nggMediaRss::get_mrss_url() . '?' . ('show=' . $show . '&page=' . $page . '&mode=last_pictures');
	}

	/**
	 * Get the XML <rss> node corresponding to the last pictures registered
	 *
	 * @param page The current page (defaults to 0)
	 * @param show The number of pictures to include in one field (default 30)
	 */
	function get_last_pictures_mrss($page = 0, $show = 30) {
		$images = nggdb::find_last_images($page, $show);

		$title = stripslashes(get_option('blogname'));
		$description = stripslashes(get_option('blogdescription'));
		$link = site_url();
		$prev_link = ($page > 0) ? nggMediaRss::get_last_pictures_mrss_url($page-1, $show) : '';
		$next_link = count($images)!=0 ? nggMediaRss::get_last_pictures_mrss_url($page+1, $show) : '';

		return nggMediaRss::get_mrss_root_node($title, $description, $link, $prev_link, $next_link, $images);
	}

	/**
	 * Get the XML <rss> node corresponding to a gallery
	 *
	 * @param $gallery (object) The gallery to include in RSS
	 * @param $prev_gallery (object) The previous gallery to link in RSS (null if none)
	 * @param $next_gallery (object) The next gallery to link in RSS (null if none)
	 */
	function get_gallery_mrss($gallery, $prev_gallery = null, $next_gallery = null) {

		$ngg_options = nggGallery::get_option('ngg_options');
		//Set sort order value, if not used (upgrade issue)
		$ngg_options['galSort'] = ($ngg_options['galSort']) ? $ngg_options['galSort'] : 'pid';
		$ngg_options['galSortDir'] = ($ngg_options['galSortDir'] == 'DESC') ? 'DESC' : 'ASC';

		$title = stripslashes(nggGallery::i18n($gallery->title));
		$description = stripslashes(nggGallery::i18n($gallery->galdesc));
		$link = nggMediaRss::get_permalink($gallery->pageid);
		$prev_link = ( $prev_gallery != null) ? nggMediaRss::get_gallery_mrss_url($prev_gallery->gid, true) : '';
		$next_link = ( $next_gallery != null) ? nggMediaRss::get_gallery_mrss_url($next_gallery->gid, true) : '';
		$images = nggdb::get_gallery($gallery->gid, $ngg_options['galSort'], $ngg_options['galSortDir']);

		return nggMediaRss::get_mrss_root_node($title, $description, $link, $prev_link, $next_link, $images);
	}

	/**
	 * Get the XML <rss> node corresponding to an album
	 *
	 * @param $album The album to include in RSS
	 */
	function get_album_mrss($album) {

		$title = stripslashes(nggGallery::i18n($album->name));
		$description = '';
		$link = nggMediaRss::get_permalink(0);
		$prev_link = '';
		$next_link = '';
		$images = nggdb::find_images_in_album($album->id);

		return nggMediaRss::get_mrss_root_node($title, $description, $link, $prev_link, $next_link, $images);
	}

	/**
	 * Get the XML <rss> node
	 */
	function get_mrss_root_node($title, $description, $link, $prev_link, $next_link, $images) {

		if ($prev_link != '' || $next_link != '')
			$out = "<rss version='2.0' xmlns:media='http://search.yahoo.com/mrss/' xmlns:atom='http://www.w3.org/2005/Atom'>\n" ;
		else
			$out = "<rss version='2.0' xmlns:media='http://search.yahoo.com/mrss/'>\n";

		$out .= "\t<channel>\n";

		$out .= nggMediaRss::get_generator_mrss_node();
		$out .= nggMediaRss::get_title_mrss_node($title);
		$out .= nggMediaRss::get_description_mrss_node($description);
		$out .= nggMediaRss::get_link_mrss_node($link);

        if ($prev_link != '' || $next_link != '')
        	$out .= nggMediaRss::get_self_node(nggMediaRss::get_mrss_url());
		if ($prev_link!='') {
			$out .= nggMediaRss::get_previous_link_mrss_node($prev_link);
		}
		if ($next_link!='') {
			$out .= nggMediaRss::get_next_link_mrss_node($next_link);
		}

		foreach ($images as $image) {
			$out .= nggMediaRss::get_image_mrss_node($image);
		}

		$out .= "\t</channel>\n";
		$out .= "</rss>\n";

		return $out;
	}

	/**
	 * Get the XML <generator> node
	 */
	function get_generator_mrss_node($indent = "\t\t") {
		return $indent . "<generator><![CDATA[NextGEN Gallery [http://nextgen-gallery.com]]]></generator>\n";
	}

	/**
	 * Get the XML <title> node
	 */
	function get_title_mrss_node($title, $indent = "\t\t") {
		return $indent . "<title>" . $title . "</title>\n";
	}

	/**
	 * Get the XML <description> node
	 */
	function get_description_mrss_node($description, $indent = "\t\t") {
		return $indent . "<description>" . $description . "</description>\n";
	}

	/**
	 * Get the XML <link> node
	 */
	function get_link_mrss_node($link, $indent = "\t\t") {
		return $indent . "<link><![CDATA[" . htmlspecialchars($link) . "]]></link>\n";
	}

	/**
	 * Get the XML <atom:link self> node
	 */
	function get_self_node($link, $indent = "\t\t") {
		return $indent . "<atom:link rel='self' href='" . htmlspecialchars($link) . "' type='application/rss+xml' />\n";
	}

	/**
	 * Get the XML <atom:link previous> node
	 */
	function get_previous_link_mrss_node($link, $indent = "\t\t") {
		return $indent . "<atom:link rel='previous' href='" . htmlspecialchars($link) . "' />\n";
	}

	/**
	 * Get the XML <atom:link next> node
	 */
	function get_next_link_mrss_node($link, $indent = "\t\t") {
		return $indent . "<atom:link rel='next' href='" . htmlspecialchars($link) . "' />\n";
	}

	/**
	 * Get the XML <item> node corresponding to one single image
	 *
	 * @param $image The image object
	 */
	function get_image_mrss_node($image, $indent = "\t\t" ) {
		$ngg_options = nggGallery::get_option('ngg_options');

		$tags = $image->get_tags();
		$tag_names = '';
		foreach ($tags as $tag) {
			$tag_names .= ($tag_names=='' ? $tag->name : ', ' . $tag->name);
		}

		$title = html_entity_decode(stripslashes($image->alttext));
		$desc = html_entity_decode(stripslashes($image->description));

		$thumbwidth = $ngg_options['thumbwidth'];
		$thumbheight = ($ngg_options['thumbfix'] ? $ngg_options['thumbheight'] : $thumbwidth);

		$out  = $indent . "<item>\n";
		$out .= $indent . "\t<title><![CDATA[" . nggGallery::i18n($title, 'pic_' . $image->pid . '_alttext') . "]]></title>\n";
		$out .= $indent . "\t<description><![CDATA[" . nggGallery::i18n($desc, 'pic_' . $image->pid . '_description') . "]]></description>\n";
		$out .= $indent . "\t<link><![CDATA[" . $image->get_permalink() . "]]></link>\n";
        $out .= $indent . "\t<guid>image-id:" . $image->pid . "</guid>\n";
		$out .= $indent . "\t<media:content url='" . esc_url($image->imageURL) . "' medium='image' />\n";
		$out .= $indent . "\t<media:title><![CDATA[" . nggGallery::i18n($title, 'pic_' . $image->pid . '_alttext') . "]]></media:title>\n";
		$out .= $indent . "\t<media:description><![CDATA[" . nggGallery::i18n($desc, 'pic_' . $image->pid . '_description') . "]]></media:description>\n";
		$out .= $indent . "\t<media:thumbnail url='" . esc_url($image->thumbURL) . "' width='" . $thumbwidth . "' height='" . $thumbheight . "' />\n";
		$out .= $indent . "\t<media:keywords><![CDATA[" . nggGallery::i18n($tag_names) . "]]></media:keywords>\n";
		$out .= $indent . "\t<media:copyright><![CDATA[Copyright (c) " . get_option("blogname") . " (" . site_url() . ")]]></media:copyright>\n";
		$out .= $indent . "</item>\n";

		return $out;
	}

	function get_permalink($page_id) {
		if ($page_id == 0)
			$permalink = site_url();
		else
			$permalink = get_permalink($page_id);

		return $permalink;
	}

}


text:
//===--- ClassMetadataVisitor.h - CRTP for class metadata -------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// A CRTP helper class for visiting all of the known fields in a class
// metadata object.
//
//===----------------------------------------------------------------------===//

#ifndef SWIFT_IRGEN_CLASSMETADATAVISITOR_H
#define SWIFT_IRGEN_CLASSMETADATAVISITOR_H

#include "swift/AST/ASTContext.h"
#include "swift/AST/SubstitutionMap.h"
#include "swift/SIL/SILDeclRef.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILVTable.h"
#include "swift/SIL/SILVTableVisitor.h"
#include "IRGen.h"
#include "NominalMetadataVisitor.h"

namespace swift {
namespace irgen {

class IRGenModule;

/// Returns true if the given SILVTable entry needs to be reified as a runtime
/// vtable entry.
///
/// Methods that have no overrides, and no ABI constraints that require a
/// vtable to be present, can be left out of the runtime vtable for classes.
bool methodRequiresReifiedVTableEntry(IRGenModule &IGM,
                                      const SILVTable *vtable,
                                      SILDeclRef method);

/// A CRTP class for laying out class metadata.  Note that this does
/// *not* handle the metadata template stuff.
template <class Impl> class ClassMetadataVisitor
    : public NominalMetadataVisitor<Impl>,
      public SILVTableVisitor<Impl> {
  using super = NominalMetadataVisitor<Impl>;

protected:
  using super::IGM;
  using super::asImpl;

  /// The most-derived class.
  ClassDecl *const Target;

  /// SILVTable entry for the class.
  const SILVTable *VTable;

  ClassMetadataVisitor(IRGenModule &IGM, ClassDecl *target)
    : super(IGM), Target(target),
      VTable(IGM.getSILModule().lookUpVTable(target, /*deserialize*/ false)) {}

public:
  void layout() {
    static_assert(MetadataAdjustmentIndex::Class == 2,
                  "Adjustment index must be synchronized with this layout");

    // HeapMetadata header.
    asImpl().addDestructorFunction();

    // Metadata header.
    super::layout();

    // ClassMetadata header. This must be layout-compatible with Objective-C
    // classes when interoperability is enabled.
    asImpl().addSuperclass();
    if (IGM.ObjCInterop) {
      asImpl().addClassCacheData();
      asImpl().addClassDataPointer();
    }

    asImpl().addClassFlags();
    asImpl().addInstanceAddressPoint();
    asImpl().addInstanceSize();
    asImpl().addInstanceAlignMask();
    asImpl().addRuntimeReservedBits();
    asImpl().addClassSize();
    asImpl().addClassAddressPoint();
    asImpl().addNominalTypeDescriptor();
    asImpl().addIVarDestroyer();

    // Class members.
    addClassMembers(Target);
  }

  /// Notes the beginning of the field offset vector for a particular ancestor
  /// of a generic-layout class.
  void noteStartOfFieldOffsets(ClassDecl *whichClass) {}

  /// Notes the end of the field offset vector for a particular ancestor
  /// of a generic-layout class.
  void noteEndOfFieldOffsets(ClassDecl *whichClass) {}

private:
  /// Add fields associated with the given class and its bases.
  void addClassMembers(ClassDecl *theClass) {
    // Visit the superclass first.
    if (auto *superclassDecl = theClass->getSuperclassDecl()) {
      if (superclassDecl->hasClangNode()) {
        // Nothing to do; Objective-C classes do not add new members to
        // Swift class metadata.
      } else if (IGM.hasResilientMetadata(superclassDecl, ResilienceExpansion::Maximal)) {
        // Runtime metadata instantiation will initialize our field offset
        // vector and vtable entries.
        //
        // Metadata access needs to access our fields relative to a
        // global variable.
        asImpl().noteResilientSuperclass();
      } else {
        // NB: We don't apply superclass substitutions to members because we want
        // consistent metadata layout between generic superclasses and concrete
        // subclasses.
        addClassMembers(superclassDecl);
      }
    }

    // Note that we have to emit a global variable storing the metadata
    // start offset, or access remaining fields relative to one.
    asImpl().noteStartOfImmediateMembers(theClass);

    // Add space for the generic parameters, if applicable.
    // This must always be the first item in the immediate members.
    asImpl().addGenericFields(theClass, theClass);

    // If the class has resilient storage, we cannot make any assumptions about
    // its storage layout, so skip the rest of this method.
    if (IGM.isResilient(theClass, ResilienceExpansion::Maximal))
      return;

    // A class only really *needs* a field-offset vector in the
    // metadata if:
    //   - it's in a generic context and
    //   - there might exist a context which
    //     - can access the class's field storage directly and
    //     - sees the class as having a possibly dependent layout.
    //
    // A context which knows that the class does not have a dependent
    // layout should be able to just use a direct field offset
    // (possibly a constant one).
    //
    // But we currently always give classes field-offset vectors,
    // whether they need them or not.
    asImpl().noteStartOfFieldOffsets(theClass);
    for (auto field :
           theClass->getStoredPropertiesAndMissingMemberPlaceholders()) {
      addFieldEntries(field);
    }
    asImpl().noteEndOfFieldOffsets(theClass);

    // If the class has resilient metadata, we cannot make any assumptions
    // about its metadata layout, so skip the rest of this method.
    if (IGM.hasResilientMetadata(theClass, ResilienceExpansion::Maximal))
      return;

    // Add vtable entries.
    asImpl().addVTableEntries(theClass);
  }

  friend SILVTableVisitor<Impl>;
  void addMethod(SILDeclRef declRef) {
    // Does this method require a reified runtime vtable entry?
    if (methodRequiresReifiedVTableEntry(IGM, VTable, declRef)) {
      asImpl().addReifiedVTableEntry(declRef);
    }
  }

  void addFieldEntries(Decl *field) {
    if (auto var = dyn_cast<VarDecl>(field)) {
      asImpl().addFieldOffset(var);
      return;
    }
    if (auto placeholder = dyn_cast<MissingMemberDecl>(field)) {
      asImpl().addFieldOffsetPlaceholders(placeholder);
      return;
    }
  }
};

/// An "implementation" of ClassMetadataVisitor that just scans through
/// the metadata layout, maintaining the offset of the next field.
template <class Impl>
class ClassMetadataScanner : public ClassMetadataVisitor<Impl> {
  using super = ClassMetadataVisitor<Impl>;

protected:
  Size NextOffset = Size(0);

  ClassMetadataScanner(IRGenModule &IGM, ClassDecl *target)
    : super(IGM, target) {}

public:
  void addMetadataFlags() { addPointer(); }
  void addNominalTypeDescriptor() { addPointer(); }
  void addIVarDestroyer() { addPointer(); }
  void addValueWitnessTable() { addPointer(); }
  void addDestructorFunction() { addPointer(); }
  void addSuperclass() { addPointer(); }
  void addClassFlags() { addInt32(); }
  void addInstanceAddressPoint() { addInt32(); }
  void addInstanceSize() { addInt32(); }
  void addInstanceAlignMask() { addInt16(); }
  void addRuntimeReservedBits() { addInt16(); }
  void addClassSize() { addInt32(); }
  void addClassAddressPoint() { addInt32(); }
  void addClassCacheData() { addPointer(); addPointer(); }
  void addClassDataPointer() { addPointer(); }
  void addReifiedVTableEntry(SILDeclRef declRef) {
    addPointer();
  }
  void addMethodOverride(SILDeclRef baseRef, SILDeclRef declRef) {}
  void addFieldOffset(VarDecl *var) { addPointer(); }
  void addFieldOffsetPlaceholders(MissingMemberDecl *mmd) {
    for (unsigned i = 0, e = mmd->getNumberOfFieldOffsetVectorEntries();
         i < e; ++i) {
      addPointer();
    }
  }
  void addGenericArgument(GenericRequirement requirement, ClassDecl *forClass) {
    addPointer();
  }
  void addGenericWitnessTable(GenericRequirement requirement,
                              ClassDecl *forClass) {
    addPointer();
  }
  void addPlaceholder(MissingMemberDecl *MMD) {
    for (auto i : range(MMD->getNumberOfVTableEntries())) {
      (void)i;
      addPointer();
    }
  }

private:
  // Our layout here assumes that there will never be unclaimed space
  // in the metadata.
  void addPointer() {
    NextOffset += super::IGM.getPointerSize();
  }
  void addInt32() {
    NextOffset += Size(4);
  }
  void addInt16() {
    NextOffset += Size(2);
  }
};

} // end namespace irgen
} // end namespace swift

#endif


text:
var path = require('path');

var Const = require("../const");
var Settings = require("../lib/Settings");

var RequestHandlerBase = function(){

}

RequestHandlerBase.prototype.path = function(path){

    return Settings.options.urlPrefix + path;

}

RequestHandlerBase.prototype.errorResponse = function(
    response,
    httpCode){

    response.status(httpCode);
    response.send("");

}

RequestHandlerBase.prototype.successResponse = function(response,code,data){

    response.status(Const.httpCodeSucceed);

    if(code != Const.resCodeSucceed){

        response.json({
            code : code
        });

    } else {

        response.json({
            code : Const.resCodeSucceed,
            data : data
        });

    }

}

module["exports"] = RequestHandlerBase;


text:
1. Check tests, linters.
2. Check issues and pull requests, update milestones.
3. Bump version in `doc.go`.
4. Update CHANGELOG.md.
5. Make tag.
6. Push it!
7. Make [release](https://github.com/go-reform/reform/releases).
8. Refresh
   * `env GO111MODULE=on GOPROXY=https://proxy.golang.org go get -v gopkg.in/reform.v1@v1.M.P`
   * https://pkg.go.dev/gopkg.in/reform.v1@v1.M.P
   * https://godoc.org/gopkg.in/reform.v1
   * https://goreportcard.com/report/gopkg.in/reform.v1


text:
package edu.wustl.cab2bwebapp.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import edu.wustl.cab2b.common.exception.RuntimeException;
import edu.wustl.cab2bwebapp.bizlogic.UserBackgroundQueries;
import edu.wustl.cab2bwebapp.bizlogic.executequery.QueryBizLogic;
import edu.wustl.cab2bwebapp.constants.Constants;

/**
 * @author pallavi_mistry
 *
 */
public class ExportResultsAction extends Action {
    private static final Logger logger = edu.wustl.common.util.logger.Logger.getLogger(ExportResultsAction.class);

    /* (non-Javadoc)
     * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                 HttpServletResponse response) {
        try {
            if (request.getParameter("fileName") == null) {
                String filePath = UserBackgroundQueries.EXPORT_CSV_DIR + File.separator;
                HttpSession session = request.getSession();
                QueryBizLogic queryBizLogic =
                        (QueryBizLogic) session.getAttribute(Constants.QUERY_BIZ_LOGIC_OBJECT);
                String exported_file_path = (String) session.getAttribute(Constants.EXPORTED_FILE_PATH);
                //File is getting exported (and thus built) first time.
                if (exported_file_path == null && !((" ").equals(exported_file_path))) {
                    String newfilename = queryBizLogic.exportToCSV();
                    exported_file_path = filePath + newfilename;
                    session.setAttribute(Constants.EXPORTED_FILE_PATH, exported_file_path);
                }
                //else take the file path from the session
                sendFileToClient(response, exported_file_path, "Results.zip", "application/download");
            } else {
                sendFileToClient(response, UserBackgroundQueries.EXPORT_CSV_DIR + File.separator
                        + request.getParameter("fileName"), "Results.zip", "application/download");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            ActionErrors errors = new ActionErrors();
            ActionError error = new ActionError("fatal.exportresults.failure", e.getMessage());
            errors.add(Constants.FATAL_EXPORT_FAILURE, error);
            saveErrors(request, errors);
            return mapping.findForward(Constants.FORWARD_FAILURE);
        }

        return null;
    }

    /**
     * @param response
     * @param filePath
     * @param fileName
     * @param contentType
     */
    public static void sendFileToClient(HttpServletResponse response, String filePath, String fileName,
                                        String contentType) {
        if (filePath != null && (filePath.length() != 0)) {
            File file = new File(filePath);
            if (file.exists()) {
                response.setContentType(contentType);
                response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\";");
                response.setContentLength((int) file.length());
                writeToStream(response, file);
            } else {
                logger.error("Exported result file does not exist.");
                throw new RuntimeException("Exported result file does not exist.");
            }
        }
    }

    /**
     * @param response
     * @param file
     */
    private static void writeToStream(HttpServletResponse response, File file) {
        BufferedInputStream bis = null;
        try {
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "max-age=0");

            OutputStream opstream = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));

            byte[] buf = new byte[Constants.FOUR_KILO_BYTES];
            int count = bis.read(buf);
            while (count > -1) {
                opstream.write(buf, 0, count);
                count = bis.read(buf);
            }
            opstream.flush();
            bis.close();
            opstream.close();
        } catch (FileNotFoundException ex) {
            logger.error("Exception in method sendFileToClient:" + ex.getMessage(), ex);
            throw new RuntimeException("Error while exporting results file.");
        } catch (IOException ex) {
            logger.error("Exception in method sendFileToClient:" + ex.getMessage(), ex);
            throw new RuntimeException("Error while doing file operations.");
        }
    }
}


text:
//TODO:need to decide on a package name
package org.wso2.carbon.analytics.api.commons;

import org.wso2.carbon.analytics.data.commons.AnalyticsDataService;
import org.wso2.carbon.analytics.data.commons.exception.AnalyticsException;
import org.wso2.carbon.analytics.data.commons.service.AnalyticsDataResponse;
import org.wso2.carbon.analytics.data.commons.service.AnalyticsSchema;
import org.wso2.carbon.analytics.data.commons.sources.AnalyticsIterator;
import org.wso2.carbon.analytics.data.commons.sources.Record;
import org.wso2.carbon.analytics.data.commons.sources.RecordGroup;
import org.wso2.carbon.analytics.indexerservice.impl.CarbonIndexerClient;

import java.util.List;
import java.util.Map;

/**
 * This interface represents the interface which is exposed to external parties who wants to use the data service with indexing implementation
 */
public interface AnalyticsDataAPI {

    /**
     * Lists all the record stores available in the system.
     *
     * @return The list of record store names
     */
    List<String> listRecordStoreNames();

    /**
     * Creates a table, if not already there, where the columns are not defined here, but can contain any arbitrary number
     * of columns when data is added. The table names are not case sensitive.
     *
     * @param recordStoreName The name of the target record store to store the table at
     * @param tableName       The name of the table to be created
     * @throws AnalyticsException
     */
    void createTable(String recordStoreName, String tableName) throws AnalyticsException;

    /**
     * @param tableName The name of the table to be created
     * @throws AnalyticsException
     * @see AnalyticsDataService#createTable(String, String). The primary record store is used
     * to create the table.
     */
    void createTable(String tableName) throws AnalyticsException;

    /**
     * Creates the table if it does not already exist in the system.
     *
     * @param recordStoreName The name of the target record store to store the table at
     * @param tableName       The name of the table to be created
     * @throws AnalyticsException
     */
    void createTableIfNotExists(String recordStoreName, String tableName) throws AnalyticsException;

    /**
     * Returns the record store name given the table information.
     *
     * @param tableName The table name
     * @return The record store name
     * @throws AnalyticsException
     */
    String getRecordStoreNameByTable(String tableName) throws AnalyticsException;

    /**
     * Sets the schema for the target analytics table, if there is already one assigned, it will be
     * overwritten.
     *
     * @param tableName The table name
     * @param schema    The schema to be applied to the table
     * @param merge Specify whether to merge the new schema with the older one or replace
     * @throws AnalyticsException
     */
    void setTableSchema(String tableName, CompositeSchema schema, boolean merge) throws AnalyticsException;

    /**
     * Retrieves the table schema for the given table.
     *
     * @param tableName The table name
     * @return The schema of the table
     * @throws AnalyticsException
     */
    CompositeSchema getTableSchema(String tableName) throws AnalyticsException;

    /**
     * Checks if the specified table with the given category and name exists.
     *
     * @param tableName The table name
     * @return true if the table exists, false otherwise
     * @throws AnalyticsException
     */
    boolean tableExists(String tableName) throws AnalyticsException;

    /**
     * Deletes the table with the given category and name if a table exists already.
     * This will not throw an error if the table is not there.
     *
     * @param tableName The name of the table to be dropped
     * @throws AnalyticsException
     */
    void deleteTable(String tableName) throws AnalyticsException;

    /**
     * Lists all the current tables with the given category.
     *
     * @return The list of table names
     * @throws AnalyticsException
     */
    List<String> listTables() throws AnalyticsException;

    /**
     * Adds a new record to the table. If the record id is mentioned,
     * it will be used to do the insert, or else, it will check the table's schema to check for the existence of
     * primary keys, if there are any, the primary keys will be used to derive the id, or else
     * the insert will be done with a randomly generated id.
     * If the record already exists, it updates the record store with the given records, matches by its record id,
     * this will be a full replace of the record, where the older record is effectively deleted and the new one is
     * added, there will not be a merge of older record's field's with the new one.
     *
     * @param records The list of records to be inserted
     * @throws AnalyticsException
     */
    void put(List<Record> records) throws AnalyticsException;

    /**
     * Retrieves data from a table, with a given range.
     *
     * @param tableName         The name of the table to search on
     * @param numPartitionsHint The best effort number of splits this should return
     * @param columns           The list of columns to required in results, null if all needs to be returned
     * @param timeFrom          The starting time to get records from, inclusive, relatively to epoch,
     *                          Long.MIN_VALUE should signal, this restriction to be disregarded
     * @param timeTo            The ending time to get records to, non-inclusive, relatively to epoch,
     *                          Long.MAX_VALUE should signal, this restriction to be disregarded
     * @param recordsFrom       The paginated index from value, zero based, inclusive
     * @param recordsCount      The paginated records count to be read, -1 for infinity
     * @return The analytics data response
     * @throws AnalyticsException
     */
    AnalyticsDataResponse get(String tableName, int numPartitionsHint, List<String> columns, long timeFrom,
                              long timeTo, int recordsFrom, int recordsCount) throws AnalyticsException;

    /**
     * Retrieves data from a table with given ids.
     *
     * @param tableName         The name of the table to search on
     * @param numPartitionsHint The best effort number of splits this should return
     * @param columns           The list of columns to required in results, null if all needs to be returned
     * @param ids               The list of ids of the records to be read
     * @return The analytics data response
     * @throws AnalyticsException
     */
    AnalyticsDataResponse get(String tableName, int numPartitionsHint, List<String> columns,
                              List<String> ids) throws AnalyticsException;

    /**
     * Retrieves data from a table with the values for all the given primary key value composites.
     *
     * @param tableName         The name of the table to search on
     * @param numPartitionsHint The best effort number of splits this should return
     * @param columns           The list of columns to required in results, null if all needs to be returned
     * @param valuesBatch       A batch of key/values which contains the primary keys values to match the data in the table
     * @return The analytics data response
     * @throws AnalyticsException
     */
    AnalyticsDataResponse getWithKeyValues(String tableName, int numPartitionsHint, List<String> columns,
                                           List<Map<String, Object>> valuesBatch) throws AnalyticsException;

    /**
     * Reads in the records from a given record group at a given record store, the records will be streamed in.
     *
     * @param recordStoreName The record store name
     * @param recordGroup     The record group which represents the local data set
     * @return An iterator of type {@link Record} in the local record group
     * @throws AnalyticsException
     */
    AnalyticsIterator<Record> readRecords(String recordStoreName, RecordGroup recordGroup) throws AnalyticsException;

    /**
     * Deletes a set of records in the table.
     *
     * @param tableName The name of the table to search on
     * @param timeFrom  The starting time to get records from for deletion
     * @param timeTo    The ending time to get records to for deletion
     * @throws AnalyticsException
     */
    void delete(String tableName, long timeFrom, long timeTo) throws AnalyticsException;

    /**
     * Delete data in a table with given ids.
     *
     * @param tableName The name of the table to search on
     * @param ids       The list of ids of the records to be deleted
     * @throws AnalyticsException
     */
    void delete(String tableName, List<String> ids) throws AnalyticsException;

    /**
     * Creates a table, if not already there, where the columns are not defined here, but can contain any arbitrary number
     * of columns when data is added. The table names are not case sensitive.
     *
     * @param username The username used to authorize the table creation
     * @param recordStoreName The name of the target record store to store the table at
     * @param tableName       The name of the table to be created
     * @throws org.wso2.carbon.analytics.data.commons.exception.AnalyticsException
     */
    void createTable(String username, String recordStoreName, String tableName) throws AnalyticsException;

    /**
     * Creates a table, if not already there, where the columns are not defined here, but can contain any arbitrary number
     * of columns when data is added. The table names are not case sensitive.
     *
     * @param username The username used to authorize the table creation
     * @param tableName The name of the table to be created
     * @throws AnalyticsException
     * @see AnalyticsDataService#createTable(String, String). The primary record store is used
     * to create the table.
     */
    void createTableWithUsername(String username, String tableName) throws AnalyticsException;

    /**
     * Creates the table if it does not already exist in the system.
     *
     * @param username The username used to authorize the table creation
     * @param recordStoreName The name of the target record store to store the table at
     * @param tableName       The name of the table to be created
     * @throws AnalyticsException
     */
    void createTableIfNotExists(String username, String recordStoreName, String tableName) throws AnalyticsException;

    /**
     * Returns the record store name given the table information.
     *
     * @param username The username used to authorize get the recordstore by table
     * @param tableName The table name
     * @return The record store name
     * @throws AnalyticsException
     */
    String getRecordStoreNameByTable(String username, String tableName) throws AnalyticsException;

    /**
     * Sets the schema for the target analytics table, if there is already one assigned, it will be
     * overwritten.
     *
     * @param username The username used to authorize to set tableSchema
     * @param tableName The table name
     * @param schema    The schema to be applied to the table
     *                  @param merge Mark whether to merge or not with the existing schema.
     * @throws AnalyticsException
     */
    void setTableSchema(String username, String tableName, CompositeSchema schema, boolean merge) throws AnalyticsException;

    /**
     * Retrieves the table schema for the given table.
     *
     * @param username The username used to authorize to get the table schema
     * @param tableName The table name
     * @return The schema of the table
     * @throws AnalyticsException
     */
    AnalyticsSchema getTableSchema(String username, String tableName) throws AnalyticsException;

    /**
     * Checks if the specified table with the given category and name exists.
     *
     * @param username The username used to authorize to check  the existence of a table.
     * @param tableName The table name
     * @return true if the table exists, false otherwise
     * @throws AnalyticsException
     */
    boolean tableExists(String username, String tableName) throws AnalyticsException;

    /**
     * Deletes the table with the given category and name if a table exists already.
     * This will not throw an error if the table is not there.
     *
     * @param username The username used to authorize table deletion
     * @param tableName The name of the table to be dropped
     * @throws AnalyticsException
     */
    void deleteTable(String username, String tableName) throws AnalyticsException;

    /**
     * Lists all the current tables with the given category.
     *
     * @param username The username to authorize listing tables
     * @return The list of table names
     * @throws AnalyticsException
     */
    List<String> listTables(String username) throws AnalyticsException;

    /**
     * Adds a new record to the table. If the record id is mentioned,
     * it will be used to do the insert, or else, it will check the table's schema to check for the existence of
     * primary keys, if there are any, the primary keys will be used to derive the id, or else
     * the insert will be done with a randomly generated id.
     * If the record already exists, it updates the record store with the given records, matches by its record id,
     * this will be a full replace of the record, where the older record is effectively deleted and the new one is
     * added, there will not be a merge of older record's field's with the new one.
     *
     * @param username The username used to authorize inserting records to datastore.
     * @param records The list of records to be inserted
     * @throws AnalyticsException
     */
    void put(String username, List<Record> records) throws AnalyticsException;

    /**
     * Retrieves data from a table, with a given range.
     *
     * @param username          The username used to authorize to get records from the table
     * @param tableName         The name of the table to search on
     * @param numPartitionsHint The best effort number of splits this should return
     * @param columns           The list of columns to required in results, null if all needs to be returned
     * @param timeFrom          The starting time to get records from, inclusive, relatively to epoch,
     *                          Long.MIN_VALUE should signal, this restriction to be disregarded
     * @param timeTo            The ending time to get records to, non-inclusive, relatively to epoch,
     *                          Long.MAX_VALUE should signal, this restriction to be disregarded
     * @param recordsFrom       The paginated index from value, zero based, inclusive
     * @param recordsCount      The paginated records count to be read, -1 for infinity
     * @return The analytics data response
     * @throws AnalyticsException
     */
    AnalyticsDataResponse get(String username, String tableName, int numPartitionsHint, List<String> columns, long timeFrom,
                              long timeTo, int recordsFrom, int recordsCount) throws AnalyticsException;

    /**
     * Retrieves data from a table with given ids.
     *
     * @param username          The username used to authorize to get the records
     * @param tableName         The name of the table to search on
     * @param numPartitionsHint The best effort number of splits this should return
     * @param columns           The list of columns to required in results, null if all needs to be returned
     * @param ids               The list of ids of the records to be read
     * @return The analytics data response
     * @throws AnalyticsException
     */
    AnalyticsDataResponse get(String username, String tableName, int numPartitionsHint, List<String> columns,
                              List<String> ids) throws AnalyticsException;

    /**
     * Retrieves data from a table with the values for all the given primary key value composites.
     *
     * @param username          The username used to authorize to get records
     * @param tableName         The name of the table to search on
     * @param numPartitionsHint The best effort number of splits this should return
     * @param columns           The list of columns to required in results, null if all needs to be returned
     * @param valuesBatch       A batch of key/values which contains the primary keys values to match the data in the table
     * @return The analytics data response
     * @throws AnalyticsException
     */
    AnalyticsDataResponse getWithKeyValues(String username, String tableName, int numPartitionsHint, List<String> columns,
                                           List<Map<String, Object>> valuesBatch) throws AnalyticsException;

    /**
     * Reads in the records from a given record group at a given record store, the records will be streamed in.
     *
     * @param username The username used to authorize to read records
     * @param recordStoreName The record store name
     * @param recordGroup     The record group which represents the local data set
     * @return An iterator of type {@link Record} in the local record group
     * @throws AnalyticsException
     */
    AnalyticsIterator<Record> readRecords(String username, String recordStoreName, RecordGroup recordGroup) throws AnalyticsException;

    /**
     * Deletes a set of records in the table.
     *
     * @param username  The username used to authorize to delete the records from a table
     * @param tableName The name of the table to search on
     * @param timeFrom  The starting time to get records from for deletion
     * @param timeTo    The ending time to get records to for deletion
     * @throws AnalyticsException
     */
    void delete(String username, String tableName, long timeFrom, long timeTo) throws AnalyticsException;

    /**
     * Delete data in a table with given ids.
     *
     * @param username  The username used to authorize to delete the records from a table
     * @param tableName The name of the table to search on
     * @param ids       The list of ids of the records to be deleted
     * @throws AnalyticsException
     */
    void delete(String username, String tableName, List<String> ids) throws AnalyticsException;

    /**
     * Destroys and frees any resources taken up by the analytics data service implementation.
     */
    void destroy() throws AnalyticsException;

    /**
     * Invalidates the given table for the current node.
     *
     * @param tableName name of the table
     */
    void invalidateTable(String tableName);

    /**
     * Returns the Solr client.
     *
     * @return A Wrapped solr indexer client to communicate with a solr server
     * @throws AnalyticsException
     */
    CarbonIndexerClient getIndexerClient() throws AnalyticsException;

    /**
     * Returns the solr client authorized with the given username.
     *
     * @param username the username used to authorize the communication between the client and the solr server
     * @return A Wrapped solr indexer client to communicate with a solr server
     * @throws AnalyticsException
     */
    CarbonIndexerClient getIndexerClient(String username) throws AnalyticsException;
}