text:
#pragma once
#include <aws/AWSMigrationHub/MigrationHub_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/AWSMigrationHub/model/Status.h>
#include <aws/core/utils/DateTime.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace MigrationHub
{
namespace Model
{

  /**
   *
MigrationTaskSummary includes MigrationTaskName,
   * ProgressPercent, ProgressUpdateStream,
   * Status, and UpdateDateTime for each
   * task.

See Also:
   AWS
   * API Reference

   */
  class AWS_MIGRATIONHUB_API MigrationTaskSummary
  {
  public:
    MigrationTaskSummary();
    MigrationTaskSummary(Aws::Utils::Json::JsonView jsonValue);
    MigrationTaskSummary& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
An AWS resource used for access control. It should uniquely identify the
     * migration tool as it is used for all updates made by the tool.

     */
    inline const Aws::String& GetProgressUpdateStream() const{ return m_progressUpdateStream; }

    /**
     *
An AWS resource used for access control. It should uniquely identify the
     * migration tool as it is used for all updates made by the tool.

     */
    inline void SetProgressUpdateStream(const Aws::String& value) { m_progressUpdateStreamHasBeenSet = true; m_progressUpdateStream = value; }

    /**
     *
An AWS resource used for access control. It should uniquely identify the
     * migration tool as it is used for all updates made by the tool.

     */
    inline void SetProgressUpdateStream(Aws::String&& value) { m_progressUpdateStreamHasBeenSet = true; m_progressUpdateStream = std::move(value); }

    /**
     *
An AWS resource used for access control. It should uniquely identify the
     * migration tool as it is used for all updates made by the tool.

     */
    inline void SetProgressUpdateStream(const char* value) { m_progressUpdateStreamHasBeenSet = true; m_progressUpdateStream.assign(value); }

    /**
     *
An AWS resource used for access control. It should uniquely identify the
     * migration tool as it is used for all updates made by the tool.

     */
    inline MigrationTaskSummary& WithProgressUpdateStream(const Aws::String& value) { SetProgressUpdateStream(value); return *this;}

    /**
     *
An AWS resource used for access control. It should uniquely identify the
     * migration tool as it is used for all updates made by the tool.

     */
    inline MigrationTaskSummary& WithProgressUpdateStream(Aws::String&& value) { SetProgressUpdateStream(std::move(value)); return *this;}

    /**
     *
An AWS resource used for access control. It should uniquely identify the
     * migration tool as it is used for all updates made by the tool.

     */
    inline MigrationTaskSummary& WithProgressUpdateStream(const char* value) { SetProgressUpdateStream(value); return *this;}

    /**
     *
Unique identifier that references the migration task.

     */
    inline const Aws::String& GetMigrationTaskName() const{ return m_migrationTaskName; }

    /**
     *
Unique identifier that references the migration task.

     */
    inline void SetMigrationTaskName(const Aws::String& value) { m_migrationTaskNameHasBeenSet = true; m_migrationTaskName = value; }

    /**
     *
Unique identifier that references the migration task.

     */
    inline void SetMigrationTaskName(Aws::String&& value) { m_migrationTaskNameHasBeenSet = true; m_migrationTaskName = std::move(value); }

    /**
     *
Unique identifier that references the migration task.

     */
    inline void SetMigrationTaskName(const char* value) { m_migrationTaskNameHasBeenSet = true; m_migrationTaskName.assign(value); }

    /**
     *
Unique identifier that references the migration task.

     */
    inline MigrationTaskSummary& WithMigrationTaskName(const Aws::String& value) { SetMigrationTaskName(value); return *this;}

    /**
     *
Unique identifier that references the migration task.

     */
    inline MigrationTaskSummary& WithMigrationTaskName(Aws::String&& value) { SetMigrationTaskName(std::move(value)); return *this;}

    /**
     *
Unique identifier that references the migration task.

     */
    inline MigrationTaskSummary& WithMigrationTaskName(const char* value) { SetMigrationTaskName(value); return *this;}

    /**
     *
Status of the task.

     */
    inline const Status& GetStatus() const{ return m_status; }

    /**
     *
Status of the task.

     */
    inline void SetStatus(const Status& value) { m_statusHasBeenSet = true; m_status = value; }

    /**
     *
Status of the task.

     */
    inline void SetStatus(Status&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }

    /**
     *
Status of the task.

     */
    inline MigrationTaskSummary& WithStatus(const Status& value) { SetStatus(value); return *this;}

    /**
     *
Status of the task.

     */
    inline MigrationTaskSummary& WithStatus(Status&& value) { SetStatus(std::move(value)); return *this;}

    /**
     *

     */
    inline int GetProgressPercent() const{ return m_progressPercent; }

    /**
     *

     */
    inline void SetProgressPercent(int value) { m_progressPercentHasBeenSet = true; m_progressPercent = value; }

    /**
     *

     */
    inline MigrationTaskSummary& WithProgressPercent(int value) { SetProgressPercent(value); return *this;}

    /**
     *
Detail information of what is being done within the overall status state.

     */
    inline const Aws::String& GetStatusDetail() const{ return m_statusDetail; }

    /**
     *
Detail information of what is being done within the overall status state.

     */
    inline void SetStatusDetail(const Aws::String& value) { m_statusDetailHasBeenSet = true; m_statusDetail = value; }

    /**
     *
Detail information of what is being done within the overall status state.

     */
    inline void SetStatusDetail(Aws::String&& value) { m_statusDetailHasBeenSet = true; m_statusDetail = std::move(value); }

    /**
     *
Detail information of what is being done within the overall status state.

     */
    inline void SetStatusDetail(const char* value) { m_statusDetailHasBeenSet = true; m_statusDetail.assign(value); }

    /**
     *
Detail information of what is being done within the overall status state.

     */
    inline MigrationTaskSummary& WithStatusDetail(const Aws::String& value) { SetStatusDetail(value); return *this;}

    /**
     *
Detail information of what is being done within the overall status state.

     */
    inline MigrationTaskSummary& WithStatusDetail(Aws::String&& value) { SetStatusDetail(std::move(value)); return *this;}

    /**
     *
Detail information of what is being done within the overall status state.

     */
    inline MigrationTaskSummary& WithStatusDetail(const char* value) { SetStatusDetail(value); return *this;}

    /**
     *
The timestamp when the task was gathered.

     */
    inline const Aws::Utils::DateTime& GetUpdateDateTime() const{ return m_updateDateTime; }

    /**
     *
The timestamp when the task was gathered.

     */
    inline void SetUpdateDateTime(const Aws::Utils::DateTime& value) { m_updateDateTimeHasBeenSet = true; m_updateDateTime = value; }

    /**
     *
The timestamp when the task was gathered.

     */
    inline void SetUpdateDateTime(Aws::Utils::DateTime&& value) { m_updateDateTimeHasBeenSet = true; m_updateDateTime = std::move(value); }

    /**
     *
The timestamp when the task was gathered.

     */
    inline MigrationTaskSummary& WithUpdateDateTime(const Aws::Utils::DateTime& value) { SetUpdateDateTime(value); return *this;}

    /**
     *
The timestamp when the task was gathered.

     */
    inline MigrationTaskSummary& WithUpdateDateTime(Aws::Utils::DateTime&& value) { SetUpdateDateTime(std::move(value)); return *this;}

  private:

    Aws::String m_progressUpdateStream;
    bool m_progressUpdateStreamHasBeenSet;

    Aws::String m_migrationTaskName;
    bool m_migrationTaskNameHasBeenSet;

    Status m_status;
    bool m_statusHasBeenSet;

    int m_progressPercent;
    bool m_progressPercentHasBeenSet;

    Aws::String m_statusDetail;
    bool m_statusDetailHasBeenSet;

    Aws::Utils::DateTime m_updateDateTime;
    bool m_updateDateTimeHasBeenSet;
  };

} // namespace Model
} // namespace MigrationHub
} // namespace Aws


text:
package org.guzz;

import org.guzz.connection.DBGroup;
import org.guzz.connection.PhysicsDBGroup;
import org.guzz.connection.VirtualDBView;
import org.guzz.dialect.Dialect;
import org.guzz.exception.DaoException;
import org.guzz.exception.GuzzException;
import org.guzz.io.Resource;
import org.guzz.orm.Business;
import org.guzz.orm.ColumnDataLoader;
import org.guzz.orm.ShadowTableView;
import org.guzz.orm.mapping.ObjectMappingManager;
import org.guzz.service.core.DatabaseService;
import org.guzz.service.core.DebugService;
import org.guzz.transaction.TransactionManager;
import org.guzz.web.context.ExtendedBeanFactory;

/**
 *
 * GuzzContext
 *
 * @author liukaixuan(liukaixuan@gmail.com)
 */
public interface GuzzContext {

	/**
	 * 获取DatabaseService,如果已经创建过直接返回,如果不存在试图创建。
	 * @param serviceName 服务名称
	 * @return 如果不存在对应的服务配置:如果为dubug模式返回null,否则抛出{@link GuzzException}
	 */
	public DatabaseService getOrCreateDataService(String serviceName) throws GuzzException;

	/**
	 * 根据ghost名称或者域对象的完整的类名获取Ghost对象,如果不存在返回null。
	 */
	public Business getBusiness(String name);

	/**
	 * 添加hbm领域对象定义文件。添加后 @param resource 不会自动关闭。
	 * @throws Exception */
	public void addHbmConfig(Business business, Resource resource) throws Exception;

	/**
	 * 添加hbm领域对象定义文件。
	 * @param fileName 完整文件名
	 */
	public void addHbmConfigFile(Business business, String fileName) throws Exception;

	public Business instanceNewGhost(String ghostName, String dbGroup, Class intepretClass, Class domainClass) throws ClassNotFoundException;

	public DBGroup getDBGroup(String groupName) throws DaoException;

	/**Get physics DBGroup.*/
	public PhysicsDBGroup getPhysicsDBGroup(String groupName) throws DaoException;

	public Service getService(String serviceName);

	public DebugService getDebugService();

	public Dialect getDialect(String name);

	public TransactionManager getTransactionManager() ;

	public ObjectMappingManager getObjectMappingManager() ;

	public void registerVirtualDBView(VirtualDBView view) ;

	public void registerColumnDataLoader(ColumnDataLoader loader) ;

	public void registerShadowTableView(ShadowTableView view) ;

	/**
	 * Retrieve the Extended Bean Factory. for example: a Bean Factory linked to spring's ApplicationContext if the GuzzContext is initialized within springframework.
	 *
	 * @return could be null
	 */
	public ExtendedBeanFactory getExtendedBeanFactory() ;

	/**
	 * Retrieve a bean in the extended bean factory.
	 */
	public Object getExtendedBean(String beanName) ;

	public void shutdown() ;

}

redpajama_set_name: RedPajamaGithub


text:
namespace json
{
    enum struct Encoding : std::uint8_t;

    struct ParseErrorContext
    {
        ParseErrorContext();
        ParseErrorContext(ParseErrorContext&& other) noexcept =delete;
        ParseErrorContext& operator=(ParseErrorContext&& other) noexcept =delete;
        ParseErrorContext(const ParseErrorContext& other) = delete;
        ParseErrorContext& operator=(const ParseErrorContext& other) = delete;
        ~ParseErrorContext() = default;

