text:
package eu.codlab.crashlytics_wear;

import android.app.Application;
import android.content.Intent;

/**
 * Created by kevinleperf on 06/12/2015.
 */
public class CrashlyticsWearExceptionCatcher implements Thread.UncaughtExceptionHandler {

    private Application _application;
    private Thread.UncaughtExceptionHandler _default;

    private CrashlyticsWearExceptionCatcher() {

    }

    public CrashlyticsWearExceptionCatcher(Application application) {
        _application = application;
    }

    public void setDefaultExceptionCatcher(Thread.UncaughtExceptionHandler def) {
        _default = def;
    }

    @Override
    public void uncaughtException(final Thread thread, final Throwable ex) {

        Intent errorIntent = new Intent(_application, ErrorService.class);
        errorIntent.putExtra("exception", ex);
        _application.startService(errorIntent);

        if (_default != null) _default.uncaughtException(thread, ex);
    }

}


text:
using Discord;
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IwuhSelfbot.Commands.Modules
{
    public class FunModule : ModuleBase
    {
        [Command("me")]
        [Summary("Shows the input as if it's an action you're performing.")]
        public async Task MeCommand([Remainder, Summary("The action you're performing.")] string input)
        {
            Color embedColour = Context.User.GetHighestRoleColor(Context.Guild);

            // Create the embed to use as the message.
            EmbedBuilder meEmbed = new EmbedBuilder()
                .WithColor(embedColour)
                .WithDescription($"{Format.Bold((Context.User as SocketGuildUser)?.Nickname ?? Context.User.Username)} {Format.Italics(input)}");

            // Delete the command message.
            await Context.Message.DeleteAsync();
            // Send the "me" message.
            await ReplyAsync(string.Empty, embed: meEmbed);
        }

        [Command("quote")]
        [Summary("Shows a message that somebody else wrote. Does not quote embeds. Note: due to a user account restriction, certain messages may not be able to be quoted.")]
        public async Task QuoteMessage([Summary("The ID of the message to quote.")] ulong id)
        {
            // Users can't access the get message endpoint, but they _can_ access the get messages endpoint.
            var messages = await Context.Channel.GetMessagesAsync(id, Direction.Around, limit: 3).Flatten();
            var message = messages.First(m => m.Id == id);

            // Don't quote any message that's only an embed with no text.
            if (message.Content == string.Empty && message.Embeds.Count > 0)
            {
                await ReplyAsync("The quoted message must have text.");
                return;
            }

            // Get the image attachment, if there is one.
            IAttachment image = message.Attachments.FirstOrDefault(a =>
            {
                string lower = a.Filename.ToLower();
                // Check if it ends with any of these common image file extensions.
                return lower.EndsWith(".png") || lower.EndsWith(".jpg") || lower.EndsWith(".jpeg") || lower.EndsWith(".gif");
            });

            EmbedBuilder quoteBuilder = new EmbedBuilder()
                .WithAuthor(new EmbedAuthorBuilder() { IconUrl = message.Author.GetAvatarUrl(), Name = message.Author.ToString() })
                .WithColor(message.Author.GetHighestRoleColor(Context.Guild))
                .WithDescription(message.Content)
                .WithTimestamp(message.Timestamp);

            if (image != null)
            {
                quoteBuilder.WithImageUrl(image.Url);
            }

            await Context.Message.DeleteAsync();
            await ReplyAsync(string.Empty, embed: quoteBuilder);
        }

        [Command("poll")]
        [Summary("Creates a pool that people can respond to via reactions. Usage: `question|option 1|option 2|etc...`")]
        [RequireBotPermission(ChannelPermission.AddReactions)]
        public async Task CreatePoll([Remainder, Summary("Creates a message with a question and several reaction options.")] string input)
        {
            const int REGIONAL_INDICATOR_A = 0x1F1E6;
            const string THUMBS_UP = "👍";
            const string THUMBS_DOWN = "👎";
            const string CLIPBOARD = "📋";

            var split = input.Split('|');

            if (split.Length == 1)
            {
                await Context.Message.ModifyAsync(m => m.Content = $"{CLIPBOARD}{Format.Italics(split[0])}");
                await Context.Message.AddReactionAsync(THUMBS_UP);
                await Context.Message.AddReactionAsync(THUMBS_DOWN);
            }
            else
            {
                var pollBuilder = new StringBuilder($"{CLIPBOARD}{Format.Italics(split[0])}\n");
                var emojiList = new List<string>();

                for (int i = 1; i < split.Length; i++)
                {
                    string currentEmoji = char.ConvertFromUtf32(REGIONAL_INDICATOR_A + i - 1);
                    pollBuilder.AppendLine($"{currentEmoji} {split[i]}");
                    emojiList.Add(currentEmoji);
                }

                await Context.Message.ModifyAsync(m => m.Content = pollBuilder.ToString());
                foreach (string emoji in emojiList)
                {
                    await Context.Message.AddReactionAsync(emoji);
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <link rel="shortcut icon" href="../../assets/images/ramblers/favicon.ico">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>East Kent Walking Group</title>
    <meta http-equiv="content-type" content="text/html">
    <meta http-equiv="content-style-type" content="text/css">
    <meta http-equiv="content-script-type" content="text/javascript">
    <link rel="stylesheet" type="text/css" href="../../assets/css/style.css" media="all" type="text/css">

East Kent Walking Group

                <xx ng-bind="lastPart"></xx>


text:
class AddExternalIdToOpenResponseAndMultipleChoice < ActiveRecord::Migration[5.1]
  def change
    add_column :embeddable_open_responses, :external_id, :string
    add_column :embeddable_multiple_choices, :external_id, :string
    add_column :embeddable_multiple_choice_choices, :external_id, :string
  end
end


text:
#ifndef BOOST_CONTAINERS_DETAIL_MULTIALLOCATION_CHAIN_HPP
#define BOOST_CONTAINERS_DETAIL_MULTIALLOCATION_CHAIN_HPP

#include "config_begin.hpp"
#include INCLUDE_BOOST_CONTAINER_CONTAINER_FWD_HPP
#include INCLUDE_BOOST_CONTAINER_DETAIL_UTILITIES_HPP
#include INCLUDE_BOOST_CONTAINER_DETAIL_TYPE_TRAITS_HPP
#include INCLUDE_BOOST_CONTAINER_DETAIL_TRANSFORM_ITERATOR_HPP
#include <boost/intrusive/slist.hpp>
#include <boost/pointer_to_other.hpp>
#include INCLUDE_BOOST_CONTAINER_MOVE_HPP

namespace boost {
namespace container {
namespace containers_detail {

template<class VoidPointer>
class basic_multiallocation_chain
{
   private:
   typedef bi::slist_base_hook<bi::void_pointer<VoidPointer>
                        ,bi::link_mode<bi::normal_link>
                        > node;

   typedef bi::slist< node
                    , bi::linear<true>
                    , bi::cache_last<true>
                    > slist_impl_t;
   slist_impl_t slist_impl_;

   static node & to_node(VoidPointer p)
   {  return *static_cast<node*>(static_cast<void*>(containers_detail::get_pointer(p))); }

   BOOST_MOVE_MACRO_MOVABLE_BUT_NOT_COPYABLE(basic_multiallocation_chain)

   public:

   typedef VoidPointer  void_pointer;
   typedef typename slist_impl_t::iterator iterator;

   basic_multiallocation_chain()
      :  slist_impl_()
   {}

   basic_multiallocation_chain(BOOST_MOVE_MACRO_RV_REF(basic_multiallocation_chain) other)
      :  slist_impl_()
   {  slist_impl_.swap(other.slist_impl_); }

   basic_multiallocation_chain& operator=(BOOST_MOVE_MACRO_RV_REF(basic_multiallocation_chain) other)
   {
      basic_multiallocation_chain tmp(BOOST_CONTAINER_MOVE_NAMESPACE::move(other));
      this->swap(tmp);
      return *this;
   }

   bool empty() const
   {  return slist_impl_.empty(); }

   std::size_t size() const
   {  return slist_impl_.size();  }

   iterator before_begin()
   {  return slist_impl_.before_begin(); }

   iterator begin()
   {  return slist_impl_.begin(); }

   iterator end()
   {  return slist_impl_.end(); }

   iterator last()
   {  return slist_impl_.last(); }

   void clear()
   {  slist_impl_.clear(); }

   iterator insert_after(iterator it, void_pointer m)
   {  return slist_impl_.insert_after(it, to_node(m));   }

   void push_front(void_pointer m)
   {  return slist_impl_.push_front(to_node(m));   }

   void push_back(void_pointer m)
   {  return slist_impl_.push_back(to_node(m));   }

   void pop_front()
   {  return slist_impl_.pop_front();   }

   void *front()
   {  return &*slist_impl_.begin();   }

   void splice_after(iterator after_this, basic_multiallocation_chain &x, iterator before_begin, iterator before_end)
   {  slist_impl_.splice_after(after_this, x.slist_impl_, before_begin, before_end);   }

   void splice_after(iterator after_this, basic_multiallocation_chain &x, iterator before_begin, iterator before_end, std::size_t n)
   {  slist_impl_.splice_after(after_this, x.slist_impl_, before_begin, before_end, n);   }

   void splice_after(iterator after_this, basic_multiallocation_chain &x)
   {  slist_impl_.splice_after(after_this, x.slist_impl_);   }

   void incorporate_after(iterator after_this, void_pointer begin , iterator before_end)
   {  slist_impl_.incorporate_after(after_this, &to_node(begin), &to_node(before_end));   }

   void incorporate_after(iterator after_this, void_pointer begin, void_pointer before_end, std::size_t n)
   {  slist_impl_.incorporate_after(after_this, &to_node(begin), &to_node(before_end), n);   }

   void swap(basic_multiallocation_chain &x)
   {  slist_impl_.swap(x.slist_impl_);   }

   static iterator iterator_to(void_pointer p)
   {  return slist_impl_t::s_iterator_to(to_node(p));   }

   std::pair<void_pointer, void_pointer> extract_data()
   {
      std::pair<void_pointer, void_pointer> ret
         (slist_impl_.begin().operator->()
         ,slist_impl_.last().operator->());
      slist_impl_.clear();
      return ret;
   }
};

template<class T>
struct cast_functor
{
   typedef typename containers_detail::add_reference<T>::type result_type;
   template<class U>
   result_type operator()(U &ptr) const
   {  return *static_cast<T*>(static_cast<void*>(&ptr));  }
};

template<class MultiallocationChain, class T>
class transform_multiallocation_chain
{
   private:
   BOOST_MOVE_MACRO_MOVABLE_BUT_NOT_COPYABLE(transform_multiallocation_chain)

   MultiallocationChain   holder_;
   typedef typename MultiallocationChain::void_pointer   void_pointer;
   typedef typename boost::pointer_to_other
      <void_pointer, T>::type                            pointer;

   static pointer cast(void_pointer p)
   {
      return pointer(static_cast<T*>(containers_detail::get_pointer(p)));
   }

   public:
   typedef transform_iterator
      < typename MultiallocationChain::iterator
      , containers_detail::cast_functor <T> >                 iterator;

   transform_multiallocation_chain()
      : holder_()
   {}

   transform_multiallocation_chain(BOOST_MOVE_MACRO_RV_REF(transform_multiallocation_chain) other)
      : holder_()
   {  this->swap(other); }

   transform_multiallocation_chain(BOOST_MOVE_MACRO_RV_REF(MultiallocationChain) other)
      : holder_(BOOST_CONTAINER_MOVE_NAMESPACE::move(other))
   {}

   transform_multiallocation_chain& operator=(BOOST_MOVE_MACRO_RV_REF(transform_multiallocation_chain) other)
   {
      transform_multiallocation_chain tmp(BOOST_CONTAINER_MOVE_NAMESPACE::move(other));
      this->swap(tmp);
      return *this;
   }

   void push_front(pointer mem)
   {  holder_.push_front(mem);  }

   void swap(transform_multiallocation_chain &other_chain)
   {  holder_.swap(other_chain.holder_); }

   void splice_after(iterator after_this, transform_multiallocation_chain &x, iterator before_begin, iterator before_end, std::size_t n)
   {  holder_.splice_after(after_this.base(), x.holder_, before_begin.base(), before_end.base(), n);  }

   void incorporate_after(iterator after_this, void_pointer begin, void_pointer before_end, std::size_t n)
   {  holder_.incorporate_after(after_this.base(), begin, before_end, n);  }

   void pop_front()
   {  holder_.pop_front();  }

   pointer front()
   {  return cast(holder_.front());   }

   bool empty() const
   {  return holder_.empty(); }

   iterator before_begin()
   {  return iterator(holder_.before_begin());   }

   iterator begin()
   {  return iterator(holder_.begin());   }

   iterator end()
   {  return iterator(holder_.end());   }

   iterator last()
   {  return iterator(holder_.last());   }

   std::size_t size() const
   {  return holder_.size();  }

   void clear()
   {  holder_.clear(); }

   iterator insert_after(iterator it, pointer m)
   {  return iterator(holder_.insert_after(it.base(), m)); }

   static iterator iterator_to(pointer p)
   {  return iterator(MultiallocationChain::iterator_to(p));  }

   std::pair<void_pointer, void_pointer> extract_data()
   {  return holder_.extract_data();  }

   MultiallocationChain extract_multiallocation_chain()
   {
      return MultiallocationChain(BOOST_CONTAINER_MOVE_NAMESPACE::move(holder_));
   }
};

}}}

// namespace containers_detail {
// namespace container {
// namespace boost {

#include INCLUDE_BOOST_CONTAINER_DETAIL_CONFIG_END_HPP

#endif   //BOOST_CONTAINERS_DETAIL_MULTIALLOCATION_CHAIN_HPP


text:
static
LONG
write_registry_setting_ex(
    HKEY hRoot,
    char* setting,
    DWORD type,
    void* buffer,
    size_t size
    )
{
    HKEY hKey = 0;
    LONG rc = 0;

    if (rc = RegCreateKeyEx(hRoot, LEASH_SETTINGS_REGISTRY_KEY_NAME, 0, 0, 0,
                            KEY_ALL_ACCESS, 0, &hKey, 0))
        goto cleanup;

    rc = RegSetValueEx(hKey, setting, 0, type, (LPBYTE)buffer, size);
 cleanup:
    if (hKey)
        RegCloseKey(hKey);
    return rc;
}

LONG
write_registry_setting(
    char* setting,
    DWORD type,
    void* buffer,
    size_t size
    )
{
    return write_registry_setting_ex(HKEY_CURRENT_USER,
                                     setting,
                                     type,
                                     buffer,
                                     size);
}

static
LONG
read_registry_setting_ex(
    HKEY hRoot,
    char* setting,
    void* buffer,
    size_t size
    )
{
    HKEY hKey = 0;
    LONG rc = 0;
    DWORD dwType;
    DWORD dwCount;

    if (rc = RegOpenKeyEx(hRoot,
                          LEASH_SETTINGS_REGISTRY_KEY_NAME,
                          0, KEY_QUERY_VALUE, &hKey))
        goto cleanup;

    memset(buffer, 0, size);
    dwCount = size;
    rc = RegQueryValueEx(hKey, setting, NULL, &dwType, (LPBYTE)buffer,
                         &dwCount);
 cleanup:
    if (hKey)
        RegCloseKey(hKey);
    return rc;
}

LONG
read_registry_setting_user(
    char* setting,
    void* buffer,
    size_t size
    )
{
    return read_registry_setting_ex(HKEY_CURRENT_USER, setting, buffer, size);
}

static
LONG
read_registry_setting_machine(
    char* setting,
    void* buffer,
    size_t size
    )
{
    return read_registry_setting_ex(HKEY_LOCAL_MACHINE, setting, buffer, size);
}

LONG
read_registry_setting(
    char* setting,
    void* buffer,
    size_t size
    )
{
    LONG rc;
    rc = read_registry_setting_user(setting, buffer, size);
    if (!rc) return rc;
    rc = read_registry_setting_machine(setting, buffer, size);
    return rc;
}


text:
# What you should know about JavaScript
What you should know about JavaScript: Comprehensive JavaScript tips

## Table Of Contents
  1. [Array](#array)
    1. [Truncate an array](#truncate-an-array)
    2. [Comma in array literal decaration](#comma-in-array-literal-declaration)
    3. [Array is a stack](#array-is-a-stack)
    4. [Array is a queue](#array-is-a-queue)
    5. [Array is a vector](#array-is-a-vector)
  2. [Class](#class)
    1. [Robust class declaration](#robust-class-declaration)
  3. [String](#string)
    1. [Encoded in UTF32](#encoded-in-utf32)
  4. [Date](#date)
    1. [Month and Date](#month-and-date)
    2. [Timezone offset](#timezone-offset)
  4. [Regex](#regex)
  5. [Number](#number)
  6. [Object](#object)
    1. [A clean hash table](#a-clean-hash-table)
    2. [Read-only property](#read-only-property)
  7. [Function](#function)
  8. [Bitwise](#bitwise)
    1. [Zero-fill right shift](#zero-fill-right-shift)
    2. [Get integral part of a decimal number](#get-integral-part-of-a-decimal-number)
  9. [IIFE](#iife)
  10. Miscs (#miscs)
    1. [undefined and void 0](#undefined-and-void-0)
    2. [!0 and !1](#0-and-1)

## Array
#### Truncate an array
To truncate an array from end, it's not necessary to pop up one by one from the end, but setting the `length` property will achieve it.
```javascript
/* truncate an array */
var arr = [1, 2, 3, 4, 5];
arr.length = 2;
console.log(arr); //[1, 2];
```
#### Comma in array literal declaration
In an array literal declaration, if there is no value or element between the last comma `,` and `]`, then the last comma will be ignored.
```javascript
/* the last comma is ignored */
var arr = [1, 2, 3, 4, ];
console.log(arr); //[1, 2, 3, 4]
```
If there is no value or element between two commas, an `undefined` will be inserted there.
```javascript
/* two adjacent commas generate an undefined value */
var arr = [1, 2, , 3];
console.log(arr); //[1, 2, undefined, 3]
```

#### Array is a stack
#### Array is a queue
#### Array is a vector

## Class
#### Robust class declaration
There is no difference between declare a JavaScript normal function and a class function, and to reduce user misuse of a class function as a normal function Pascal naming convention is one of the solution. However, this requires the user to follow the rule and not a technical solution. What we need is a robust class declaration, with it user hardly misuse it: use or not use `new` operation on that class will both generate a correct instance of that class.

We can use `this` keyword to detect whether it is pointing to an instance of that class, and if not create a new instance and return it to user.
```javascript
/* a robust class declaration */
function Customer() {
    if (!(this instanceof Customer)) {
        return new Customer();
    }
}
```

To be more generic, `arguments.callee` can be used to replace the `class` name.
```javascript
/* a generic robust class declaration */
function Customer() {
    if (!(this instanceof arguments.callee)) {
        return new arguments.callee();
    }
}
```

The code works on parameter-less classes, but it does not work on any class with parameters because it throws away the parameters. So, we need to restore the parameters.
```javascript
function Customer(name) {
    if (!(this instanceof Customer)) {
        return new Customer(name);
    }
}
```

But if the class accepts length varying parameters, we cannot simply pass the `arguments` parameter to the internal class instantiation statement, but need handle it element by element.

## String
#### Encoded in UTF32
JavaScript string is encoded in UTF32, so it supports the whole set of unicode characters.

## Date
#### Month and date
JavaScript month starts from 0, but JavaScript date starts from 1.
```javascript
var x = new Date();
x.getMonth(); // starts from 0;
x.getDate(); // starts from 1;
```

#### Timezone offset
JavaScript `Date` object calculates (`getTimezoneOffset()`) by substracting local time from UTC time. So if local time zone is positive the result will be negative.

## Regex
## Number
## Object
#### A clean hash table
By nature, a JavaScript object is a hash table, and we can use it for most scenarios. However, it is not clean because it has some predefined keys there and if there will be conflicts if your data has the same key.
```javascript
var hashtable = {}
hashtable.hasOwnProperty; // function hasOwnProperty()
```
Besides the literal object declaration, an object could also be created using `Object` factory method.
```javascript
/* A definition of clean JavaScript hash table */
var hashtable = Object.create(null);
hashtable.hasOwnProperty; // undefined
```

#### Read-only property
A property defined using `this.some_property` or using object notation is write-able. But to define a read-only property, we can use `Object.defineProperty` method to achieve it.
```javascript
var obj = {};
Object.defineProperty(obj, 'name', {
    get: function() {
        return 'abc';
    }
});

console.log(obj.name); // 'abc'
obj.name = 123;
console.log(obj.name); // 'abc'
```

## Function

## Bitwise
#### Zero-fill right shift
The right shift operator `>>` does not change the sign bit of a number, but zero-fill right shift operator can be used to change a negative number into a positive number.
```javascript
/* 5: 101 (base 2, without sign bit: 0)
   -5: 11111111111111111111111111111011 (base 2, without sign bit: 1)
   4294967291: 11111111111111111111111111111011 (base 2, without sign bit: 0
*/
-5 >>> 0; // 4294967291
```
Zero-fill right shift enables an interesting feature - output the actual binary representation for a negative number: complement code. With the `Number.prototype.toString(2)` method, we could not get the actual binary representation for a negative number.
```javascript
(-5).toString(2); // "-101"
```
But use `>>>` operator to change the sign bit to `0` then we can output the actual binary representation for a negative number.
```javascript
(-5>>>0).toString(2); // "11111111111111111111111111111011"
```

#### Get integral part of a decimal number
In addition to the `parseInt` function to get the integral part of a number, but `>>` and `<<` operators can also be used to get the integral part of a decimal number.
```javascript
123 << 0; // 123
123.456 << 0; // 123
123.456 >> 0; // 123
-456.789 >> 0; // -456
```
## IIFE
There are various forms of Immediately-Invoked Function Expressions, and 2 mostly used froms are
```javascript
/* form 1 */
(function() {
    // code
})();

/* form 2 */
(function() {
    // code
}());
```
but if you don't care about the function return value, there are manay other forms
```javascript
/* form 3 */
!function() {
    // code
}();

/* form 4 */
~function() {
    // code
}();

/* form 5 */
void function() {
    // code
}();

/* and more ... */
```

## Miscs
#### undefined and void 0
`void 0` equals to `undefined`, so you may find source code uses `void 0` to detect whether whether a variable is defined or not.

#### !0 and !1
For code minimizing purpose, `!0` and `!1` are often be used to replace `true` and `false`

## License
MIT


text:
<title> University of Washington: Research in Mobile Ubiquitous Computing </title>

Mobile Computing at the University of Washington

Here's an overview of mobile computing
research here at UW.

 Projects

 Mobisaic

 An information system for a mobile and wireless computing environment

 Wit

 A system infrastructure for mobile handheld computing

 Task Graph Manager

 An application infrastructure for coping with resource variability.

 Papers

A survey paper describing the fundamental challenges in this field.

A Programming Methodology for Disconnected Operation

Distributed Transactions in a Mobile
Computing System

Contacts:

Prof. Brian Bershad

Prof. Gaetano Borriello

Marc E. Fiuczynski

George Forman

Prof. Hank Levy

Geoff Voelker

Terri Watson

Prof. John Zahorjan

<address> Last updated Mon 15 Jan 1996 </address>

<address>
forman@cs.washington.edu
</address>


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using GitReleaseManager.Core.Configuration;
using GitReleaseManager.Core.Model;
using GitReleaseManager.Core.Provider;
using GitReleaseManager.Core.ReleaseNotes;
using GitReleaseManager.Core.Templates;
using NSubstitute;
using NUnit.Framework;
using Serilog;
using Shouldly;
using ItemState = GitReleaseManager.Core.Model.ItemState;
using ItemStateFilter = GitReleaseManager.Core.Model.ItemStateFilter;
using Label = GitReleaseManager.Core.Model.Label;
using Milestone = GitReleaseManager.Core.Model.Milestone;
using NotFoundException = GitReleaseManager.Core.Exceptions.NotFoundException;
using Release = GitReleaseManager.Core.Model.Release;

namespace GitReleaseManager.Core.Tests
{
    public class VcsServiceTests
    {
        private const string OWNER = "owner";
        private const string REPOSITORY = "repository";
        private const int MILESTONE_NUMBER = 1;
        private const string MILESTONE_TITLE = "0.1.0";
        private const string TAG_NAME = "0.1.0";
        private const string RELEASE_NOTES = "Release Notes";
        private const string ASSET_CONTENT = "Asset Content";
        private const bool SKIP_PRERELEASES = false;

        private const string UNABLE_TO_FOUND_MILESTONE_MESSAGE = "Unable to find a {State} milestone with title '{Title}' on '{Owner}/{Repository}'";
        private const string UNABLE_TO_FOUND_RELEASE_MESSAGE = "Unable to find a release with tag '{TagName}' on '{Owner}/{Repository}'";

        private static readonly string _tempPath = Path.GetTempPath();
        private static readonly string _releaseNotesTemplate = Path.Combine(_tempPath, "ReleaseNotesTemplate.txt");
        private readonly List<string> _assets = new List<string>();
        private readonly List<string> _files = new List<string>();
        private readonly NotFoundException _notFoundException = new NotFoundException("NotFound");

        private IReleaseNotesExporter _releaseNotesExporter;
        private IReleaseNotesBuilder _releaseNotesBuilder;
        private ILogger _logger;
        private IVcsProvider _vcsProvider;
        private Config _configuration;
        private VcsService _vcsService;

        private string _releaseNotesFilePath;
        private string _releaseNotesTemplateFilePath;
        private string _releaseNotesEmptyTemplateFilePath;

        [OneTimeSetUp]
        public void OneTimeSetUp()
        {
            _releaseNotesFilePath = Path.Combine(_tempPath, "ReleaseNotes.txt");
            _releaseNotesTemplateFilePath = Path.Combine(_tempPath, "ReleaseNotesTemplate.txt");
            _releaseNotesEmptyTemplateFilePath = Path.Combine(_tempPath, "ReleaseNotesEmptyTemplate.txt");

            var fileContent = new Dictionary<string, string>
            {
                { _releaseNotesFilePath, RELEASE_NOTES },
                { _releaseNotesTemplateFilePath, _releaseNotesTemplate },
                { _releaseNotesEmptyTemplateFilePath, string.Empty },
            };

            for (int i = 0; i < 3; i++)
            {
                var fileName = $"Asset{i + 1}.txt";
                var filePath = Path.Combine(_tempPath, fileName);
                _assets.Add(filePath);

                fileContent.Add(filePath, ASSET_CONTENT);
            }

            _files.Add(_releaseNotesFilePath);
            _files.Add(_releaseNotesTemplateFilePath);
            _files.Add(_releaseNotesEmptyTemplateFilePath);
            _files.AddRange(_assets);

            foreach (var file in _files)
            {
                if (!File.Exists(file))
                {
                    File.WriteAllText(file, fileContent[file]);
                }
            }
        }

        [OneTimeTearDown]
        public void OneTimeTearDown()
        {
            foreach (var file in _files)
            {
                if (!File.Exists(file))
                {
                    File.Delete(file);
                }
            }
        }

        [SetUp]
        public void Setup()
        {
            _releaseNotesExporter = Substitute.For<IReleaseNotesExporter>();
            _releaseNotesBuilder = Substitute.For<IReleaseNotesBuilder>();
            _logger = Substitute.For<ILogger>();
            _vcsProvider = Substitute.For<IVcsProvider>();
            _configuration = new Config();
            _vcsService = new VcsService(_vcsProvider, _logger, _releaseNotesBuilder, _releaseNotesExporter, _configuration);
        }

        [Test]
        public async Task Should_Add_Assets()
        {
            var release = new Release { Assets = new List<ReleaseAsset>() };

            var assetsCount = _assets.Count;

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(release);

            await _vcsService.AddAssetsAsync(OWNER, REPOSITORY, TAG_NAME, _assets).ConfigureAwait(false);

            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
            await _vcsProvider.DidNotReceive().DeleteAssetAsync(OWNER, REPOSITORY, Arg.Any<int>()).ConfigureAwait(false);
            await _vcsProvider.Received(assetsCount).UploadAssetAsync(release, Arg.Any<ReleaseAssetUpload>()).ConfigureAwait(false);

            _logger.DidNotReceive().Warning(Arg.Any<string>(), Arg.Any<string>());
            _logger.Received(assetsCount).Verbose(Arg.Any<string>(), Arg.Any<string>(), TAG_NAME, OWNER, REPOSITORY);
            _logger.Received(assetsCount).Debug(Arg.Any<string>(), Arg.Any<ReleaseAssetUpload>());
        }

        [Test]
        public async Task Should_Add_Assets_With_Deleting_Existing_Assets()
        {
            var releaseAsset = new ReleaseAsset { Id = 1, Name = "Asset1.txt" };
            var release = new Release { Assets = new List<ReleaseAsset> { releaseAsset } };

            var releaseAssetsCount = release.Assets.Count;
            var assetsCount = _assets.Count;

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(release);

            await _vcsService.AddAssetsAsync(OWNER, REPOSITORY, TAG_NAME, _assets).ConfigureAwait(false);

            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
            await _vcsProvider.Received(releaseAssetsCount).DeleteAssetAsync(OWNER, REPOSITORY, releaseAsset.Id).ConfigureAwait(false);
            await _vcsProvider.Received(assetsCount).UploadAssetAsync(release, Arg.Any<ReleaseAssetUpload>()).ConfigureAwait(false);

            _logger.Received(releaseAssetsCount).Warning(Arg.Any<string>(), Arg.Any<string>());
            _logger.Received(assetsCount).Verbose(Arg.Any<string>(), Arg.Any<string>(), TAG_NAME, OWNER, REPOSITORY);
            _logger.Received(assetsCount).Debug(Arg.Any<string>(), Arg.Any<ReleaseAssetUpload>());
        }

        [Test]
        public async Task Should_Throw_Exception_On_Adding_Assets_When_Asset_File_Not_Exists()
        {
            var release = new Release();
            var assetFilePath = Path.Combine(_tempPath, "AssetNotExists.txt");

            _assets[0] = assetFilePath;

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(release);

            var ex = await Should.ThrowAsync<FileNotFoundException>(() => _vcsService.AddAssetsAsync(OWNER, REPOSITORY, TAG_NAME, _assets)).ConfigureAwait(false);
            ex.Message.ShouldContain(assetFilePath);

            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
            await _vcsProvider.DidNotReceive().DeleteAssetAsync(OWNER, REPOSITORY, Arg.Any<int>()).ConfigureAwait(false);
            await _vcsProvider.DidNotReceive().UploadAssetAsync(release, Arg.Any<ReleaseAssetUpload>()).ConfigureAwait(false);
        }

        [TestCaseSource(nameof(Assets_TestCases))]
        public async Task Should_Do_Nothing_On_Missing_Assets(IList<string> assets)
        {
            await _vcsService.AddAssetsAsync(OWNER, REPOSITORY, TAG_NAME, assets).ConfigureAwait(false);

            await _vcsProvider.DidNotReceive().GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
            await _vcsProvider.DidNotReceive().DeleteAssetAsync(OWNER, REPOSITORY, Arg.Any<int>()).ConfigureAwait(false);
            await _vcsProvider.DidNotReceive().UploadAssetAsync(Arg.Any<Release>(), Arg.Any<ReleaseAssetUpload>()).ConfigureAwait(false);
        }

        public static IEnumerable Assets_TestCases()
        {
            yield return new TestCaseData(null);
            yield return new TestCaseData(new List<string>());
        }

        [Test]
        public async Task Should_Create_Labels()
        {
            var labels = new List<Label>
            {
                new Label { Name = "Bug" },
                new Label { Name = "Feature" },
                new Label { Name = "Improvement" },
            };

            _vcsProvider.GetLabelsAsync(OWNER, REPOSITORY)
                .Returns(Task.FromResult((IEnumerable<Label>)labels));

            _vcsProvider.DeleteLabelAsync(OWNER, REPOSITORY, Arg.Any<string>())
                .Returns(Task.CompletedTask);

            _vcsProvider.CreateLabelAsync(OWNER, REPOSITORY, Arg.Any<Label>())
                .Returns(Task.CompletedTask);

            await _vcsService.CreateLabelsAsync(OWNER, REPOSITORY).ConfigureAwait(false);

            await _vcsProvider.Received(1).GetLabelsAsync(OWNER, REPOSITORY).ConfigureAwait(false);
            await _vcsProvider.Received(labels.Count).DeleteLabelAsync(OWNER, REPOSITORY, Arg.Any<string>()).ConfigureAwait(false);
            await _vcsProvider.Received(_configuration.Labels.Count).CreateLabelAsync(OWNER, REPOSITORY, Arg.Any<Label>()).ConfigureAwait(false);

            _logger.Received(1).Verbose(Arg.Any<string>(), OWNER, REPOSITORY);
            _logger.Received(2).Verbose(Arg.Any<string>());
            _logger.Received(2).Debug(Arg.Any<string>(), Arg.Any<IEnumerable<Label>>());
        }

        [Test]
        public async Task Should_Log_An_Warning_When_Labels_Not_Configured()
        {
            _configuration.Labels.Clear();

            await _vcsService.CreateLabelsAsync(OWNER, REPOSITORY).ConfigureAwait(false);

            _logger.Received(1).Warning(Arg.Any<string>());
        }

        [Test]
        public async Task Should_Close_Milestone()
        {
            var milestone = new Milestone { Number = MILESTONE_NUMBER };

            _vcsProvider.GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Open)
                .Returns(Task.FromResult(milestone));

            _vcsProvider.SetMilestoneStateAsync(OWNER, REPOSITORY, milestone.Number, ItemState.Closed)
                .Returns(Task.CompletedTask);

            await _vcsService.CloseMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false);

            await _vcsProvider.Received(1).GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Open).ConfigureAwait(false);
            await _vcsProvider.Received(1).SetMilestoneStateAsync(OWNER, REPOSITORY, milestone.Number, ItemState.Closed).ConfigureAwait(false);
        }

        [Test]
        public async Task Should_Log_An_Warning_On_Closing_When_Milestone_Cannot_Be_Found()
        {
            _vcsProvider.GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Open)
                .Returns(Task.FromException<Milestone>(_notFoundException));

            await _vcsService.CloseMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false);

            await _vcsProvider.Received(1).GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Open).ConfigureAwait(false);
            await _vcsProvider.DidNotReceive().SetMilestoneStateAsync(OWNER, REPOSITORY, MILESTONE_NUMBER, ItemState.Closed).ConfigureAwait(false);
            _logger.Received(1).Warning(UNABLE_TO_FOUND_MILESTONE_MESSAGE, "open", MILESTONE_TITLE, OWNER, REPOSITORY);
        }

        [Test]
        public async Task Should_Open_Milestone()
        {
            var milestone = new Milestone { Number = MILESTONE_NUMBER };

            _vcsProvider.GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Closed)
                .Returns(Task.FromResult(milestone));

            _vcsProvider.SetMilestoneStateAsync(OWNER, REPOSITORY, milestone.Number, ItemState.Open)
                .Returns(Task.CompletedTask);

            await _vcsService.OpenMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false);

            await _vcsProvider.Received(1).GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Closed).ConfigureAwait(false);
            await _vcsProvider.Received(1).SetMilestoneStateAsync(OWNER, REPOSITORY, milestone.Number, ItemState.Open).ConfigureAwait(false);
            _logger.Received(2).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY);
        }

        [Test]
        public async Task Should_Log_An_Warning_On_Opening_When_Milestone_Cannot_Be_Found()
        {
            _vcsProvider.GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Closed)
                .Returns(Task.FromException<Milestone>(_notFoundException));

            await _vcsService.OpenMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false);

            await _vcsProvider.Received(1).GetMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, ItemStateFilter.Closed).ConfigureAwait(false);
            await _vcsProvider.DidNotReceive().SetMilestoneStateAsync(OWNER, REPOSITORY, MILESTONE_NUMBER, ItemState.Open).ConfigureAwait(false);
            _logger.Received(1).Warning(UNABLE_TO_FOUND_MILESTONE_MESSAGE, "closed", MILESTONE_TITLE, OWNER, REPOSITORY);
        }

        [Test]
        public async Task Should_Create_Release_From_Milestone()
        {
            var release = new Release();

            _releaseNotesBuilder.BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME)
                .Returns(Task.FromResult(RELEASE_NOTES));

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE)
                .Returns(Task.FromResult<Release>(null));

            _vcsProvider.CreateReleaseAsync(OWNER, REPOSITORY, Arg.Any<Release>())
                .Returns(Task.FromResult(release));

            var result = await _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, null).ConfigureAwait(false);
            result.ShouldBeSameAs(release);

            await _releaseNotesBuilder.Received(1).BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME).ConfigureAwait(false);
            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false);
            await _vcsProvider.Received(1).CreateReleaseAsync(OWNER, REPOSITORY, Arg.Is<Release>(o =>
                o.Body == RELEASE_NOTES &&
                o.Name == MILESTONE_TITLE &&
                o.TagName == MILESTONE_TITLE)).ConfigureAwait(false);

            _logger.Received(1).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY);
            _logger.Received(1).Debug(Arg.Any<string>(), Arg.Any<Release>());
        }

        [Test]
        public async Task Should_Create_Release_From_Milestone_Using_Template_File()
        {
            var release = new Release();

            _releaseNotesBuilder.BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, _releaseNotesTemplate)
                .Returns(Task.FromResult(RELEASE_NOTES));

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE)
                .Returns(Task.FromResult<Release>(null));

            _vcsProvider.CreateReleaseAsync(OWNER, REPOSITORY, Arg.Any<Release>())
                .Returns(Task.FromResult(release));

            var result = await _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, _releaseNotesTemplateFilePath).ConfigureAwait(false);
            result.ShouldBeSameAs(release);

            await _releaseNotesBuilder.Received(1).BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, _releaseNotesTemplate).ConfigureAwait(false);
            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false);
            await _vcsProvider.Received(1).CreateReleaseAsync(OWNER, REPOSITORY, Arg.Is<Release>(o =>
                o.Body == RELEASE_NOTES &&
                o.Name == MILESTONE_TITLE &&
                o.TagName == MILESTONE_TITLE)).ConfigureAwait(false);

            _logger.Received(1).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY);
            _logger.Received(1).Debug(Arg.Any<string>(), Arg.Any<Release>());
        }

        [Test]
        [Ignore("This may be handled by the TemplateLoader instead")]
        public async Task Should_Throw_Exception_On_Creating_Release_With_Empty_Template()
        {
            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(Task.FromException<Release>(_notFoundException));

            await Should.ThrowAsync<ArgumentException>(() => _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, _releaseNotesEmptyTemplateFilePath)).ConfigureAwait(false);

            await _releaseNotesBuilder.DidNotReceive().BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, Arg.Any<string>()).ConfigureAwait(false);
        }

        [Test]
        [Ignore("This may be handled by the TemplateLoader instead")]
        public async Task Should_Throw_Exception_On_Creating_Release_With_Invalid_Template_File_Path()
        {
            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(Task.FromException<Release>(_notFoundException));

            var fileName = "InvalidReleaseNotesTemplate.txt";
            var invalidReleaseNotesTemplateFilePath = Path.Combine(_tempPath, fileName);

            var ex = await Should.ThrowAsync<FileNotFoundException>(() => _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, invalidReleaseNotesTemplateFilePath)).ConfigureAwait(false);
            ex.Message.ShouldContain(invalidReleaseNotesTemplateFilePath);
            ex.FileName.ShouldBe(fileName);

            await _releaseNotesBuilder.DidNotReceive().BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, Arg.Any<string>()).ConfigureAwait(false);
        }

        [TestCase(true, false)]
        [TestCase(true, true)]
        [TestCase(false, true)]
        public async Task Should_Update_Published_Release_On_Creating_Release_From_Milestone(bool isDraft, bool updatePublishedRelease)
        {
            var release = new Release { Draft = isDraft };

            _configuration.Create.AllowUpdateToPublishedRelease = updatePublishedRelease;

            _releaseNotesBuilder.BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME)
                .Returns(Task.FromResult(RELEASE_NOTES));

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE)
                .Returns(Task.FromResult(release));

            _vcsProvider.UpdateReleaseAsync(OWNER, REPOSITORY, release)
                .Returns(Task.FromResult(new Release()));

            var result = await _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, null).ConfigureAwait(false);
            result.ShouldBeSameAs(release);

            await _releaseNotesBuilder.Received(1).BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME).ConfigureAwait(false);
            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false);
            await _vcsProvider.Received(1).UpdateReleaseAsync(OWNER, REPOSITORY, release).ConfigureAwait(false);

            _logger.Received(1).Warning(Arg.Any<string>(), MILESTONE_TITLE);
            _logger.Received(1).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY);
            _logger.Received(1).Debug(Arg.Any<string>(), release);
        }

        [Test]
        public async Task Should_Throw_Exception_While_Updating_Published_Release_On_Creating_Release_From_Milestone()
        {
            var release = new Release { Draft = false };

            _configuration.Create.AllowUpdateToPublishedRelease = false;

            _releaseNotesBuilder.BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME)
                .Returns(Task.FromResult(RELEASE_NOTES));

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE)
                .Returns(Task.FromResult(release));

            var ex = await Should.ThrowAsync<InvalidOperationException>(() => _vcsService.CreateReleaseFromMilestoneAsync(OWNER, REPOSITORY, MILESTONE_TITLE, MILESTONE_TITLE, null, null, false, null)).ConfigureAwait(false);
            ex.Message.ShouldBe($"Release with tag '{MILESTONE_TITLE}' not in draft state, so not updating");

            await _releaseNotesBuilder.Received(1).BuildReleaseNotes(OWNER, REPOSITORY, MILESTONE_TITLE, ReleaseTemplates.DEFAULT_NAME).ConfigureAwait(false);
            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false);
        }

        [Test]
        public async Task Should_Create_Release_From_InputFile()
        {
            var release = new Release();

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE)
                .Returns(Task.FromResult<Release>(null));

            _vcsProvider.CreateReleaseAsync(OWNER, REPOSITORY, Arg.Any<Release>())
                .Returns(Task.FromResult(release));

            var result = await _vcsService.CreateReleaseFromInputFileAsync(OWNER, REPOSITORY, MILESTONE_TITLE, _releaseNotesFilePath, null, null, false).ConfigureAwait(false);
            result.ShouldBeSameAs(release);

            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false);
            await _vcsProvider.Received(1).CreateReleaseAsync(OWNER, REPOSITORY, Arg.Is<Release>(o =>
                o.Body == RELEASE_NOTES &&
                o.Name == MILESTONE_TITLE &&
                o.TagName == MILESTONE_TITLE)).ConfigureAwait(false);

            _logger.Received(1).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY);
            _logger.Received(1).Debug(Arg.Any<string>(), Arg.Any<Release>());
        }

        [TestCase(true, false)]
        [TestCase(true, true)]
        [TestCase(false, true)]
        public async Task Should_Update_Published_Release_On_Creating_Release_From_InputFile(bool isDraft, bool updatePublishedRelease)
        {
            var release = new Release { Draft = isDraft };

            _configuration.Create.AllowUpdateToPublishedRelease = updatePublishedRelease;

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE)
                .Returns(Task.FromResult(release));

            _vcsProvider.UpdateReleaseAsync(OWNER, REPOSITORY, release)
                .Returns(Task.FromResult(new Release()));

            var result = await _vcsService.CreateReleaseFromInputFileAsync(OWNER, REPOSITORY, MILESTONE_TITLE, _releaseNotesFilePath, null, null, false).ConfigureAwait(false);
            result.ShouldBeSameAs(release);

            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false);
            await _vcsProvider.Received(1).UpdateReleaseAsync(OWNER, REPOSITORY, release).ConfigureAwait(false);

            _logger.Received(1).Warning(Arg.Any<string>(), MILESTONE_TITLE);
            _logger.Received(1).Verbose(Arg.Any<string>(), MILESTONE_TITLE, OWNER, REPOSITORY);
            _logger.Received(1).Debug(Arg.Any<string>(), release);
        }

        [Test]
        public async Task Should_Throw_Exception_While_Updating_Published_Release_On_Creating_Release_From_InputFile()
        {
            var release = new Release { Draft = false };

            _configuration.Create.AllowUpdateToPublishedRelease = false;

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE)
                .Returns(Task.FromResult(release));

            var ex = await Should.ThrowAsync<InvalidOperationException>(() => _vcsService.CreateReleaseFromInputFileAsync(OWNER, REPOSITORY, MILESTONE_TITLE, _releaseNotesFilePath, null, null, false)).ConfigureAwait(false);
            ex.Message.ShouldBe($"Release with tag '{MILESTONE_TITLE}' not in draft state, so not updating");

            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, MILESTONE_TITLE).ConfigureAwait(false);
        }

        [Test]
        public async Task Should_Throw_Exception_Creating_Release_From_InputFile()
        {
            var fileName = "NonExistingReleaseNotes.txt";
            var filePath = Path.Combine(Path.GetTempPath(), fileName);

            var ex = await Should.ThrowAsync<FileNotFoundException>(() => _vcsService.CreateReleaseFromInputFileAsync(OWNER, REPOSITORY, MILESTONE_TITLE, filePath, null, null, false)).ConfigureAwait(false);
            ex.Message.ShouldBe("Unable to locate input file.");
            ex.FileName.ShouldBe(fileName);
        }

        [Test]
        public async Task Should_Delete_Draft_Release()
        {
            var release = new Release
            {
                Id = 1,
                Draft = true,
            };

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(Task.FromResult(release));

            _vcsProvider.DeleteReleaseAsync(OWNER, REPOSITORY, release.Id)
                .Returns(Task.CompletedTask);

            await _vcsService.DiscardReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);

            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
            await _vcsProvider.Received(1).DeleteReleaseAsync(OWNER, REPOSITORY, release.Id).ConfigureAwait(false);
        }

        [Test]
        public async Task Should_Not_Delete_Published_Release()
        {
            var release = new Release { Id = 1 };

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(Task.FromResult(release));

            await _vcsService.DiscardReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);

            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
            await _vcsProvider.DidNotReceive().DeleteReleaseAsync(OWNER, REPOSITORY, release.Id).ConfigureAwait(false);
            _logger.Received(1).Warning(Arg.Any<string>(), TAG_NAME);
        }

        [Test]
        public async Task Should_Log_An_Warning_On_Deleting_Release_For_Non_Existing_Tag()
        {
            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(Task.FromException<Release>(_notFoundException));

            await _vcsService.DiscardReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);

            await _vcsProvider.Received().GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
            await _vcsProvider.DidNotReceiveWithAnyArgs().DeleteReleaseAsync(OWNER, REPOSITORY, default).ConfigureAwait(false);
            _logger.Received(1).Warning(UNABLE_TO_FOUND_RELEASE_MESSAGE, TAG_NAME, OWNER, REPOSITORY);
        }

        [Test]
        public async Task Should_Publish_Release()
        {
            var release = new Release { Id = 1 };

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(Task.FromResult(release));

            _vcsProvider.PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME, release.Id)
                .Returns(Task.CompletedTask);

            await _vcsService.PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);

            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
            await _vcsProvider.Received(1).PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME, release.Id).ConfigureAwait(false);
            _logger.Received(1).Verbose(Arg.Any<string>(), TAG_NAME, OWNER, REPOSITORY);
            _logger.Received(1).Debug(Arg.Any<string>(), Arg.Any<Release>());
        }

        [Test]
        public async Task Should_Log_An_Warning_On_Publishing_Release_For_Non_Existing_Tag()
        {
            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(Task.FromException<Release>(_notFoundException));

            await _vcsService.PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);

            await _vcsProvider.Received().GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
            await _vcsProvider.DidNotReceiveWithAnyArgs().PublishReleaseAsync(OWNER, REPOSITORY, TAG_NAME, default).ConfigureAwait(false);
            _logger.Received(1).Warning(Arg.Any<string>(), TAG_NAME, OWNER, REPOSITORY);
        }

        [Test]
        public async Task Should_Get_Release_Notes()
        {
            var releases = Enumerable.Empty<Release>();
            var releaseNotes = "Release Notes";

            _vcsProvider.GetReleasesAsync(OWNER, REPOSITORY, SKIP_PRERELEASES)
                .Returns(Task.FromResult(releases));

            _releaseNotesExporter.ExportReleaseNotes(Arg.Any<IEnumerable<Release>>())
                .Returns(releaseNotes);

            var result = await _vcsService.ExportReleasesAsync(OWNER, REPOSITORY, null, SKIP_PRERELEASES).ConfigureAwait(false);
            result.ShouldBeSameAs(releaseNotes);

            await _vcsProvider.DidNotReceive().GetReleaseAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<string>()).ConfigureAwait(false);
            await _vcsProvider.Received(1).GetReleasesAsync(OWNER, REPOSITORY, SKIP_PRERELEASES).ConfigureAwait(false);
            _logger.Received(1).Verbose(Arg.Any<string>(), OWNER, REPOSITORY);
            _releaseNotesExporter.Received(1).ExportReleaseNotes(Arg.Any<IEnumerable<Release>>());
        }

        [Test]
        public async Task Should_Get_Release_Notes_For_Tag()
        {
            var release = new Release();

            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(Task.FromResult(release));

            _releaseNotesExporter.ExportReleaseNotes(Arg.Any<IEnumerable<Release>>())
                .Returns(RELEASE_NOTES);

            var result = await _vcsService.ExportReleasesAsync(OWNER, REPOSITORY, TAG_NAME, SKIP_PRERELEASES).ConfigureAwait(false);
            result.ShouldBeSameAs(RELEASE_NOTES);

            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
            await _vcsProvider.DidNotReceive().GetReleasesAsync(Arg.Any<string>(), Arg.Any<string>(), Arg.Any<bool>()).ConfigureAwait(false);
            _logger.Received(1).Verbose(Arg.Any<string>(), OWNER, REPOSITORY, TAG_NAME);
            _releaseNotesExporter.Received(1).ExportReleaseNotes(Arg.Any<IEnumerable<Release>>());
        }

        [Test]
        public async Task Should_Get_Default_Release_Notes_For_Non_Existent_Tag()
        {
            _vcsProvider.GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME)
                .Returns(Task.FromException<Release>(_notFoundException));

            _releaseNotesExporter.ExportReleaseNotes(Arg.Any<IEnumerable<Release>>())
                .Returns(RELEASE_NOTES);

            var result = await _vcsService.ExportReleasesAsync(OWNER, REPOSITORY, TAG_NAME, SKIP_PRERELEASES).ConfigureAwait(false);
            result.ShouldBeSameAs(RELEASE_NOTES);

            await _vcsProvider.Received(1).GetReleaseAsync(OWNER, REPOSITORY, TAG_NAME).ConfigureAwait(false);
            _logger.Received(1).Warning(UNABLE_TO_FOUND_RELEASE_MESSAGE, TAG_NAME, OWNER, REPOSITORY);
            _releaseNotesExporter.Received(1).ExportReleaseNotes(Arg.Any<IEnumerable<Release>>());
        }
    }
}