        std::size_t line;
        std::size_t column;
        std::istream* stream;
        Encoding enc;
        std::string filename;
    };
}


text:
<?php

namespace eZPublishBundle\Entity;

class Policy
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $module;

    /**
     * @var string
     */
    private $function;

    /**
     * @var array
     */
    private $class;

    /**
     * @var array
     */
    private $path;

    /**
     * @var array
     */
    private $language;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set module
     *
     * @param string $module
     *
     * @return Policy
     */
    public function setModule($module)
    {
        $this->module = $module;

        return $this;
    }

    /**
     * Get module
     *
     * @return string
     */
    public function getModule()
    {
        return $this->module;
    }

    /**
     * Set function
     *
     * @param string $function
     *
     * @return Policy
     */
    public function setFunction($function)
    {
        $this->function = $function;

        return $this;
    }

    /**
     * Get function
     *
     * @return string
     */
    public function getFunction()
    {
        return $this->function;
    }

    /**
     * Set class
     *
     * @param array $class
     *
     * @return Policy
     */
    public function setClass($class)
    {
        $this->class = $class;

        return $this;
    }

    /**
     * Get class
     *
     * @return array
     */
    public function getClass()
    {
        return $this->class;
    }

    /**
     * Set path
     *
     * @param array $path
     *
     * @return Policy
     */
    public function setPath($path)
    {
        $this->path = $path;

        return $this;
    }

    /**
     * Get path
     *
     * @return array
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Set language
     *
     * @param array $language
     *
     * @return Policy
     */
    public function setLanguage($language)
    {
        $this->language = $language;

        return $this;
    }

    /**
     * Get language
     *
     * @return array
     */
    public function getLanguage()
    {
        return $this->language;
    }
    /**
     * Constructor
     */
    public function __construct()
    {
        $this->language = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add language
     *
     * @param \eZPublishBundle\Entity\Language $language
     *
     * @return Policy
     */
    public function addLanguage(\eZPublishBundle\Entity\Language $language)
    {
        $this->language[] = $language;

        return $this;
    }

    /**
     * Remove language
     *
     * @param \eZPublishBundle\Entity\Language $language
     */
    public function removeLanguage(\eZPublishBundle\Entity\Language $language)
    {
        $this->language->removeElement($language);
    }
}


text:
ProfileSyncServiceBase* ProfileSyncServiceBase::FromBrowserContext(
    content::BrowserContext* context) {
  return ProfileSyncServiceFactory::GetForProfile(
      static_cast<Profile*>(context));
}


text:
import { ComponentPropsWithRef } from 'react';

interface ScaleLabelProps extends ComponentPropsWithRef<'div'> {
    fromLabel: string;
    toLabel: string;
}

const ScaleLabel = ({ fromLabel, toLabel, ...rest }: ScaleLabelProps) => {
    return (

            {fromLabel}
            {toLabel}

    );
};

export default ScaleLabel;


text:
<?php

namespace AppBundle\Entity;

use AppBundle\Entity\Audit\CreatedTrait;
use AppBundle\Entity\Audit\CreatorTrait;
use AppBundle\Entity\Audit\ProvidesCreatedInterface;
use AppBundle\Entity\Audit\ProvidesCreatorInterface;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use JMS\Serializer\Annotation as Serialize;

/**
 * @ORM\Entity
 * @ORM\Table(name="participant_payment_event")
 * @Serialize\ExclusionPolicy("all")
 * @Serialize\ReadOnly()
 */
class ParticipantPaymentEvent implements ProvidesCreatedInterface, ProvidesCreatorInterface
{
    use CreatedTrait, CreatorTrait;

    const EVENT_TYPE_SET           = 'price_set';
    const EVENT_TYPE_SET_LABEL     = 'Preis Festlegung';
    const EVENT_TYPE_PAYMENT       = 'price_payment';
    const EVENT_TYPE_PAYMENT_LABEL = 'Zahlungserfassung';

    /**
     * @ORM\Column(type="integer", name="yid")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $yid;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    protected $description = null;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $isPriceSet = false;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $isPricePayment = true;

    /**
     * Contains the events value, in EURO CENT (instead of euro)
     *
     * @ORM\Column(type="integer", name="price_value")
     */
    protected $value;

    /**
     * @ORM\ManyToOne(targetEntity="Participant", inversedBy="paymentEvents")
     * @ORM\JoinColumn(name="aid", referencedColumnName="aid", onDelete="cascade")
     */
    protected $participant;

    /**
     * Create new payment event
     *
     * @param User|null   $createdBy   User who caused this event
     * @param int         $value       Value of event
     * @param string|null $description Description
     * @return ParticipantPaymentEvent
     */
    public static function createPaymentEvent(User $createdBy = null, int $value, string $description = null)
    {
        return new self($createdBy, self::EVENT_TYPE_PAYMENT, $value, $description);
    }

    /**
     * Create price set event
     *
     * @param User|null   $createdBy   User who caused this event
     * @param int         $value       Value of event
     * @param string|null $description Description
     * @return ParticipantPaymentEvent
     */
    public static function createPriceSetEvent(User $createdBy = null, int $value, string $description = null)
    {
        return new self($createdBy, self::EVENT_TYPE_SET, $value, $description);
    }

    /**
     * ParticipantPaymentEvent constructor.
     *
     * @param User|null   $createdBy   User who caused this event
     * @param string      $type        Event type
     * @param int         $value       Value of event
     * @param string|null $description Description
     */
    public function __construct(User $createdBy = null, string $type, int $value, string $description = null)
    {
        $this->createdAt   = new \DateTime();
        $this->createdBy   = $createdBy;
        $this->description = $description;
        $this->value       = $value;
        $this->setEventType($type);
    }

    /**
     * Set value
     *
     * @param string $value
     *
     * @return self
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * Get value
     *
     * @param bool $inEuro If set to true, resulting value is returned in EURO instead of EURO CENT
     * @return int|float
     */
    public function getValue($inEuro = false)
    {
        return $inEuro ? $this->value / 100 : $this->value;
    }

    /**
     * @return string|null
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Define event type
     *
     * @param string $type
     * @return self
     */
    public function setEventType($type)
    {
        if (!self::isEventTypeValid($type)) {
            throw new \RuntimeException('Invalid event type');
        }
        switch ($type) {
            case self::EVENT_TYPE_PAYMENT:
                $this->isPricePayment = true;
                $this->isPriceSet     = false;
                break;
            case self::EVENT_TYPE_SET:
                $this->isPricePayment = false;
                $this->isPriceSet     = true;
                break;
        }
        return $this;
    }

    /**
     * Get the event type of this payment event
     *
     * @return string
     * @throws \RuntimeException If invalid payment event configuration present
     */
    public function getEventType()
    {
        if ($this->isPricePayment && !$this->isPriceSet) {
            return self::EVENT_TYPE_PAYMENT;
        } elseif (!$this->isPricePayment && $this->isPriceSet) {
            return self::EVENT_TYPE_SET;
        } else {
            throw new \RuntimeException('Invalid payment event configuration');
        }
    }

    /**
     * Determine if this is an payment event
     *
     * @return bool
     */
    public function isPricePaymentEvent() {
        return $this->getEventType() === self::EVENT_TYPE_PAYMENT;
    }

    /**
     * Determine if this is an price set event
     *
     * @return bool
     */
    public function isPriceSetEvent() {
        return $this->getEventType() === self::EVENT_TYPE_SET;
    }

    /**
     * Get label for event type of this payment event
     *
     * @return string
     * @throws \RuntimeException If invalid payment event configuration present
     */
    public function getEventTypeLabeled()
    {
        switch ($this->getEventType()) {
            case self::EVENT_TYPE_PAYMENT:
                return self::EVENT_TYPE_PAYMENT_LABEL;
                break;
            case self::EVENT_TYPE_SET:
                return self::EVENT_TYPE_SET_LABEL;
                break;
            default:
                throw new \RuntimeException('Invalid payment event configuration');
        }
    }

    /**
     * Check if transmitted event type is valid
     *
     * @param mixed $type Value to check
     * @return bool
     */
    public static function isEventTypeValid($type)
    {
        return in_array($type, [self::EVENT_TYPE_SET, self::EVENT_TYPE_PAYMENT]);
    }

    /**
     * @return Participant
     */
    public function getParticipant()
    {
        return $this->participant;
    }

    /**
     * @param mixed $participant
     * @return ParticipantPaymentEvent
     */
    public function setParticipant($participant)
    {
        $this->participant = $participant;
        return $this;
    }
}


text:
var
  fs = require('fs'),
  argv = require('optimist').argv;

if (!argv.run) {
  process.exit(1);
}

try {
  var
    fn    = require(__dirname + '/../script/' + argv.run),
    json  = fs.readFileSync(argv.filename, 'ascii'),
    board = JSON.parse(json);

    fn(board, argv);
} catch (e) {
  fs.writeFileSync(__dirname + '/../tmp/run.error.txt', e);
  throw e;
  process.exit(1);
}


text:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{glossaries}

\makeglossaries

\newglossaryentry{mass}
{
    name=mass,
    description={Mass is the stuff that provides inertia.  Mass also begets gravity.}
}

\newglossaryentry{maths}
{
    name=mathematics,
    description={Mathematics is what mathematicians do}
}

\title{Computer Science Glossary}
\author{ }
\date{ }

\begin{document}
\maketitle

To do physics with \Gls{mass} you need \gls{maths}.

\clearpage

\printglossaries

\end{document}


text:
package iamdilipkumar.com.udacitybaking.data;

import net.simonvt.schematic.annotation.AutoIncrement;
import net.simonvt.schematic.annotation.DataType;
import net.simonvt.schematic.annotation.NotNull;
import net.simonvt.schematic.annotation.PrimaryKey;

/**
 * Created on 16/05/17.
 *
 * @author dilipkumar4813
 * @version 1.0
 */

public interface StepsColumns {

    @DataType(DataType.Type.INTEGER)
    @AutoIncrement
    @PrimaryKey
    String _ID = "id";

    @DataType(DataType.Type.INTEGER)
    @NotNull
    String RECIPE_ID = "recipe_id";

    @DataType(DataType.Type.INTEGER)
    @NotNull
    String STEPS = "step";

    @DataType(DataType.Type.TEXT)
    @NotNull
    String SHORT_DESCRIPTION = "short_description";

    @DataType(DataType.Type.TEXT)
    @NotNull
    String LONG_DESCRIPTION = "long_description";

    @DataType(DataType.Type.TEXT)
    String VIDEO_URL = "video_url";

    @DataType(DataType.Type.TEXT)
    String THUMBNAIL_URL = "thumnail_url";
}


text:
Preload content of links before clicking

## Getting Started
Download the [production version][min] or the [development version][max].

[min]: https://raw.github.com/KATT/promise-click/master/dist/promise-click.min.js
[max]: https://raw.github.com/KATT/promise-click/master/dist/promise-click.js

In your web page:

```html
<script src="jquery.js"></script>
<script src="dist/promise-click.min.js"></script>
<script>
jQuery(function($) {
  $(document).on('promiseclick', 'a.ajax', function(event) {
	  event.preventDefault();
	  var $this = $(this);

	  event.data.promise.done(function (data) {
	    // do something with the data
	  });
	});
});
</script>
```

## Documentation
_(Coming soon)_

## Examples
See [`demos/`](demos/index.html).

## Todo / wish list

* Delay mouseover promise with X milliseconds
* Options
	* Mouseover delay
	* Override promise generation
	* Auto `preventDefault` on click
* Unit tests
* Clean-up old promises
* Prevent caching on rejected promises?

### Implemented

* Implement as a jQuery event, `jQuery.Event.promsieclick`
* Ability to unbind
* Support [virtual mouse][vclick]
* Clean-up interface (jQuery `.on()`-esque?)

[vclick]: http://api.jquerymobile.com/vclick/

## Release History
_(Nothing yet)_


text:
'use strict';

/*globals togileApp*/

togileApp.directive('setFocus', function($timeout) {
    return function(scope, element, attr) {
        scope.$watch(attr.setFocus, function(value) {
            if (value) {
                $timeout(function() {
                    element[0].focus();
                }, 0, false);
            }
        });
    };
});


text: .NET Grid Computing Framework


text:
//
//  HRUtils.h
//  HttpRequestClient
//
//  Created by 张雁军 on 19/06/2017.
//  Copyright © 2017 张雁军. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "HRError.h"

@interface HRUtils : NSObject

+ (NSString *)getToken;

+ (void)showError:(HRError *)error;

/**
 show UIAlertView with 'OK'

 @param error <#error description#>
 @param handler something to do when clicked OK
 */
+ (void)showError:(HRError *)error alertHandler:(void(^)())handler;

@end


text:
import sys
import json
from calvin.runtime.north.calvin_token import Token
import time
from calvin.utilities.calvinlogger import get_logger

_log = get_logger(__name__)

class Endpoint(object):

    """docstring for Endpoint"""

    def __init__(self, port, former_peer_id=None):
        super(Endpoint, self).__init__()
        self.port = port
        self.former_peer_id = former_peer_id

    def __str__(self):
        return self.__class__.__name__

    def is_connected(self):
        return False

    def read_token(self):
        return None

    def communicate(self):
        """
        Called by the runtime when it is possible to transfer data to counterpart.
        """
        raise Exception("Can't communicate on endpoint in port %s.%s with id: %s" % (
            self.port.owner.name, self.port.name, self.port.id))

    def destroy(self):
        pass

    def get_peer(self):
        return (None, self.former_peer_id)

#
# Local endpoints
#

class LocalInEndpoint(Endpoint):

    """docstring for LocalEndpoint"""

    def __init__(self, port, peer_port):
        super(LocalInEndpoint, self).__init__(port)
        self.peer_port = peer_port
        # When migrating from remote to local,
        # there might be initial data to read in the FIFO
        self.data_in_local_fifo = True
        self.fifo_mismatch = True

    def is_connected(self):
        return True

    def _fifo_mismatch_fix(self):
        # Fix once mismatch of positions: we have tokens in the peer fifo that are duplicates of tokens transferred (and ack never reached peer)
        # Need to remove in peer fifo since might already been consumed
        while self.peer_port.fifo.can_read(self.port.id) and self.port.fifo.write_pos > self.peer_port.fifo.read_pos[self.port.id]:
            token = self.peer_port.fifo.read(self.port.id)
            self.peer_port.fifo.commit_reads(self.port.id, True)
        self.fifo_mismatch = False

    def _sync_local_fifos(self):
        # TODO Fix performance by only doing this at a disconnect of local port
        # Make this port's write pos to be synced with peer's read_pos as it is when using 2 FIFOs (i.e. remote)
        self.port.fifo.write_pos = self.peer_port.fifo.read_pos[self.port.id]
        # and the read pos reflect it does not actually contain any data
        self.port.fifo.read_pos[self.port.id] = self.port.fifo.write_pos
        self.port.fifo.tentative_read_pos[self.port.id] = self.port.fifo.write_pos

    def read_token(self):
        if self.fifo_mismatch:
            self._fifo_mismatch_fix()

        if self.data_in_local_fifo:
            # Empty local inport fifo once, since local transport only use outport's fifo
            token = self.port.fifo.read(self.port.id)
            if token:
                self.port.fifo.commit_reads(self.port.id, True)
                return token
            self.data_in_local_fifo = False

        token = self.peer_port.fifo.read(self.port.id)
        self.peer_port.fifo.commit_reads(self.port.id, token is not None)

        self._sync_local_fifos()
        return token

    def peek_token(self):
        if self.fifo_mismatch:
            self._fifo_mismatch_fix()

        if self.data_in_local_fifo:
            # Empty local FIFO (once) in case it contains data
            token = self.port.fifo.read(self.port.id)
            if token:
                return token

        token = self.peer_port.fifo.read(self.port.id)
        return token

    def peek_rewind(self):
        if self.data_in_local_fifo:
            token = self.port.fifo.rollback_reads(self.port.id)
        token = self.peer_port.fifo.rollback_reads(self.port.id)

    def commit_peek_as_read(self):
        if self.data_in_local_fifo:
            self.port.fifo.commit_reads(self.port.id)
            if self.port.fifo.can_read(self.port.id):
                # Still data left in own fifo, no need to commit on peer port and no sync should be done
                return
            else:
                self.data_in_local_fifo = False
        self.peer_port.fifo.commit_reads(self.port.id)
        self._sync_local_fifos()

    def available_tokens(self):
        if self.fifo_mismatch:
            self._fifo_mismatch_fix()

        tokens = 0
        if self.data_in_local_fifo:
            # Check local FIFO in case it contains data
            tokens += self.port.fifo.available_tokens(self.port.id)
            if tokens == 0:
                self.data_in_local_fifo = False
        tokens += self.peer_port.fifo.available_tokens(self.port.id)
        return tokens

    def get_peer(self):
        return ('local', self.peer_port.id)

class LocalOutEndpoint(Endpoint):

    """docstring for LocalEndpoint"""

    def __init__(self, port, peer_port):
        super(LocalOutEndpoint, self).__init__(port)
        self.peer_port = peer_port
        self.peer_id = peer_port.id

    def is_connected(self):
        return True

    def get_peer(self):
        return ('local', self.peer_id)

#
# Remote endpoints
#

class TunnelInEndpoint(Endpoint):

    """docstring for TunnelInEndpoint"""

    def __init__(self, port, tunnel, peer_node_id, peer_port_id, trigger_loop):
        super(TunnelInEndpoint, self).__init__(port)
        self.tunnel = tunnel
        self.peer_port_id = peer_port_id
        self.peer_node_id = peer_node_id
        self.trigger_loop = trigger_loop

    def __str__(self):
        str = super(TunnelInEndpoint, self).__str__()
        return str

    def is_connected(self):
        return True

    def recv_token(self, payload):
        ok =False
        # Drop any tokens that we can't write to fifo or is out of sequence
        if self.port.fifo.can_write() and self.port.fifo.write_pos == payload['sequencenbr']:
            self.port.fifo.write(Token.decode(payload['token']))
            self.trigger_loop()
            ok = True
        elif self.port.fifo.write_pos > payload['sequencenbr']:
            # Other side resent a token we already have received (can happen after a reconnect if our previous ACK was lost), just ACK
            ok = True
        reply = {'cmd': 'TOKEN_REPLY', 'port_id':payload['port_id'], 'peer_port_id': payload['peer_port_id'], 'sequencenbr': payload['sequencenbr'], 'value': 'ACK' if ok else 'NACK'}
        self.tunnel.send(reply)

    def read_token(self):
        token = self.port.fifo.read(self.port.id)
        self.port.fifo.commit_reads(self.port.id, token is not None)
        return token

    def peek_token(self):
        token = self.port.fifo.read(self.port.id)
        return token

    def peek_rewind(self):
        self.port.fifo.rollback_reads(self.port.id)

    def commit_peek_as_read(self):
        self.port.fifo.commit_reads(self.port.id)

    def available_tokens(self):
        # First fit as many tokens as possible in the fifo
        return self.port.fifo.available_tokens(self.port.id)

    def set_peer_port_id(self, id):
        self.peer_port_id = id

    def get_peer(self):
        return (self.peer_node_id, self.peer_port_id)

class TunnelOutEndpoint(Endpoint):

    """docstring for TunnelOutEndpoint"""

    def __init__(self, port, tunnel, peer_node_id, peer_port_id, trigger_loop):
        super(TunnelOutEndpoint, self).__init__(port)
        self.tunnel = tunnel
        self.peer_id = peer_port_id
        self.peer_node_id = peer_node_id
        self.trigger_loop = trigger_loop
        # Keep track of acked tokens, only contains something post call if acks comes out of order
        self.sequencenbrs_acked = []
        self.backoff = 0.0
        self.time_cont = 0.0
        self.bulk = True

    def __str__(self):
        str = super(TunnelOutEndpoint, self).__str__()
        return str

    def is_connected(self):
        return True

    def reply(self, sequencenbr, status):
        sequencenbr_sent = self.port.fifo.tentative_read_pos[self.peer_id]
        sequencenbr_acked= self.port.fifo.read_pos[self.peer_id]
        _log.debug("Reply on port %s/%s/%s [%i] %s" % (self.port.owner.name, self.peer_id, self.port.name, sequencenbr, status))
        if status=='ACK':
            # Back to full send speed directly
            self.bulk = True
            self.backoff = 0.0
            if sequencenbr < sequencenbr_sent:
                self.sequencenbrs_acked.append(sequencenbr)
            while any(n==sequencenbr_acked for n in self.sequencenbrs_acked):
                self.port.fifo.commit_one_read(self.peer_id, True)
                self.sequencenbrs_acked.remove(sequencenbr_acked)
            # Maybe someone can fill the fifo again
            self.trigger_loop()

        elif status=='NACK':
            # Make send only send one token at a time and have increasing time between them
            curr_time = time.time()
            if self.bulk:
                self.time_cont = curr_time
            if self.time_cont <= curr_time:
                # Need to trigger again due to either too late NACK or switched from series of ACK
                self.trigger_loop()
            self.bulk = False
            self.backoff = min(1.0, 0.1 if self.backoff < 0.1 else self.backoff*2.0)

            if sequencenbr < sequencenbr_sent and sequencenbr >= sequencenbr_acked:
                # Filter out ACK for later seq nbrs, should not happen but precaution
                self.sequencenbrs_acked = [n for n in self.sequencenbrs_acked if n<sequencenbr]
                # Rollback fifo to the NACKed token
                while(self.port.fifo.tentative_read_pos[self.peer_id] > sequencenbr):
                    self.port.fifo.commit_one_read(self.peer_id, False)
        else:
            # FIXME implement ABORT
            pass

    def _send_one_token(self):
        token = self.port.fifo.read(self.peer_id)
        sequencenbr_sent = self.port.fifo.tentative_read_pos[self.peer_id] - 1
        _log.debug("Send on port  %s/%s/%s [%i] %s" % (self.port.owner.name,
                                                       self.peer_id,
                                                       self.port.name,
                                                       sequencenbr_sent,
                                                       "" if self.bulk else "@%f/%f" % (self.time_cont, self.backoff)))
        self.tunnel.send({'cmd':'TOKEN', 'token':token.encode(), 'peer_port_id':self.peer_id, 'sequencenbr': sequencenbr_sent, 'port_id': self.port.id})

    def communicate(self, *args, **kwargs):
        sent = False
        if self.bulk:
            # Send all we have, since other side seems to keep up
            while self.port.fifo.can_read(self.peer_id):
                sent = True
                self._send_one_token()
        else:
            # Send only one since other side sent NACK likely due to their FIFO is full
            if (self.port.fifo.can_read(self.peer_id) and
               self.port.fifo.tentative_read_pos[self.peer_id] == self.port.fifo.read_pos[self.peer_id] and
               time.time() >= self.time_cont):
                # Something to read and last (N)ACK recived
                self._send_one_token()
                sent = True
                self.time_cont = time.time() + self.backoff
                # Make sure that resend will be tried in backoff seconds
                self.trigger_loop(self.backoff)
        return sent

    def get_peer(self):
        return (self.peer_node_id, self.peer_id)