text:
using System;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Forms;
using OpenLiveWriter.Api;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.ApplicationFramework.Skinning;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.CoreServices.UI;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;

namespace OpenLiveWriter.PostEditor.Tagging
{
    public class TagSmartContentEditor : SmartContentEditor
    {
        public TagSmartContentEditor(IProperties options, TagContentSource.CurrentBlogId getCurrentBlogId) : this()
        {
            _options = options;
            _getCurrentBlogId = getCurrentBlogId;
        }

        public TagSmartContentEditor()
        {
            InitializeComponent();

            this.header.HeaderText = Res.Get(StringId.Options);
            sidebarHeader.HeaderText = Res.Get(StringId.Tags);
            sidebarHeader.LinkText = "";
            sidebarHeader.LinkUrl = "";

            tagEditor.Changed += new EventHandler(TagEditor_Changed);
            tagEditor.SuppressMnemonics();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            tagEditor.NaturalizeLayout();
        }

        private TagContext _context;
        private SectionHeaderControl header;
        private IProperties _options;
        private SidebarHeaderControl sidebarHeader;
        private TagContentSource.CurrentBlogId _getCurrentBlogId;
        private string _providerName = string.Empty;

        private void InitializeComponent()
        {
            this.header = new OpenLiveWriter.ApplicationFramework.SectionHeaderControl();
            this.sidebarHeader = new OpenLiveWriter.ApplicationFramework.SidebarHeaderControl();
            this.tagEditor = new OpenLiveWriter.PostEditor.Tagging.TagEditor();
            this.SuspendLayout();
            //
            // header
            //
            this.header.AccessibleName = "Options";
            this.header.AccessibleRole = System.Windows.Forms.AccessibleRole.Grouping;
            this.header.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.header.HeaderText = "Options";
            this.header.Location = new System.Drawing.Point(6, 88);
            this.header.Name = "header";
            this.header.Size = new System.Drawing.Size(184, 14);
            this.header.TabIndex = 4;
            this.header.TabStop = false;
            //
            // sidebarHeader
            //
            this.sidebarHeader.AccessibleName = "SidebarHeader";
            this.sidebarHeader.Location = new System.Drawing.Point(10, 2);
            this.sidebarHeader.Name = "sidebarHeader";
            this.sidebarHeader.Size = new System.Drawing.Size(184, 89);
            this.sidebarHeader.TabIndex = 5;
            this.sidebarHeader.TabStop = false;
            //
            // tagEditor
            //
            this.tagEditor.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.tagEditor.Location = new System.Drawing.Point(10, 112);
            this.tagEditor.Name = "tagEditor";
            this.tagEditor.Size = new System.Drawing.Size(184, 160);
            this.tagEditor.TabIndex = 0;
            this.tagEditor.TagProvider = null;
            this.tagEditor.Tags = new string[0];
            //
            // TagSmartContentEditor
            //
            this.Controls.Add(this.tagEditor);
            this.Controls.Add(this.header);
            this.Controls.Add(this.sidebarHeader);
            this.Name = "TagSmartContentEditor";
            this.ResumeLayout(false);

        }