text:
<?php

namespace Honeybadger\Backtrace;

use \Honeybadger\Filter;
use \Honeybadger\Util\SemiOpenStruct;

/**
 * Handles backtrace parsing line by line.
 *
 * @package   Honeybadger
 * @category  Backtrace
 */
class Line extends SemiOpenStruct {

	protected $_attribute_methods = array('source');

	/**
	 * @var  string  The file portion of the line.
	 */
	protected $file;

	/**
	 * @var  integer  The line number portion of the line.
	 */
	protected $number;

	/**
	 * @var  string  The method of the line (such as index).
	 */
	protected $method;

	/**
	 * @var  string  The source code surrounding the matching line.
	 */
	protected $source;

	/**
	 * @var  string  Filtered representation of [Line::$file].
	 */
	protected $filtered_file;

	/**
	 * @var  string  Filtered representation of [Line::$number].
	 */
	protected $filtered_number;

	/**
	 * @var  string  Filtered representation of [Line::$method].
	 */
	protected $filtered_method;

	/**
	 * Parses a single line of a given backtrace.
	 *
	 * @param   array   $unparsed_line   The raw line from `caller` or some backtrace.
	 * @param   array   $options
	 * @return  Line    The parsed backtrace line.
	 */
	public static function parse(array $unparsed_line, array $options = array())
	{
		if ( ! isset($unparsed_line['file']) OR empty($unparsed_line['file']))
		{
			$unparsed_line['file'] = '{PHP internal call}';
		}

		if ( ! isset($options['filters']))
		{
			$options['filters'] = array();
		}

		$filtered = Filter::callbacks($options['filters'], $unparsed_line);

		if ($filtered === NULL)
			return;

		// Extract the filtered line parameters
		extract($filtered + array(
			'filtered_file'     => NULL,
			'filtered_line'     => NULL,
			'filtered_function' => NULL,
		));

		// Extract the original line parameters
		extract($unparsed_line + array(
			'file'     => '',
			'line'     => '',
			'function' => '',
		));

		return new self($file, $line, $function, $filtered_file,
			$filtered_line, $filtered_function);
	}

	/**
	 * Instantiates a new backtrace line from a given filename, line number, and
	 * method name.
	 *
	 * @param  string   $file    The filename in the given backtrace line
	 * @param  integer  $number  The line number of the file
	 * @param  string   $method  The method referenced in the given backtrace line
	 */
	public function __construct($file, $number, $method, $filtered_file = NULL,
                                $filtered_number = NULL, $filtered_method = NULL)
	{
		if ($filtered_file === NULL)
		{
			$filtered_file = $file;
		}

		if ($filtered_number === NULL)
		{
			$filtered_number = $number;
		}

		if ($filtered_method === NULL)
		{
			$filtered_method = $method;
		}

		$this->filtered_file   = $filtered_file;
		$this->filtered_number = $filtered_number;
		$this->filtered_method = $filtered_method;
		$this->file            = $file;
		$this->number          = $number;
		$this->method          = $method;
	}

	/**
	 * Formats the backtrace line as a string.
	 *
	 *     echo $line; // => "app/models/user.php:109:in `some_method'"
	 *
	 * @return  string  The backtrace line.
	 */
	public function __toString()
	{
		return sprintf("%s:%d:in `%s'", $this->filtered_file,
			$this->filtered_number, $this->filtered_method);
	}

	/**
	 * Checks if this `Line` matches another supplied `Line`.
	 *
	 * @param   Line     $other  The `Line` to match.
	 * @return  boolean  `TRUE` if objects match, `FALSE` otherwise.
	 */
	public function equals($other)
	{
		return ( (string) $this == (string) $other);
	}

	/**
	 * Checks if this `Line` is a part of the configured project. Ignores files
	 * under `[PROJECT_ROOT]/vendor`.
	 *
	 * @return  boolean  `TRUE` if application line, `FALSE` otherwise.
	 */
	public function is_application()
	{
		return (strpos($this->filtered_file, '[PROJECT_ROOT]') === 0 AND
		        strpos($this->filtered_file, '[PROJECT_ROOT]/vendor') === FALSE);
	}

	/**
	 * Extracts the source code of the line. Optionally, `$radius` can be
	 * supplied to specificy the number of lines before and after to extract.
	 *
	 * @param   integer  $radius  Radius to extract.
	 * @return  array    The extracted source code.
	 */
	public function source($radius = 2)
	{
		if ($this->source)
			return $this->source;

		return $this->source = $this->get_source($this->file, $this->number, $radius);
	}

	/**
	 * Formats the backtrace line as an array.
	 *
	 * @return  array  The backtrace line
	 */
	public function as_array()
	{
		return array(
			'file'   => $this->filtered_file,
			'number' => $this->filtered_number,
			'method' => $this->filtered_method,
		);
	}

	/**
	 * Extracts source code from the specified `$file`, starting `$radius`
	 * lines before the specified `$number`.
	 *
	 * @return  array  The extracted source.
	 */
	private function get_source($file, $number, $radius = 2)
	{
		if ( ! is_file($file) OR ! is_readable($file))
		{
			return array();
		}

		$before = $after = $radius;
		$start  = ($number - 1) - $before;

		if ($start <= 0)
		{
			$start  = 1;
			$before = 1;
		}

		$duration = $before + 1 + $after;
		$size     = $start + $duration;
		$lines    = array();

		$f = fopen($file, 'r');

		for ($l = 1; $l < $size; $l++)
		{
			$line = fgets($f);

			if ($l < $start)
				continue;

			$lines["$l"] = $this->trim_line($line);
		}

		return $lines;
	}

	/**
	 * Replaces tabs with spaces and strips endlines and trailing whitespace
	 * from the supplied `$line`.
	 *
	 * @param   string  $line  The line to trim.
	 * @return  string  The trimmed line.
	 */
	private function trim_line($line)
	{
		$trimmed = trim($line, "\n\r\0\x0B");

		return preg_replace(array(
			'/\s*$/D',
			'/\t/'
		), array(
			'',
			'    ',
		), $trimmed);
	}

} // End Line


text:
'use strict';

const models = require('./index');

/**
 * Network rule set
 *
 */
class NetworkRuleSet {
  /**
   * Create a NetworkRuleSet.
   * @member {string} [bypass] Specifies whether traffic is bypassed for
   * Logging/Metrics/AzureServices. Possible values are any combination of
   * Logging|Metrics|AzureServices (For example, "Logging, Metrics"), or None
   * to bypass none of those traffics. Possible values include: 'None',
   * 'Logging', 'Metrics', 'AzureServices'. Default value: 'AzureServices' .
   * @member {array} [virtualNetworkRules] Sets the virtual network rules
   * @member {array} [ipRules] Sets the IP ACL rules
   * @member {string} defaultAction Specifies the default action of allow or
   * deny when no other rules match. Possible values include: 'Allow', 'Deny'.
   * Default value: 'Allow' .
   */
  constructor() {
  }