        private TagEditor tagEditor;

        protected override void OnVisibleChanged(EventArgs e)
        {
            if (!Visible)
                _context.AddTagsToHistory(tagEditor.Tags);
            base.OnVisibleChanged(e);
            LayoutHelper.FitControlsBelow(0, sidebarHeader);
        }

        protected override void OnPaintBackground(PaintEventArgs pevent)
        {
            VirtualTransparency.VirtualPaint(this, pevent);
        }

        private void TagEditor_Changed(object sender, EventArgs e)
        {
            _context.Tags = tagEditor.Tags;
            _context.CurrentProvider = tagEditor.TagProvider;

            _providerName = tagEditor.TagProvider.Name;
            if (_providerName != null)
                sidebarHeader.LinkText = _providerName;
            Invalidate();
            OnContentEdited();
            RefreshLayout();

        }

        private void RefreshLayout()
        {
            sidebarHeader.RefreshLayout();
            LayoutHelper.FitControlsBelow(0, sidebarHeader);
        }

        public override ISmartContent SelectedContent
        {
            get { return base.SelectedContent; }
            set
            {
                tagEditor.Changed -= new EventHandler(TagEditor_Changed);
                try
                {
                    base.SelectedContent = value;
                    _context = new TagContext(value, _options, _getCurrentBlogId());
                    tagEditor.SetTagProviders(_context);
                    tagEditor.Tags = _context.Tags;
                    tagEditor.PreviouslyUsedTags = _context.PreviouslyUsedTags;
                    tagEditor.TagProvider = _context.CurrentProvider;
                    _providerName = _context.CurrentProvider.Name;
                    if (_providerName != null)
                        sidebarHeader.LinkText = _providerName;
                    Invalidate();
                    RefreshLayout();
                }
                finally
                {
                    tagEditor.Changed += new EventHandler(TagEditor_Changed);
                }
            }
        }
    }
}