  /**
   * Defines the metadata of NetworkRuleSet
   *
   * @returns {object} metadata of NetworkRuleSet
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'NetworkRuleSet',
      type: {
        name: 'Composite',
        className: 'NetworkRuleSet',
        modelProperties: {
          bypass: {
            required: false,
            serializedName: 'bypass',
            defaultValue: 'AzureServices',
            type: {
              name: 'String'
            }
          },
          virtualNetworkRules: {
            required: false,
            serializedName: 'virtualNetworkRules',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'VirtualNetworkRuleElementType',
                  type: {
                    name: 'Composite',
                    className: 'VirtualNetworkRule'
                  }
              }
            }
          },
          ipRules: {
            required: false,
            serializedName: 'ipRules',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'IPRuleElementType',
                  type: {
                    name: 'Composite',
                    className: 'IPRule'
                  }
              }
            }
          },
          defaultAction: {
            required: true,
            serializedName: 'defaultAction',
            defaultValue: 'Allow',
            type: {
              name: 'Enum',
              allowedValues: [ 'Allow', 'Deny' ]
            }
          }
        }
      }
    };
  }
}

module.exports = NetworkRuleSet;


text:
'use strict';

angular.module('core').controller('HomeController', ['$scope', '$http', '$location', 'Authentication',
	function($scope, $http, $location, Authentication) {
		// This provides Authentication context.
		$scope.authentication = Authentication;

		// If user is signed in then redirect back home
		if ($scope.authentication.user) $location.path('/');
	}
]);


text:
#include "tiledb/sm/consolidator/fragment_consolidator.h"
#include "tiledb/common/logger.h"
#include "tiledb/sm/array_schema/array_schema.h"
#include "tiledb/sm/enums/datatype.h"
#include "tiledb/sm/enums/query_status.h"
#include "tiledb/sm/enums/query_type.h"
#include "tiledb/sm/misc/tdb_time.h"
#include "tiledb/sm/query/query.h"
#include "tiledb/sm/stats/global_stats.h"
#include "tiledb/sm/storage_manager/storage_manager.h"
#include "tiledb/storage_format/uri/parse_uri.h"

#include <iostream>
#include <sstream>

using namespace tiledb::common;

namespace tiledb::sm {

class FragmentConsolidatorStatusException : public StatusException {
 public:
  explicit FragmentConsolidatorStatusException(const std::string& message)
      : StatusException("FragmentConsolidator", message) {
  }
};

/* ****************************** */
/*          CONSTRUCTOR           */
/* ****************************** */

FragmentConsolidator::FragmentConsolidator(
    const Config& config, StorageManager* storage_manager)
    : Consolidator(storage_manager) {
  auto st = set_config(config);
  if (!st.ok()) {
    throw std::logic_error(st.message());
  }
}

/* ****************************** */
/*               API              */
/* ****************************** */

Status FragmentConsolidator::consolidate(
    const char* array_name,
    EncryptionType encryption_type,
    const void* encryption_key,
    uint32_t key_length) {
  auto timer_se = stats_->start_timer("consolidate_frags");

  check_array_uri(array_name);

  // Open array for reading
  auto array_for_reads{
      make_shared<Array>(HERE(), URI(array_name), storage_manager_)};
  RETURN_NOT_OK(array_for_reads->open_without_fragments(
      encryption_type, encryption_key, key_length));

  // Open array for writing
  auto array_for_writes{make_shared<Array>(
      HERE(), array_for_reads->array_uri(), storage_manager_)};
  RETURN_NOT_OK(array_for_writes->open(
      QueryType::WRITE, encryption_type, encryption_key, key_length));

  // Disable consolidation with timestamps on older arrays.
  if (array_for_reads->array_schema_latest().write_version() <
      constants::consolidation_with_timestamps_min_version) {
    config_.with_timestamps_ = false;
  }

  // Get fragment info
  // For dense arrays, we need to pass the last parameter to the
  // `load` function to indicate that all fragment metadata
  // must be fetched (even before `config_.timestamp_start_`),
  // to compute the anterior ND range that can help determine
  // which dense fragments are consolidatable.
  FragmentInfo fragment_info(URI(array_name), storage_manager_);
  auto st = fragment_info.load(
      array_for_reads->array_directory(),
      config_.timestamp_start_,
      config_.timestamp_end_,
      encryption_type,
      encryption_key,
      key_length);
  if (!st.ok()) {
    throw_if_not_ok(array_for_reads->close());
    throw_if_not_ok(array_for_writes->close());
    return st;
  }

  uint32_t step = 0;
  std::vector<TimestampedURI> to_consolidate;
  do {
    // No need to consolidate if no more than 1 fragment exist
    if (fragment_info.fragment_num() <= 1)
      break;

    // Find the next fragments to be consolidated
    NDRange union_non_empty_domains;
    st = compute_next_to_consolidate(
        array_for_reads->array_schema_latest(),
        fragment_info,
        &to_consolidate,
        &union_non_empty_domains);
    if (!st.ok()) {
      throw_if_not_ok(array_for_reads->close());
      throw_if_not_ok(array_for_writes->close());
      return st;
    }

    // Check if there is anything to consolidate
    if (to_consolidate.size() <= 1) {
      break;
    }

    // Consolidate the selected fragments
    URI new_fragment_uri;
    st = consolidate_internal(
        array_for_reads,
        array_for_writes,
        to_consolidate,
        union_non_empty_domains,
        &new_fragment_uri);
    if (!st.ok()) {
      throw_if_not_ok(array_for_reads->close());
      throw_if_not_ok(array_for_writes->close());
      return st;
    }

    // Load info of the consolidated fragment and add it
    // to the fragment info, replacing the fragments that it
    // consolidated.
    st = fragment_info.load_and_replace(new_fragment_uri, to_consolidate);
    if (!st.ok()) {
      throw_if_not_ok(array_for_reads->close());
      throw_if_not_ok(array_for_writes->close());
      return st;
    }

    // Advance number of steps
    ++step;

  } while (step < config_.steps_);

  RETURN_NOT_OK_ELSE(
      array_for_reads->close(), throw_if_not_ok(array_for_writes->close()));
  RETURN_NOT_OK(array_for_writes->close());

  stats_->add_counter("consolidate_step_num", step);

  return Status::Ok();
}

Status FragmentConsolidator::consolidate_fragments(
    const char* array_name,
    EncryptionType encryption_type,
    const void* encryption_key,
    uint32_t key_length,
    const std::vector<std::string>& fragment_uris) {
  auto timer_se = stats_->start_timer("consolidate_frags");

  // Open array for reading
  auto array_for_reads{
      make_shared<Array>(HERE(), URI(array_name), storage_manager_)};
  RETURN_NOT_OK(array_for_reads->open_without_fragments(
      encryption_type, encryption_key, key_length));

  // Open array for writing
  auto array_for_writes{make_shared<Array>(
      HERE(), array_for_reads->array_uri(), storage_manager_)};
  RETURN_NOT_OK(array_for_writes->open(
      QueryType::WRITE, encryption_type, encryption_key, key_length));

  // Disable consolidation with timestamps on older arrays.
  if (array_for_reads->array_schema_latest().write_version() <
      constants::consolidation_with_timestamps_min_version) {
    config_.with_timestamps_ = false;
  }

  // Check if there is anything to consolidate
  if (fragment_uris.size() <= 1) {
    return Status::Ok();
  }

  // Get all fragment info
  FragmentInfo fragment_info(URI(array_name), storage_manager_);
  auto st = fragment_info.load(
      array_for_reads->array_directory(),
      0,
      utils::time::timestamp_now_ms(),
      encryption_type,
      encryption_key,
      key_length);
  if (!st.ok()) {
    throw_if_not_ok(array_for_reads->close());
    throw_if_not_ok(array_for_writes->close());
    return st;
  }

  // Make a set of the uris to consolidate
  NDRange union_non_empty_domains;
  std::unordered_set<std::string> to_consolidate_set;
  for (auto& uri : fragment_uris) {
    to_consolidate_set.emplace(uri);
  }

  // Make sure all fragments to consolidate are present
  // Compute union of non empty domains as we go
  uint64_t count = 0;
  auto& domain{array_for_reads->array_schema_latest().domain()};
  std::vector<TimestampedURI> to_consolidate;
  to_consolidate.reserve(fragment_uris.size());
  auto& frag_info_vec = fragment_info.single_fragment_info_vec();
  for (auto& frag_info : frag_info_vec) {
    auto uri = frag_info.uri().last_path_part();
    if (to_consolidate_set.count(uri) != 0) {
      count++;
      domain.expand_ndrange(
          frag_info.non_empty_domain(), &union_non_empty_domains);
      to_consolidate.emplace_back(frag_info.uri(), frag_info.timestamp_range());
    }
  }

  if (count != fragment_uris.size()) {
    return logger_->status(Status_ConsolidatorError(
        "Cannot consolidate; Not all fragments could be found"));
  }

  // Consolidate the selected fragments
  URI new_fragment_uri;
  st = consolidate_internal(
      array_for_reads,
      array_for_writes,
      to_consolidate,
      union_non_empty_domains,
      &new_fragment_uri);
  if (!st.ok()) {
    throw_if_not_ok(array_for_reads->close());
    throw_if_not_ok(array_for_writes->close());
    return st;
  }

  // Load info of the consolidated fragment and add it
  // to the fragment info, replacing the fragments that it
  // consolidated.
  st = fragment_info.load_and_replace(new_fragment_uri, to_consolidate);
  if (!st.ok()) {
    throw_if_not_ok(array_for_reads->close());
    throw_if_not_ok(array_for_writes->close());
    return st;
  }

  RETURN_NOT_OK_ELSE(
      array_for_reads->close(), RETURN_NOT_OK(array_for_writes->close()));
  throw_if_not_ok(array_for_writes->close());

  return Status::Ok();
}

void FragmentConsolidator::vacuum(const char* array_name) {
  if (array_name == nullptr) {
    throw Status_StorageManagerError(
        "Cannot vacuum fragments; Array name cannot be null");
  }

  // Get the fragment URIs and vacuum file URIs to be vacuumed
  auto vfs = storage_manager_->vfs();
  auto compute_tp = storage_manager_->compute_tp();
  auto array_dir = ArrayDirectory(
      vfs,
      compute_tp,
      URI(array_name),
      0,
      std::numeric_limits<uint64_t>::max(),
      ArrayDirectoryMode::VACUUM_FRAGMENTS);

  auto filtered_fragment_uris = array_dir.filtered_fragment_uris(true);
  const auto& fragment_uris_to_vacuum =
      filtered_fragment_uris.fragment_uris_to_vacuum();
  const auto& commit_uris_to_ignore =
      filtered_fragment_uris.commit_uris_to_ignore();

  if (commit_uris_to_ignore.size() > 0) {
    throw_if_not_ok(storage_manager_->write_commit_ignore_file(
        array_dir, commit_uris_to_ignore));
  }

  // Delete the commit and vacuum files
  vfs->remove_files(compute_tp, filtered_fragment_uris.commit_uris_to_vacuum());
  vfs->remove_files(
      compute_tp, filtered_fragment_uris.fragment_vac_uris_to_vacuum());

  // Delete fragment directories
  throw_if_not_ok(parallel_for(
      compute_tp, 0, fragment_uris_to_vacuum.size(), [&](size_t i) {
        RETURN_NOT_OK(vfs->remove_dir(fragment_uris_to_vacuum[i]));

        return Status::Ok();
      }));
}

/* ****************************** */
/*        PRIVATE METHODS         */
/* ****************************** */

bool FragmentConsolidator::are_consolidatable(
    const Domain& domain,
    const FragmentInfo& fragment_info,
    size_t start,
    size_t end,
    const NDRange& union_non_empty_domains) const {
  auto anterior_ndrange = fragment_info.anterior_ndrange();
  if (anterior_ndrange.size() != 0 &&
      domain.overlap(union_non_empty_domains, anterior_ndrange))
    return false;

  // Check overlap of union with earlier fragments
  const auto& fragments = fragment_info.single_fragment_info_vec();
  for (size_t i = 0; i < start; ++i) {
    if (domain.overlap(
            union_non_empty_domains, fragments[i].non_empty_domain()))
      return false;
  }

  // Check consolidation amplification factor
  auto union_cell_num = domain.cell_num(union_non_empty_domains);
  uint64_t sum_cell_num = 0;
  for (size_t i = start; i <= end; ++i) {
    sum_cell_num += domain.cell_num(fragments[i].expanded_non_empty_domain());
  }

  return (double(union_cell_num) / sum_cell_num) <= config_.amplification_;
}

Status FragmentConsolidator::consolidate_internal(
    shared_ptr<Array> array_for_reads,
    shared_ptr<Array> array_for_writes,
    const std::vector<TimestampedURI>& to_consolidate,
    const NDRange& union_non_empty_domains,
    URI* new_fragment_uri) {
  auto timer_se = stats_->start_timer("consolidate_internal");

  RETURN_NOT_OK(array_for_reads->load_fragments(to_consolidate));

  if (array_for_reads->is_empty()) {
    return Status::Ok();
  }

  // Get schema
  const auto& array_schema = array_for_reads->array_schema_latest();

  // If there are any delete conditions coming after the first fragment or if
  // there are any fragments with delete meta, the new fragment will include
  // delete meta.
  if (!config_.purge_deleted_cells_ &&
      array_schema.write_version() >= constants::deletes_min_version) {
    // Get the first fragment first timestamp.
    std::pair<uint64_t, uint64_t> timestamps;
    RETURN_NOT_OK(
        utils::parse::get_timestamp_range(to_consolidate[0].uri_, &timestamps));

    for (auto& delete_and_update_tile_location :
         array_for_reads->array_directory()
             .delete_and_update_tiles_location()) {
      if (delete_and_update_tile_location.timestamp() >= timestamps.first) {
        config_.with_delete_meta_ = true;
        break;
      }
    }

    if (!config_.with_delete_meta_) {
      for (auto& frag_md : array_for_reads->fragment_metadata()) {
        if (frag_md->has_delete_meta()) {
          config_.with_delete_meta_ = true;
          break;
        }
      }
    }
  }

  // Prepare buffers
  std::vector<ByteVec> buffers;
  std::vector<uint64_t> buffer_sizes;
  RETURN_NOT_OK(create_buffers(array_schema, &buffers, &buffer_sizes));

  // Create queries
  auto query_r = (Query*)nullptr;
  auto query_w = (Query*)nullptr;
  auto st = create_queries(
      array_for_reads,
      array_for_writes,
      union_non_empty_domains,
      &query_r,
      &query_w,
      new_fragment_uri);
  if (!st.ok()) {
    tdb_delete(query_r);
    tdb_delete(query_w);
    return st;
  }

  // Get the vacuum URI
  URI vac_uri;
  try {
    vac_uri =
        array_for_reads->array_directory().get_vacuum_uri(*new_fragment_uri);
  } catch (std::exception& e) {
    tdb_delete(query_r);
    tdb_delete(query_w);
    std::throw_with_nested(
        std::logic_error("[FragmentConsolidator::consolidate_internal] "));
  }

  // Read from one array and write to the other
  st = copy_array(query_r, query_w, &buffers, &buffer_sizes);
  if (!st.ok()) {
    tdb_delete(query_r);
    tdb_delete(query_w);
    return st;
  }

  // Finalize write query
  st = query_w->finalize();
  if (!st.ok()) {
    tdb_delete(query_r);
    tdb_delete(query_w);
    bool is_dir = false;
    auto st2 = storage_manager_->vfs()->is_dir(*new_fragment_uri, &is_dir);
    (void)st2;  // Perhaps report this once we support an error stack
    if (is_dir)
      throw_if_not_ok(storage_manager_->vfs()->remove_dir(*new_fragment_uri));
    return st;
  }

  // Write vacuum file
  st = write_vacuum_file(vac_uri, to_consolidate);
  if (!st.ok()) {
    tdb_delete(query_r);
    tdb_delete(query_w);
    bool is_dir = false;
    throw_if_not_ok(
        storage_manager_->vfs()->is_dir(*new_fragment_uri, &is_dir));
    if (is_dir)
      throw_if_not_ok(storage_manager_->vfs()->remove_dir(*new_fragment_uri));
    return st;
  }

  // Clean up
  tdb_delete(query_r);
  tdb_delete(query_w);

  return st;
}

Status FragmentConsolidator::copy_array(
    Query* query_r,
    Query* query_w,
    std::vector<ByteVec>* buffers,
    std::vector<uint64_t>* buffer_sizes) {
  auto timer_se = stats_->start_timer("consolidate_copy_array");

  // Set the read query buffers outside the repeated submissions.
  // The Reader will reset the query buffer sizes to the original
  // sizes, not the potentially smaller sizes of the results after
  // the query submission.
  RETURN_NOT_OK(set_query_buffers(query_r, buffers, buffer_sizes));

  do {
    // READ
    RETURN_NOT_OK(query_r->submit());

    // If Consolidation cannot make any progress, throw. The first buffer will
    // always contain fixed size data, wether it is tile offsets for var size
    // attribute/dimension or the actual fixed size data so we can use its size
    // to know if any cells were written or not.
    if (buffer_sizes->at(0) == 0) {
      throw FragmentConsolidatorStatusException(
          "Consolidation read 0 cells, no progress can be made");
    }

    // Set explicitly the write query buffers, as the sizes may have
    // been altered by the read query.
    RETURN_NOT_OK(set_query_buffers(query_w, buffers, buffer_sizes));

    // WRITE
    RETURN_NOT_OK(query_w->submit());
  } while (query_r->status() == QueryStatus::INCOMPLETE);

  return Status::Ok();
}

Status FragmentConsolidator::create_buffers(
    const ArraySchema& array_schema,
    std::vector<ByteVec>* buffers,
    std::vector<uint64_t>* buffer_sizes) {
  auto timer_se = stats_->start_timer("consolidate_create_buffers");

  // For easy reference
  auto attribute_num = array_schema.attribute_num();
  auto& domain{array_schema.domain()};
  auto dim_num = array_schema.dim_num();
  auto sparse = !array_schema.dense();

  // Calculate number of buffers
  size_t buffer_num = 0;
  for (unsigned i = 0; i < attribute_num; ++i) {
    buffer_num += (array_schema.attributes()[i]->var_size()) ? 2 : 1;
    buffer_num += (array_schema.attributes()[i]->nullable()) ? 1 : 0;
  }
  if (sparse) {
    for (unsigned i = 0; i < dim_num; ++i)
      buffer_num += (domain.dimension_ptr(i)->var_size()) ? 2 : 1;
  }
  if (config_.with_timestamps_ && sparse) {
    buffer_num++;
  }

  // Adding buffers for delete meta, one for timestamp and one for condition
  // index.
  if (config_.with_delete_meta_) {
    buffer_num += 2;
  }

  // Create buffers
  buffers->resize(buffer_num);
  buffer_sizes->resize(buffer_num);

  // Allocate space for each buffer
  for (unsigned i = 0; i < buffer_num; ++i) {
    (*buffers)[i].resize(config_.buffer_size_);
    (*buffer_sizes)[i] = config_.buffer_size_;
  }

  // Success
  return Status::Ok();
}

Status FragmentConsolidator::create_queries(
    shared_ptr<Array> array_for_reads,
    shared_ptr<Array> array_for_writes,
    const NDRange& subarray,
    Query** query_r,
    Query** query_w,
    URI* new_fragment_uri) {
  auto timer_se = stats_->start_timer("consolidate_create_queries");

  const auto dense = array_for_reads->array_schema_latest().dense();

  // Note: it is safe to use `set_subarray_safe` for `subarray` below
  // because the subarray is calculated by the TileDB algorithm (it
  // is not a user input prone to errors).

  // Create read query
  *query_r = tdb_new(Query, storage_manager_, array_for_reads);
  RETURN_NOT_OK((*query_r)->set_layout(Layout::GLOBAL_ORDER));

  // Dense consolidation will do a tile aligned read.
  if (dense) {
    NDRange read_subarray = subarray;
    auto& domain{array_for_reads->array_schema_latest().domain()};
    domain.expand_to_tiles(&read_subarray);
    RETURN_NOT_OK((*query_r)->set_subarray_unsafe(read_subarray));
  }

  // Enable consolidation with timestamps on the reader, if applicable.
  if (config_.with_timestamps_ && !dense) {
    throw_if_not_ok((*query_r)->set_consolidation_with_timestamps());
  }

  // Get last fragment URI, which will be the URI of the consolidated fragment
  auto first = (*query_r)->first_fragment_uri();
  auto last = (*query_r)->last_fragment_uri();

  auto write_version = array_for_reads->array_schema_latest().write_version();
  auto&& [st, fragment_name] =
      array_for_reads->array_directory().compute_new_fragment_name(
          first, last, write_version);
  RETURN_NOT_OK(st);

  // Create write query
  *query_w = tdb_new(Query, storage_manager_, array_for_writes, fragment_name);
  RETURN_NOT_OK((*query_w)->set_layout(Layout::GLOBAL_ORDER));
  RETURN_NOT_OK((*query_w)->disable_checks_consolidation());
  (*query_w)->set_fragment_size(config_.max_fragment_size_);
  if (array_for_reads->array_schema_latest().dense()) {
    RETURN_NOT_OK((*query_w)->set_subarray_unsafe(subarray));
  }

  // Set the processed conditions on new fragment.
  const auto& delete_and_update_tiles_location =
      (*query_r)->array()->array_directory().delete_and_update_tiles_location();
  std::vector<std::string> processed_conditions;
  processed_conditions.reserve(delete_and_update_tiles_location.size());
  for (auto& location : delete_and_update_tiles_location) {
    processed_conditions.emplace_back(location.condition_marker());
  }
  (*query_w)->set_processed_conditions(processed_conditions);

  // Set the URI for the new fragment.
  auto frag_uri =
      array_for_reads->array_directory().get_fragments_dir(write_version);
  *new_fragment_uri = frag_uri.join_path(fragment_name.value());

  return Status::Ok();
}

Status FragmentConsolidator::compute_next_to_consolidate(
    const ArraySchema& array_schema,
    const FragmentInfo& fragment_info,
    std::vector<TimestampedURI>* to_consolidate,
    NDRange* union_non_empty_domains) const {
  auto timer_se = stats_->start_timer("consolidate_compute_next");

  // Preparation
  auto sparse = !array_schema.dense();
  const auto& fragments = fragment_info.single_fragment_info_vec();
  auto& domain{array_schema.domain()};
  to_consolidate->clear();
  auto min = config_.min_frags_;
  min = (uint32_t)((min > fragments.size()) ? fragments.size() : min);
  auto max = config_.max_frags_;
  max = (uint32_t)((max > fragments.size()) ? fragments.size() : max);
  auto size_ratio = config_.size_ratio_;

  // Trivial case - no fragments
  if (max == 0)
    return Status::Ok();

  // Prepare the dynamic-programming matrices. The rows are from 1 to max
  // and the columns represent the fragments in `fragments`. One matrix
  // stores the sum of fragment sizes, and the other the union of the
  // corresponding non-empty domains of the fragments.
  std::vector<std::vector<uint64_t>> m_sizes;
  std::vector<std::vector<NDRange>> m_union;
  auto col_num = fragments.size();
  auto row_num = max;
  m_sizes.resize(row_num);
  for (auto& row : m_sizes)
    row.resize(col_num);
  m_union.resize(row_num);
  for (auto& row : m_union) {
    row.resize(col_num);
  }

  // Entry m[i][j] contains the collective size of fragments
  // fragments[j], ..., fragments[j+i]. If the size ratio
  // of any adjacent pair in the above list is smaller than the
  // defined one, or the entries' corresponding fragments are no
  // consolidatable, then the size sum of that entry is infinity
  // (UINT64_MAX) and the memory from the union matrix is freed.
  // This marks this entry as invalid and it will never be selected
  // as the winner for choosing which fragments to consolidate next.
  for (size_t i = 0; i < row_num; ++i) {
    for (size_t j = 0; j < col_num; ++j) {
      if (i == 0) {  // In the first row we store the sizes of `fragments`
        m_sizes[i][j] = fragments[j].fragment_size();
        m_union[i][j] = fragments[j].non_empty_domain();
      } else if (i + j >= col_num) {  // Non-valid entries
        m_sizes[i][j] = UINT64_MAX;
        m_union[i][j].clear();
        m_union[i][j].shrink_to_fit();
      } else {  // Every other row is computed using the previous row
        auto ratio = (float)fragments[i + j - 1].fragment_size() /
                     fragments[i + j].fragment_size();
        ratio = (ratio <= 1.0f) ? ratio : 1.0f / ratio;
        if (ratio >= size_ratio && (m_sizes[i - 1][j] != UINT64_MAX)) {
          m_sizes[i][j] = m_sizes[i - 1][j] + fragments[i + j].fragment_size();
          m_union[i][j] = m_union[i - 1][j];
          domain.expand_ndrange(
              fragments[i + j].non_empty_domain(), &m_union[i][j]);
          if (!sparse && !are_consolidatable(
                             domain, fragment_info, j, j + i, m_union[i][j])) {
            // Mark this entry as invalid
            m_sizes[i][j] = UINT64_MAX;
            m_union[i][j].clear();
            m_union[i][j].shrink_to_fit();
          }
        } else {
          // Mark this entry as invalid
          m_sizes[i][j] = UINT64_MAX;
          m_union[i][j].clear();
          m_union[i][j].shrink_to_fit();
        }
      }
    }
  }

  // Choose the maximal set of fragments with cardinality in [min, max]
  // with the minimum size
  uint64_t min_size = UINT64_MAX;
  size_t min_col = 0;
  for (int i = row_num - 1; (i >= 0 && i >= (int)min - 1); --i) {
    min_size = UINT64_MAX;
    for (size_t j = 0; j < col_num; ++j) {
      // Update the min size if the new size is more than 25% smaller.
      // This is to give preference to earlier fragment sets, in case
      // the user writes in *approximately* equal batches. Otherwise,
      // fragment sets in the middle of the timeline may get consolidated,
      // which will hinder the next step of consolidation (which will
      // select some small and some big fragments).
      if (min_size == UINT64_MAX || m_sizes[i][j] < (min_size / 1.25)) {
        min_size = m_sizes[i][j];
        min_col = j;
      }
    }

    // Results not found
    if (min_size == UINT64_MAX)
      continue;

    // Results found
    for (size_t f = min_col; f <= min_col + i; ++f) {
      to_consolidate->emplace_back(
          fragments[f].uri(), fragments[f].timestamp_range());
    }
    *union_non_empty_domains = m_union[i][min_col];
    break;
  }

  return Status::Ok();
}

Status FragmentConsolidator::set_query_buffers(
    Query* query,
    std::vector<ByteVec>* buffers,
    std::vector<uint64_t>* buffer_sizes) const {
  const auto& array_schema = query->array_schema();
  auto dim_num = array_schema.dim_num();
  auto dense = array_schema.dense();
  auto attributes = array_schema.attributes();
  unsigned bid = 0;

  // Here the first buffer should always be the fixed buffer (either offsets or
  // fixed data) as we use the first buffer size to determine if any cells were
  // written or not.
  for (const auto& attr : attributes) {
    if (!attr->var_size()) {
      if (!attr->nullable()) {
        RETURN_NOT_OK(query->set_data_buffer(
            attr->name(), (void*)&(*buffers)[bid][0], &(*buffer_sizes)[bid]));
        ++bid;
      } else {
        RETURN_NOT_OK(query->set_buffer_vbytemap(
            attr->name(),
            (void*)&(*buffers)[bid][0],
            &(*buffer_sizes)[bid],
            (uint8_t*)&(*buffers)[bid + 1][0],
            &(*buffer_sizes)[bid + 1]));
        bid += 2;
      }
    } else {
      if (!attr->nullable()) {
        RETURN_NOT_OK(query->set_data_buffer(
            attr->name(),
            (void*)&(*buffers)[bid + 1][0],
            &(*buffer_sizes)[bid + 1]));
        RETURN_NOT_OK(query->set_offsets_buffer(
            attr->name(),
            (uint64_t*)&(*buffers)[bid][0],
            &(*buffer_sizes)[bid]));
        bid += 2;
      } else {
        RETURN_NOT_OK(query->set_buffer_vbytemap(
            attr->name(),
            (uint64_t*)&(*buffers)[bid][0],
            &(*buffer_sizes)[bid],
            (void*)&(*buffers)[bid + 1][0],
            &(*buffer_sizes)[bid + 1],
            (uint8_t*)&(*buffers)[bid + 2][0],
            &(*buffer_sizes)[bid + 2]));
        bid += 3;
      }
    }
  }
  if (!dense) {
    for (unsigned d = 0; d < dim_num; ++d) {
      auto dim{array_schema.dimension_ptr(d)};
      auto dim_name = dim->name();
      if (!dim->var_size()) {
        RETURN_NOT_OK(query->set_data_buffer(
            dim_name, (void*)&(*buffers)[bid][0], &(*buffer_sizes)[bid]));
        ++bid;
      } else {
        RETURN_NOT_OK(query->set_data_buffer(
            dim_name,
            (void*)&(*buffers)[bid + 1][0],
            &(*buffer_sizes)[bid + 1]));
        RETURN_NOT_OK(query->set_offsets_buffer(
            dim_name, (uint64_t*)&(*buffers)[bid][0], &(*buffer_sizes)[bid]));
        bid += 2;
      }
    }
  }

  if (config_.with_timestamps_ && !dense) {
    RETURN_NOT_OK(query->set_data_buffer(
        constants::timestamps,
        (void*)&(*buffers)[bid][0],
        &(*buffer_sizes)[bid]));
    ++bid;
  }

  if (config_.with_delete_meta_ && !dense) {
    RETURN_NOT_OK(query->set_data_buffer(
        constants::delete_timestamps,
        (void*)&(*buffers)[bid][0],
        &(*buffer_sizes)[bid]));
    ++bid;
    RETURN_NOT_OK(query->set_data_buffer(
        constants::delete_condition_index,
        (void*)&(*buffers)[bid][0],
        &(*buffer_sizes)[bid]));
    ++bid;
  }

  return Status::Ok();
}

Status FragmentConsolidator::set_config(const Config& config) {
  // Set the consolidation config for ease of use
  Config merged_config = storage_manager_->config();
  merged_config.inherit(config);
  bool found = false;
  config_.amplification_ = 0.0f;
  RETURN_NOT_OK(merged_config.get<float>(
      "sm.consolidation.amplification", &config_.amplification_, &found));
  assert(found);
  config_.steps_ = 0;
  RETURN_NOT_OK(merged_config.get<uint32_t>(
      "sm.consolidation.steps", &config_.steps_, &found));
  assert(found);
  config_.buffer_size_ = 0;
  RETURN_NOT_OK(merged_config.get<uint64_t>(
      "sm.consolidation.buffer_size", &config_.buffer_size_, &found));
  assert(found);
  config_.max_fragment_size_ = 0;
  RETURN_NOT_OK(merged_config.get<uint64_t>(
      "sm.consolidation.max_fragment_size",
      &config_.max_fragment_size_,
      &found));
  assert(found);
  config_.size_ratio_ = 0.0f;
  RETURN_NOT_OK(merged_config.get<float>(
      "sm.consolidation.step_size_ratio", &config_.size_ratio_, &found));
  assert(found);
  config_.purge_deleted_cells_ = false;
  RETURN_NOT_OK(merged_config.get<bool>(
      "sm.consolidation.purge_deleted_cells",
      &config_.purge_deleted_cells_,
      &found));
  assert(found);
  config_.min_frags_ = 0;
  RETURN_NOT_OK(merged_config.get<uint32_t>(
      "sm.consolidation.step_min_frags", &config_.min_frags_, &found));
  assert(found);
  config_.max_frags_ = 0;
  RETURN_NOT_OK(merged_config.get<uint32_t>(
      "sm.consolidation.step_max_frags", &config_.max_frags_, &found));
  assert(found);
  RETURN_NOT_OK(merged_config.get<uint64_t>(
      "sm.consolidation.timestamp_start", &config_.timestamp_start_, &found));
  assert(found);
  RETURN_NOT_OK(merged_config.get<uint64_t>(
      "sm.consolidation.timestamp_end", &config_.timestamp_end_, &found));
  assert(found);
  std::string reader =
      merged_config.get("sm.query.sparse_global_order.reader", &found);
  assert(found);
  config_.use_refactored_reader_ = reader.compare("refactored") == 0;
  config_.with_timestamps_ = true;
  config_.with_delete_meta_ = false;

  // Sanity checks
  if (config_.min_frags_ > config_.max_frags_)
    return logger_->status(Status_ConsolidatorError(
        "Invalid configuration; Minimum fragments config parameter is larger "
        "than the maximum"));
  if (config_.size_ratio_ > 1.0f || config_.size_ratio_ < 0.0f)
    return logger_->status(Status_ConsolidatorError(
        "Invalid configuration; Step size ratio config parameter must be in "
        "[0.0, 1.0]"));
  if (config_.amplification_ < 0)
    return logger_->status(
        Status_ConsolidatorError("Invalid configuration; Amplification config "
                                 "parameter must be non-negative"));

  return Status::Ok();
}

Status FragmentConsolidator::write_vacuum_file(
    const URI& vac_uri,
    const std::vector<TimestampedURI>& to_consolidate) const {
  std::stringstream ss;
  for (const auto& timestampedURI : to_consolidate)
    ss << timestampedURI.uri_.to_string() << "\n";

  auto data = ss.str();
  RETURN_NOT_OK(
      storage_manager_->vfs()->write(vac_uri, data.c_str(), data.size()));
  RETURN_NOT_OK(storage_manager_->vfs()->close_file(vac_uri));

  return Status::Ok();
}

}  // namespace tiledb::sm