text:
package org.apache.hadoop.yarn.server.resourcemanager.scheduler.policy;

import java.util.*;

import org.apache.hadoop.yarn.api.records.Priority;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.util.resource.Resources;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.ResourceUsage;
import org.apache.hadoop.yarn.nodelabels.CommonNodeLabelsManager;

public class MockSchedulableEntity implements SchedulableEntity {

  private String id;
  private long serial = 0;
  private Priority priority;
  private boolean isRecovering;

  public MockSchedulableEntity() { }

  public MockSchedulableEntity(long serial, int priority,
      boolean isRecovering) {
    this.serial = serial;
    this.priority = Priority.newInstance(priority);
    this.isRecovering = isRecovering;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getId() {
    return id;
  }

  public void setSerial(long serial) {
    this.serial = serial;
  }

  public long getSerial() {
    return serial;
  }

  public void setUsed(Resource value) {
    schedulingResourceUsage.setUsed(CommonNodeLabelsManager.ANY, value);
  }

  public void setPending(Resource value) {
    schedulingResourceUsage.setPending(CommonNodeLabelsManager.ANY, value);
  }

  private ResourceUsage schedulingResourceUsage = new ResourceUsage();

  @Override
  public ResourceUsage getSchedulingResourceUsage() {
    return schedulingResourceUsage;
  }

  @Override
  public int compareInputOrderTo(SchedulableEntity other) {
    if (other instanceof MockSchedulableEntity) {
      MockSchedulableEntity r2 = (MockSchedulableEntity) other;
      int res = (int) Math.signum(getSerial() - r2.getSerial());
      return res;
    }
    return 1;//let other types go before this, if any
  }

  @Override
  public Priority getPriority() {
    return priority;
  }

  public void setApplicationPriority(Priority priority) {
    this.priority = priority;
  }

  @Override
  public boolean isRecovering() {
    return isRecovering;
  }

  protected void setRecovering(boolean entityRecovering) {
    this.isRecovering = entityRecovering;
  }
}


text:
CKEDITOR.addTemplates("default",{imagesPath:CKEDITOR.getUrl("//will.illinois.edu/themes/site_themes/will2.1/plugins/wygwam-content-templates/"),
 	 	templates:[{
 	 		title:"Image on the left with caption",
 	 		image:"captioned-image-left.gif",
 	 		description:"Add an image on the left with a caption below it.",
 	 		html:'

Replace this text with your caption

Photo Credit:

'},
 	 		{
 	 		title:"Image on the right with caption",
 	 		image:"captioned-image-right.gif",
 	 		description:"Add an image on the right with a caption below it.",
 	 		html:'

Replace this text with your caption

Photo Credit:

'},
 	 		{
 	 		title:"Full-width with caption",
 	 		image:"captioned-image-full.png",
 	 		description:"Add a full-sized image (1200px wide) with a caption below it.",
 	 		html:'

Replace this text with your caption

Photo Credit:

'},
 	 		{
 	 		title:"Pullquote on Left",
 	 		image:"",
 	 		description:"",
 	 		html:'

Maybe replace this with something more interesting than this sentence?Wise Man

'},
 	 		{
 	 		title:"Pullquote on Right",
 	 		image:"",
 	 		description:"",
 	 		html:'

Maybe replace this with something more interesting than this sentence?Wise Man

'}
 	 		]});


text:
require 'application_system_test_case'

# Tests around line selection behavior
class SelectLineTest < ApplicationSystemTestCase
  before do
    @user = create :user
    log_in @user
  end

  describe 'line selection process' do
    it 'should redirect to line selection page on login' do
      assert_equal current_path, new_line_path
      assert has_content? 'DC'
      assert has_content? 'MD'
      assert has_content? 'VA'
      assert has_button? 'Start'
    end

    it 'should redirect to the main dashboard after line set' do
      choose 'DC'
      click_button 'Start'
      assert_equal current_path, authenticated_root_path
      assert has_content? 'Your current line: DC'
    end
  end

  # This is handled in `lines_controller_test` rather than here,
  # because setting env vars in integration tests suuuuucks. -CF
  # describe 'line redirect on single line' do
  #   Object.stub_const(:LINES, ['DC']) do
  #     it 'should redirect to the dashboard' do
  #       assert_equal current_path, authenticated_root_path
  #     end
  #   end
  # end

  describe 'redirection conditions' do
    before { @patient = create :patient }
    it 'should redirect from dashboard if no line is set' do
      visit edit_patient_path(@patient) # no redirect
      assert_equal current_path, edit_patient_path(@patient)
      visit authenticated_root_path # back to dashboard
      assert_equal current_path, new_line_path
    end
  end
end


text:
package scala.slick.test.ql.ql

import org.junit.Test
import org.junit.Assert._
import scala.slick.ql._
import scala.slick.driver.AccessDriver
import scala.slick.driver.{BasicTable => Table}
import scala.slick.session.Database.threadLocalSession
import scala.slick.testutil._
import scala.slick.testutil.TestDB._

object DataTypeTest extends DBTestObject(H2Mem, SQLiteMem, HsqldbMem, MySQL, DerbyMem, Postgres, MSAccess, SQLServer)

class DataTypeTest(tdb: TestDB) extends DBTest(tdb) {
  import tdb.driver.Implicit._

  @Test def testByteArray() {
    object T extends Table[(Int, Array[Byte])]("test") {
      def id = column[Int]("id")
      def data = column[Array[Byte]]("data")
      def * = id ~ data
    }

    db withSession {
      T.ddl.createStatements foreach println
      T.ddl.create;
      T insert (1, Array[Byte](1,2,3))
      T insert (2, Array[Byte](4,5))
      assertEquals(Set((1,"123"), (2,"45")), Query(T).list.map{ case (id, data) => (id, data.mkString) }.toSet)
    }
  }

  @Test def testNumeric() = db withSession {
    object T extends Table[(Int, Int, Long, Short, Byte)]("test") {
      def id = column[Int]("id")
      def intData = column[Int]("int_data")
      def longData = column[Long]("long_data")
      def shortData = column[Short]("short_data")
      def byteData = column[Byte]("byte_data")
      def * = id ~ intData ~ longData ~ shortData ~ byteData
    }

    T.ddl.createStatements foreach println
    T.ddl.create;

    def test(data: List[(Int, Int, Long, Short, Byte)]) {
      T.insertAll(data: _*)
      val q = T.sortBy(_.id)
      assertEquals(data, q.list)
      Query(T).delete
    }

    test(List(
      (2, -1,          -1L,           -1: Short,      -1: Byte),
      (3, 0,            0L,            0: Short,       0: Byte),
      (4, 1,            1L,            1: Short,       1: Byte)
    ))

    test(List(
      (1, Int.MinValue, 0L, Short.MinValue, Byte.MinValue),
      (5, Int.MaxValue, 0L, Short.MaxValue, Byte.MaxValue)
    ))

    if(tdb.driver != AccessDriver) { // No proper LONG type support in Access via JDBC
      test(List(
        (1, 0, Long.MinValue, 0, 0),
        (5, 0, Long.MaxValue, 0, 0)
      ))
    }
  }
}


text:
void advance_state ( int k );
bool antithetic_get ( );
void antithetic_memory ( int i, bool &value );
void antithetic_set ( bool value );
void cg_get ( int g, int &cg1, int &cg2 );
void cg_memory ( int i, int g, int &cg1, int &cg2 );
void cg_set ( int g, int cg1, int cg2 );
int cgn_get ( );
void cgn_memory ( int i, int &g );
void cgn_set ( int g );
void get_state ( int &cg1, int &cg2 );
int i4_uni ( );
void ig_get ( int g, int &ig1, int &ig2 );
void ig_memory ( int i, int g, int &ig1, int &ig2 );
void ig_set ( int g, int ig1, int ig2 );
void init_generator ( int t );
void initialize ( );
bool initialized_get ( );
void initialized_memory ( int i, bool &initialized );
void initialized_set ( );
void lg_get ( int g, int &lg1, int &lg2 );
void lg_memory ( int i, int g, int &lg1, int &lg2 );
void lg_set ( int g, int lg1, int lg2 );
int multmod ( int a, int s, int m );
float r4_uni_01 ( );
double r8_uni_01 ( );
void set_initial_seed ( int ig1, int ig2 );
void set_seed (  int cg1, int cg2 );
#if !defined(TIMESTAMP)
#define TIMESTAMP
void timestamp ( );
#endif


text:
'use strict'

const fs = require('fs')
const del = require('del')
const tap = require('tap')
const Api = require('../../api')

const parent = require('path').basename(__filename, '.js')
const helper = require('../helper').get(parent)
const assertNoErrors = helper.assertNoErrors.bind(helper)
const assertTypeDetails = helper.assertTypeDetails.bind(helper)

const versionFixture = '9.7.999'
let shouldDeleteFile = false
let expectedVersion

tap.beforeEach(() => {
  if (expectedVersion) {
    // console.error('!!!!!!!!! ALREADY READ PACKAGE.JSON, SKIPPING')
    return Promise.resolve()
  }
  return new Promise((resolve, reject) => {
    fs.readFile('package.json', 'utf8', (err, data) => {
      if (!err) {
        try {
          const pkg = JSON.parse(data)
          expectedVersion = pkg && pkg.version
        } catch (e) {}
      }
      if (expectedVersion) {
        // console.error('!!!!!!!!! READ EXISTING FILE:', expectedVersion)
        return resolve()
      }
      // need to write our own file
      fs.writeFile('package.json', JSON.stringify({ name: 'fake', version: versionFixture, private: true }), err => {
        if (err) return reject(err)
        shouldDeleteFile = true
        expectedVersion = versionFixture
        // console.error('########## WROTE CUSTOM PACKAGE.JSON FILE')
        resolve()
      })
    })
  })
})

tap.afterEach(async () => {
  if (!shouldDeleteFile) return Promise.resolve()
  // console.error('########## DELETING CUSTOM PACKAGE.JSON FILE')
  await del('package.json')
  shouldDeleteFile = false
  expectedVersion = undefined
})

tap.test('version > defaults', async t => {
  const api = Api.get().version()
  const typeObjects = api.initContext(true).types
  t.same(typeObjects[parent][0].aliases, ['version'])
  t.equal(typeObjects[parent][0].datatype, 'boolean')
  t.equal(typeObjects[parent][0].helpFlags, '--version')
  t.equal(typeObjects[parent][0].helpDesc, 'Show version number')
  t.equal(typeObjects[parent][0].helpHints, '[commands: version] [boolean]')
  t.equal(typeObjects[parent][0].helpGroup, 'Options:')
  t.equal(typeObjects[parent][0].isHidden, false)
  const result = await api.parse('--version')
  t.equal(result.code, 0)
  t.equal(result.output, expectedVersion || versionFixture)
  t.equal(result.errors.length, 0)
  t.equal(result.argv.version, true)
  assertTypeDetails(t, result, 1, ['version'], 'boolean', true, 'flag', [0], ['--version'])
})

tap.test('version > custom flags, desc, group, hints', t => {
  const typeObjects = Api.get().version('-V, --get-version', {
    desc: 'Get the program version and exit',
    group: 'Global Options:',
    hints: false
  }).initContext(true).types
  t.same(typeObjects[parent][0].aliases, ['V', 'get-version'])
  t.equal(typeObjects[parent][0].datatype, 'boolean')
  t.equal(typeObjects[parent][0].helpFlags, '-V, --get-version')
  t.equal(typeObjects[parent][0].helpDesc, 'Get the program version and exit')
  t.equal(typeObjects[parent][0].helpHints, false)
  t.equal(typeObjects[parent][0].helpGroup, 'Global Options:')
  t.equal(typeObjects[parent][0].isHidden, false)
  t.end()
})

tap.test('version > default implicit command', async t => {
  const api = Api.get().version()

  let result = await api.parse('version')
  t.equal(result.code, 0)
  t.equal(result.output, expectedVersion || versionFixture)
  t.equal(result.errors.length, 0)
  t.equal(result.argv.version, true)
  assertTypeDetails(t, result, 1, ['version'], 'boolean', true, 'positional', [0], ['version'])

  result = await api.parse('not version')
  assertNoErrors(t, result)
  t.equal(result.argv.version, false)
  t.same(result.argv._, ['not', 'version'])
  assertTypeDetails(t, result, 0, ['_'], 'array:string', ['not', 'version'], 'positional', [0, 1], ['not', 'version'])
  assertTypeDetails(t, result, 1, ['version'], 'boolean', false, 'default', [], [])
})

tap.test('version > custom implicit command via flags', async t => {
  const api = Api.get().version('-V | --get-version')

  let result = await api.parse('get-version')
  t.equal(result.code, 0)
  t.equal(result.output, expectedVersion || versionFixture)
  t.equal(result.errors.length, 0)
  t.equal(result.argv.V, true)
  t.equal(result.argv['get-version'], true)
  assertTypeDetails(t, result, 1, ['V', 'get-version'], 'boolean', true, 'positional', [0], ['get-version'])

  result = await api.parse('V')
  assertNoErrors(t, result)
  t.equal(result.argv.V, false)
  t.equal(result.argv['get-version'], false)
  t.same(result.argv._, ['V'])
  assertTypeDetails(t, result, 0, ['_'], 'array:string', ['V'], 'positional', [0], ['V'])
  assertTypeDetails(t, result, 1, ['V', 'get-version'], 'boolean', false, 'default', [], [])
})

tap.test('version > disable implicit command', async t => {
  const result = await Api.get().version({ implicitCommand: false }).parse('version')
  assertNoErrors(t, result)
  t.equal(result.argv.version, false)
  t.same(result.argv._, ['version'])
  assertTypeDetails(t, result, 0, ['_'], 'array:string', ['version'], 'positional', [0], ['version'])
  assertTypeDetails(t, result, 1, ['version'], 'boolean', false, 'default', [], [])
})

tap.test('version > custom version string', async t => {
  const result = await Api.get().version('-v, --version', {
    version: '3.14159265359'
  }).parse('-v')
  t.equal(result.code, 0)
  t.equal(result.output, '3.14159265359')
  t.equal(result.errors.length, 0)
  t.equal(result.argv.v, true)
  t.equal(result.argv.version, true)
  assertTypeDetails(t, result, 1, ['v', 'version'], 'boolean', true, 'flag', [0], ['-v'])
})

tap.test('version > custom version function', async t => {
  const result = await Api.get().version('-v, --version', {
    version: () => '6.2831853071' // currently must be synchronous
  }).parse('-v')
  t.equal(result.code, 0)
  t.equal(result.output, '6.2831853071')
  t.equal(result.errors.length, 0)
  t.equal(result.argv.v, true)
  t.equal(result.argv.version, true)
  assertTypeDetails(t, result, 1, ['v', 'version'], 'boolean', true, 'flag', [0], ['-v'])
})