text:
#region Copyright and license information
// Copyright 2010-2011 Jon Skeet
//
// 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.
#endregion
using System;
using System.Collections.Generic;

namespace Edulinq
{
    public static partial class Enumerable
    {
        public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(
            this IOrderedEnumerable<TSource> source,
            Func<TSource, TKey> keySelector)
        {
            return ThenByDescending(source, keySelector, Comparer<TKey>.Default);
        }

        public static IOrderedEnumerable<TSource> ThenByDescending<TSource, TKey>(
            this IOrderedEnumerable<TSource> source,
            Func<TSource, TKey> keySelector,
            IComparer<TKey> comparer)
        {
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }
            if (keySelector == null)
            {
                throw new ArgumentNullException("keySelector");
            }
            return source.CreateOrderedEnumerable(keySelector, comparer, true);
        }
    }
}


text:
using System;

namespace Braintree
{
    public class RangeNode<T> : SearchNode<T> where T : SearchRequest
    {
        public RangeNode(String name, T parent) : base(name, parent)
        {
        }

        public T Between(object min, object max) {
            GreaterThanOrEqualTo(min);
            LessThanOrEqualTo(max);
            return Parent;
        }

        public T GreaterThanOrEqualTo(object min) {
            Parent.AddRangeCriteria(Name, new SearchCriteria("min", min.ToString()));
            return Parent;
        }

        public T Is(object value) {
            Parent.AddCriteria(Name, new SearchCriteria("is", value.ToString()));
            return Parent;
        }

        public T LessThanOrEqualTo(object max) {
            Parent.AddRangeCriteria(Name, new SearchCriteria("max", max.ToString()));
            return Parent;
        }
    }
}


text:
/* jasmine specs for controllers go here */

describe('ConfirmCtrl', function () {
    'use strict';
    beforeEach(module('peid'));

    describe("scope work", function () {
        var scope, location, confirmCtrl;
        beforeEach(inject(function ($rootScope, $controller, $location) {
            location = $location;
            scope = $rootScope.$new();
            confirmCtrl = $controller("ConfirmCtrl", {
                $scope: scope
            });
        }));

        it('should be defined', inject(function () {
            expect(confirmCtrl).toBeDefined();
        }));

        it('BillSplitterService should be defined', inject(function (BillSplitterService) {
            expect(BillSplitterService).toBeDefined();
        }));

        describe("when Confirm is pressed (onConfirmClicked)", function () {
            var parseFunctionService;
            beforeEach(inject(function (ParseFunctionService) {
                parseFunctionService = ParseFunctionService;
                spyOn(parseFunctionService, 'sendBills');
            }));

            it('onConfirmClicked should be defined', function () {
                expect(scope.onConfirmClicked).toBeDefined();
            });

            it('should call parse function to send split bill emails', function () {
                scope.onConfirmClicked();
                expect(parseFunctionService.sendBills.calls.length).toEqual(1);
            });

            it('should redirect to rating page on click', inject(function ($location) {
                spyOn($location, 'path');
                scope.onConfirmClicked();
                expect($location.path).toHaveBeenCalledWith("/tab/rating");
            }));
        });

        it('should update breakdown as BillSplitterService publish changes', inject(function (BillSplitterService) {
            var modelAns = [578.87, 4, 144.72, 2.9, 147.62];
            var keys = [
                'billAmount',
                'partySize',
                'costPerPerson',
                'costOfMagic',
                'billPerPerson'
            ];

            var modelBreakdown = _.zipObject(keys, modelAns);
            // note that 3 email + user = party of 4.
            var newContacts = ["a@cd.com", "ab@cd.com", "abc@cd.com"];

            BillSplitterService.updateBillDetails({
                'contacts': newContacts,
                'billAmount': '' + modelBreakdown.billAmount
            });

            for (var j = 0; j < keys.length; j++) {
                var modelAnswerAsString = modelBreakdown[keys[j]];
                expect(_.contains(scope.formattedBreakdown[keys[j]].content, modelAnswerAsString)).toBe(true);
            }
        }));

        it('should update contacts as BillSplitterService publish changes', inject(function (BillSplitterService) {
            var modelAns = [578.87, 4, 144.72, 2.9, 147.62];
            var keys = [
                'billAmount',
                'partySize',
                'costPerPerson',
                'costOfMagic',
                'billPerPerson'
            ];

            var modelBreakdown = _.zipObject(keys, modelAns);
            // note that 3 email + user = party of 4.
            var newContacts = ["a@cd.com", "ab@cd.com", "abc@cd.com"];

            BillSplitterService.updateBillDetails({
                'contacts': newContacts,
                'billAmount': '' + modelBreakdown.billAmount
            });

            expect(scope.billDetails.contacts).toEqual(newContacts);
        }));

        describe("breakdown formatter", function () {
            it('should have a set structure for all of its items', function () {
                var givenBreakdown = {
                    billAmount: "999.99",
                    partySize: "12",
                    costPerPerson: '12.34',
                    costOfMagic: '0.45',
                    billPerPerson: '45.67'
                };
                var expectedFormattedBreakdown = {
                    billAmount: {
                        'row': 0,
                        'icon': 'ion-pricetag',
                        'name': 'Bill Amount',
                        'color': 'energized',
                        'content': '£999.99'
                    },
                    partySize: {
                        'row': 1,
                        'icon': 'ion-person-stalker',
                        'name': 'Party Size',
                        'color': '',
                        'content': '÷ 12'
                    },
                    costPerPerson: {
                        'row': 2,
                        'icon': 'ion-person',
                        'name': 'Cost per person',
                        'color': '',
                        'content': '= £12.34'
                    },
                    costOfMagic: {
                        'row': 3,
                        'icon': 'ion-wand',
                        'name': 'Cost of magic (2%)',
                        'color': '',
                        'content': '+ £0.45'
                    },
                    billPerPerson: {
                        'row': 4,
                        'icon': 'ion-card',
                        'name': 'Bill per person',
                        'color': 'balanced',
                        'content': '= £45.67'
                    }
                };
                expect(confirmCtrl.getFormattedBreakdown(givenBreakdown)).toEqual(expectedFormattedBreakdown);
            });
        });

    });
});


text:
/* tslint:disable:no-unused-expression */
import * as chai from 'chai'
import * as sinon from 'sinon'
import * as spies from 'sinon-chai'

chai.use(spies)
const expect = chai.expect

import { RequestLoggingHandler } from 'logging/requestPromiseLoggingHandler'
import { ApiLogger } from 'logging/apiLogger'

describe('RequestLoggingHandler', () => {
  let handler
  let proxy
  let options

  /* tslint:disable:no-empty allow empty for mocking */
  let requestPromise = {
    get: (options) => { },
    post: (options) => { },
    put: (options) => { },
    del: (options) => { },
    delete: (options) => { },
    patch: (options) => { },
    head: (options) => { },
    another: (options) => { }
  }

  let apiLogger = {
    logRequest: (requestData) => { },
    logResponse: (responseData) => { }
  }
  /* tslint:enable:no-empty */

  beforeEach(() => {
    options = {}
    handler = new RequestLoggingHandler(requestPromise, apiLogger as ApiLogger)
    proxy = new Proxy(requestPromise, handler)
  })

  it('should throw an error when initialised without request', () => {
    expect(() => new RequestLoggingHandler(undefined)).to.throw(Error)
  })

  describe('request-promise http calls proxy', () => {
    let logRequestCall

    beforeEach(() => {
      logRequestCall = sinon.spy(apiLogger, 'logRequest')
    })

    afterEach(() => {
      logRequestCall.restore()
    })

    const suiteParameters = [
      { paramName: 'options object', param: {} },
      { paramName: 'uri string', param: 'http://local.instance/some/path' }
    ]

    suiteParameters.forEach((suite) => {
      describe(`when passed an ${suite.paramName}`, () => {
        it('should handle logging on a get call', () => {
          proxy.get(suite.param)
          expect(logRequestCall).to.have.been.called
        })

        it('should handle logging on a put call', () => {
          proxy.put(suite.param)
          expect(logRequestCall).to.have.been.called
        })

        it('should handle logging on a post call', () => {
          proxy.post(suite.param)
          expect(logRequestCall).to.have.been.called
        })

        it('should handle logging on a del call', () => {
          proxy.del(suite.param)
          expect(logRequestCall).to.have.been.called
        })

        it('should handle logging on a delete call', () => {
          proxy.delete(suite.param)
          expect(logRequestCall).to.have.been.called
        })

        it('should handle logging on a patch call', () => {
          proxy.patch(suite.param)
          expect(logRequestCall).to.have.been.called
        })

        it('should handle logging on a head call', () => {
          proxy.head(suite.param)
          expect(logRequestCall).to.have.been.called
        })

        it('should not handle logging on other calls', () => {
          proxy.another(suite.param)
          expect(logRequestCall).not.to.have.been.called
        })
      })
    })
  })

  describe('handleLogging', () => {
    let originalCallback

    beforeEach(() => {
      originalCallback = sinon.spy()
    })

    it('should assign a callback to the options object', () => {
      handler.handleLogging('any', options)
      // tslint:disable:disable-next-line no-unused-expression allow chai to be used without ()
      expect(options.callback).not.to.be.undefined
    })

    it('should override the originally assigned callback', () => {
      options.callback = originalCallback
      handler.handleLogging('any', options)

      expect(options.callback).not.to.equal(originalCallback)
    })

    it('should call the original callback defined in options object', () => {
      options.callback = originalCallback
      handler.handleLogging('any', options)
      options.callback()

      expect(originalCallback).to.have.been.called
    })
  })
})


text:
package io.dropwizard.testing.junit5;

import io.dropwizard.cli.CheckCommand;
import io.dropwizard.configuration.ResourceConfigurationSourceProvider;
import io.dropwizard.testing.app.DropwizardTestApplication;
import io.dropwizard.testing.app.TestConfiguration;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;

@ExtendWith(DropwizardExtensionsSupport.class)
class DropwizardAppExtensionWithCheckCommandTest {

    private static final DropwizardAppExtension<TestConfiguration> EXTENSION = new DropwizardAppExtension<>(
        DropwizardTestApplication.class, "test-config.yaml", new ResourceConfigurationSourceProvider(), null, CheckCommand::new);

    @Test
    void returnsConfiguration() {
        assertThat(EXTENSION.getConfiguration().getMessage()).isEqualTo("Yes, it's here");
    }

    @Test
    void returnsApplication() {
        assertThat(EXTENSION.<DropwizardTestApplication>getApplication()).isNotNull();
    }

    @Test
    void environmentIsNull() {
        assertThatNullPointerException().isThrownBy(EXTENSION::getEnvironment);
    }
}


text:
'use strict';

var Ogr = require('./../ogr');

function GeoPackageFormat () {}

GeoPackageFormat.prototype = new Ogr('gpkg');

GeoPackageFormat.prototype._contentType = 'application/x-sqlite3; charset=utf-8';
GeoPackageFormat.prototype._fileExtension = 'gpkg';
// As of GDAL 1.10.1 SRID detection is bogus, so we use
// our own method. See:
//  http://trac.osgeo.org/gdal/ticket/5131
//  http://trac.osgeo.org/gdal/ticket/5287
//  http://github.com/CartoDB/CartoDB-SQL-API/issues/110
//  http://github.com/CartoDB/CartoDB-SQL-API/issues/116
// Bug was fixed in GDAL 1.10.2
GeoPackageFormat.prototype._needSRS = true;

GeoPackageFormat.prototype.generate = function (options, callback) {
    options.cmd_params = ['-lco', 'FID=cartodb_id'];
    this.toOGR_SingleFile(options, 'GPKG', callback);
};

module.exports = GeoPackageFormat;


text:
require 'abstract_unit'
require 'active_support/core_ext/thread'

class ThreadExt < ActiveSupport::TestCase
  def test_main_thread_variable_in_enumerator
    assert_equal Thread.main, Thread.current

    Thread.current.thread_variable_set :foo, "bar"

    thread, value = Fiber.new {
      Fiber.yield [Thread.current, Thread.current.thread_variable_get(:foo)]
    }.resume

    assert_equal Thread.current, thread
    assert_equal Thread.current.thread_variable_get(:foo), value
  end

  def test_thread_variable_in_enumerator
    Thread.new {
      Thread.current.thread_variable_set :foo, "bar"

      thread, value = Fiber.new {
        Fiber.yield [Thread.current, Thread.current.thread_variable_get(:foo)]
      }.resume

      assert_equal Thread.current, thread
      assert_equal Thread.current.thread_variable_get(:foo), value
    }.join
  end

  def test_thread_variables
    assert_equal [], Thread.new { Thread.current.thread_variables }.join.value

    t = Thread.new {
      Thread.current.thread_variable_set(:foo, "bar")
      Thread.current.thread_variables
    }
    assert_equal [:foo], t.join.value
  end

  def test_thread_variable?
    assert_not Thread.new { Thread.current.thread_variable?("foo") }.join.value
    t = Thread.new {
      Thread.current.thread_variable_set("foo", "bar")
    }.join

    assert t.thread_variable?("foo")
    assert t.thread_variable?(:foo)
    assert_not t.thread_variable?(:bar)
  end

  def test_thread_variable_strings_and_symbols_are_the_same_key
    t = Thread.new {}.join
    t.thread_variable_set("foo", "bar")
    assert_equal "bar", t.thread_variable_get(:foo)
  end

  def test_thread_variable_frozen
    t = Thread.new { }.join
    t.freeze
    assert_raises(RuntimeError) do
      t.thread_variable_set(:foo, "bar")
    end
  end

  def test_thread_variable_frozen_after_set
    t = Thread.new { }.join
    t.thread_variable_set :foo, "bar"
    t.freeze
    assert_raises(RuntimeError) do
      t.thread_variable_set(:baz, "qux")
    end
  end

end