text:
package pe.chalk.watermarker;

import pe.chalk.watermarker.util.SystemUiHider;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;

public class MainActivity extends Activity {
    private SystemUiHider mSystemUiHider;
    private ImageView imageContent;

    private final Handler mHideHandler = new Handler();
    private final Runnable mHideRunnable = new Runnable(){ @Override public void run(){ MainActivity.this.mSystemUiHider.hide(); } };

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        this.setContentView(R.layout.activity_main);
        if(this.getActionBar() != null) this.getActionBar().hide();

        final View contentView = this.findViewById(R.id.fullscreen_content);
        final View controlsView = this.findViewById(R.id.fullscreen_content_controls);

        this.imageContent = (ImageView) this.findViewById(R.id.image_content);

        this.mSystemUiHider = SystemUiHider.getInstance(this, contentView, SystemUiHider.FLAG_HIDE_NAVIGATION);
        this.mSystemUiHider.setup();
        this.mSystemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
            private int mControlsHeight;
            private int mShortAnimTime;

            @Override
            @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
            public void onVisibilityChange(boolean visible) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR2) {
                    controlsView.setVisibility(visible ? View.VISIBLE : View.GONE);
                } else {
                    if (this.mControlsHeight == 0) this.mControlsHeight = controlsView.getHeight();
                    if (this.mShortAnimTime == 0)
                        this.mShortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

                    controlsView.animate().translationY(visible ? 0 : this.mControlsHeight).setDuration(this.mShortAnimTime);
                }

                if (visible) delayedHide(3000);
            }
        });

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MainActivity.this.mSystemUiHider.toggle();
            }
        });

        this.findViewById(R.id.dummy_button).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                MainActivity.this.delayedHide(3000);
                return false;
            }
        });

        final ImageView watermark = (ImageView) this.findViewById(R.id.watermark);
        ((SeekBar) this.findViewById(R.id.alpha_seek)).setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                watermark.setAlpha(progress / (seekBar.getMax() + 0f));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar){

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar){

            }
        });
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState){
        super.onPostCreate(savedInstanceState);
        this.delayedHide(100);
    }

    private void delayedHide(int delayMillis){
        this.mHideHandler.removeCallbacks(this.mHideRunnable);
        this.mHideHandler.postDelayed(this.mHideRunnable, delayMillis);
    }

    public void selectImage(View view){
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");

        this.startActivityForResult(intent, 19132);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 19132 && resultCode == Activity.RESULT_OK){
            if(data == null) return;

            try{
                this.imageContent.setImageURI(data.getData());
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    }
}


text:
external help file: Microsoft.Azure.Commands.Consumption.dll-Help.xml
Module Name: AzureRM.Consumption
online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.consumption/new-azurermconsumptionbudget
schema: 2.0.0
---

# New-AzureRmConsumptionBudget

## SYNOPSIS
Create a budget in either a subscription or a resource group.

## SYNTAX

### Subscription (Default)
```
New-AzureRmConsumptionBudget [-DefaultProfile <IAzureContextContainer>] -Name <String> -Amount <Decimal>
 -Category <String> -TimeGrain <String> -StartDate <DateTime> [-EndDate <DateTime>]
 [-ResourceGroupName <String>] [-MeterFilter <String[]>] [-ResourceFilter <String[]>]
 [-ResourceGroupFilter <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>]
```

### Notification
```
New-AzureRmConsumptionBudget [-DefaultProfile <IAzureContextContainer>] -Name <String> -Amount <Decimal>
 -Category <String> -TimeGrain <String> -StartDate <DateTime> [-EndDate <DateTime>]
 [-ResourceGroupName <String>] [-MeterFilter <String[]>] [-ResourceFilter <String[]>]
 [-ResourceGroupFilter <String[]>] -NotificationKey <String> [-NotificationEnabled]
 -NotificationThreshold <Decimal> -ContactEmail <String[]> [-ContactGroup <String[]>] [-ContactRole <String[]>]
 [-WhatIf] [-Confirm] [<CommonParameters>]
```

## DESCRIPTION
The New-AzureRmConsumptionBudget cmdlet creates a budget in either a subscription or a resource group.

## EXAMPLES

### Example 1: Create a cost budget with a budget name at subscription level
```powershell
PS C:\> New-AzureRmConsumptionBudget -Amount 60 -Name PSBudget -Category Cost -StartDate 2018-06-01 -EndDate 2018-11-01 -TimeGrain Monthly
Amount:  60
Category:  Cost
CurrentSpend:  null
Id:  subscriptions/1caaa5a3-2b66-438e-8ab4-bce37d518c5d/providers/Microsoft.Consumption/budgets/PSBudget
Name:  PSBudget
TimeGrain:  Monthly
TimePeriod:  EndDate:  11/1/2018 12:00:00 AM
             StartDate:  6/1/2018 12:00:00 AM
Type:  Microsoft.Consumption/budgets
```

### Example 2: Create a cost budget with a budget name at resource group level
```powershell
PS C:\> New-AzureRmConsumptionBudget -ResourceGroupName RGBudgets -Amount 60 -Name PSBudgetRG -Category Cost -StartDate 2018-06-01 -EndDate 2018-11-01 -TimeGrain Monthly
Amount:  60
Category:  Cost
CurrentSpend:  null
Id:  subscriptions/1caaa5a3-2b66-438e-8ab4-bce37d518c5d/resourceGroups/RGBudgets/providers/Microsoft.Consumption/budgets/PSBudgetRG
Name:  PSBudgetRG
TimeGrain:  Monthly
TimePeriod:  EndDate:  11/1/2018 12:00:00 AM
             StartDate:  6/1/2018 12:00:00 AM
Type:  Microsoft.Consumption/budgets
```

## PARAMETERS

### -Amount
Amount of a budget.

```yaml
Type: System.Decimal
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Category
Category of the budget can be cost or usage.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:
Accepted values: Cost, Usage

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ContactEmail
Email addresses to send the budget notification to when the threshold is exceeded.

```yaml
Type: System.String[]
Parameter Sets: Notification
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ContactGroup
Action groups to send the budget notification to when the threshold is exceeded.

```yaml
Type: System.String[]
Parameter Sets: Notification
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ContactRole
Contact roles to send the budget notification to when the threshold is exceeded.

```yaml
Type: System.String[]
Parameter Sets: Notification
Aliases:
Accepted values: Owner, Reader, Contributor

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -DefaultProfile
The credentials, account, tenant, and subscription used for communication with Azure.

```yaml
Type: Microsoft.Azure.Commands.Common.Authentication.Abstractions.IAzureContextContainer
Parameter Sets: (All)
Aliases: AzureRmContext, AzureCredential

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -EndDate
End date (YYYY-MM-DD in UTC) of time period of a budget.

```yaml
Type: System.Nullable`1[System.DateTime]
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -MeterFilter
Comma-separated list of meters to filter on.
Required if category is usage.

```yaml
Type: System.String[]
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Name
Name of a budget.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -NotificationEnabled
The notification is enabled or not.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: Notification
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -NotificationKey
Key of a notification associated with a budget, required to create a notification with notification enabled switch, notification threshold, contact emails, contact groups, or contact roles.

```yaml
Type: System.String
Parameter Sets: Notification
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -NotificationThreshold
Threshold value associated with a notification.
Notification is sent when the cost or usage exceeded the threshold.
It is always percent and has to be between 0 and 1000.

```yaml
Type: System.Nullable`1[System.Decimal]
Parameter Sets: Notification
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ResourceFilter
Comma-separated list of resource instances to filter on.

```yaml
Type: System.String[]
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ResourceGroupFilter
Comma-separated list of resource groups to filter on.

```yaml
Type: System.String[]
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -ResourceGroupName
Resource Group of a budget.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -StartDate
Start date (YYYY-MM-DD in UTC) of time period of a budget.
Not prior to current month for monthly time grain.
Not prior to three months for quarterly time grain.
Not prior to twelve months for yearly time grain.
Future start date not more than three months.

```yaml
Type: System.Nullable`1[System.DateTime]
Parameter Sets: (All)
Aliases:

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -TimeGrain
Time grain of the budget can be monthly, quarterly, or annually.

```yaml
Type: System.String
Parameter Sets: (All)
Aliases:
Accepted values: Monthly, Quarterly, Annually

Required: True
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -Confirm
Prompts you for confirmation before running the cmdlet.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.

```yaml
Type: System.Management.Automation.SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

### None

## OUTPUTS

### Microsoft.Azure.Commands.Consumption.Models.PSBudget

## NOTES

## RELATED LINKS

redpajama_set_name: RedPajamaGithub


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Hyménomyc. de France (Sceaux) 444 (1928)

#### Original name
Hydnum fragile Pers., 1801

### Remarks
null


text:
#ifndef _RAYSORT_H_
#define _RAYSORT_H_

#include <tbb/tbb.h>

#include <core/Common.h>
#include <core/RayUncompressed.h>

MSC_NAMESPACE_BEGIN

/**
 * @brief      Sorts rays according to a ray position and direction recursively and in parallel
 *
 * This will recursively sort rays according to the median split along the longest axis of a bounding
 * box. When the size reaches a minimum size it stops sorting rays according to position and starts
 * sorting according to direction to achieve maximum coherency.
 */
class RaySort
{
public:
  /**
   * @brief      Initialiser list for class
   */
  RaySort(
    size_t _begin,
    size_t _end,
    BoundingBox3f _limits,
    RayUncompressed* _output
    )
   : m_begin(_begin)
   , m_end(_end)
   , m_limits(_limits)
   , m_output(_output)
  {;}

  /**
   * @brief      Operator overloader to allow the class to act as a functor with tbb
   */
  void operator()() const;

private:
  size_t m_begin;
  size_t m_end;
  BoundingBox3f m_limits;
  RayUncompressed* m_output;
};

MSC_NAMESPACE_END

#endif


text:
package org.txazo.weixin.develop.media;

import java.io.Serializable;

/**
 * Media
 *
 * @author txazo
 * @email txazo1218@163.com
 * @since 05.06.2015
 */
public class Media implements Serializable {

    private static final long serialVersionUID = -6619063245708445972L;

    /** media_id有效时间(2天23小时50分钟) */
    private static final long MEDIA_ID_VALID_TIME = (3 * 24 * 60 - 10) * 60 * 1000;

    /** 媒体文件路径 */
    private String path;
    /** 媒体文件hash */
    private String hash;
    /** 媒体文件类型 */
    private String type;
    /** 媒体文件唯一标识 */
    private String media_id;
    /** 媒体文件上传时间戳 */
    private long created_at;

    public Media() {
    }

    public Media(String path, MediaType mediaType) {
        this.path = path;
        this.type = mediaType.getType();
    }

    public boolean isVaild() {
        return (System.currentTimeMillis() - created_at) <= MEDIA_ID_VALID_TIME;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getHash() {
        return hash;
    }

    public void setHash(String hash) {
        this.hash = hash;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getMedia_id() {
        return media_id;
    }

    public void setMedia_id(String media_id) {
        this.media_id = media_id;
    }

    public long getCreated_at() {
        return created_at;
    }

    public void setCreated_at(long created_at) {
        this.created_at = created_at;
    }

}


text:
using System.Collections.Generic;
using MSG.DomainLogic;
using MSG.DomainLogic.Entities;
using NUnit.Framework;

namespace MSG.UnitTests
{
    [TestFixture]
    class GetEventualPostfixedAdverbTests
    {
        private List<int> _defaults;

        [SetUp]
        public void SetUpDefaultNumbers()
        {
            _defaults = new List<int> {0, 17, 7, 2, 10, 23, 11, 3, 5, 12};
        }

        [TearDown]
        public void UndoRandomNumberSetting()
        {
            MoqUtil.UndoMockRandomNumber();
        }

        [Test]
        public void VerifyGoingForward()
        {
            _defaults.Add(1);
            MoqUtil.SetupRandMock(_defaults.ToArray());

            Sentence output = DomainFactory.Generator.GetSentences(1)[0];

            Assert.AreEqual("The partners diligently avoid gaps going forward.", output.Text);
        }

        [Test]
        public void VerifyBlankOutputForInvalidNumber()
        {
            _defaults.Add(222);
            MoqUtil.SetupRandMock(_defaults.ToArray());

            Sentence output = DomainFactory.Generator.GetSentences(1)[0];

            Assert.AreEqual("The partners diligently avoid gaps.", output.Text);
        }

        [Test]
        public void VerifyIndividualOutput()
        {
            _defaults.Add(33);
            MoqUtil.SetupRandMock(_defaults.ToArray());

            Sentence output = DomainFactory.Generator.GetSentences(1)[0];

            Assert.AreEqual("The partners diligently avoid gaps at the individual, team and organizational level.", output.Text);
        }

        [Test]
        public void VerifyRandomArticle()
        {
            _defaults.Add(10);
            _defaults.Add(2);
            _defaults.Add(74);
            _defaults.Add(6);
            _defaults.Add(3);
            _defaults.Add(8);
            MoqUtil.SetupRandMock(_defaults.ToArray());

            Sentence output = DomainFactory.Generator.GetSentences(1)[0];

            Assert.AreEqual("The partners diligently avoid gaps using unparallelled throughput increase.", output.Text);
        }

        [Test]
        public void VerifyRandomArticleAndThing()
        {
            _defaults.Add(12);
            _defaults.Add(2);
            _defaults.Add(74);
            _defaults.Add(6);
            _defaults.Add(3);
            _defaults.Add(8);
            MoqUtil.SetupRandMock(_defaults.ToArray());

            Sentence output = DomainFactory.Generator.GetSentences(1)[0];

            Assert.AreEqual("The partners diligently avoid gaps taking advantage of unparallelled throughput increase.", output.Text);
        }

        [Test]
        public void VerifyMatrix()
        {
            _defaults.Add(13);
            _defaults.Add(2);
            MoqUtil.SetupRandMock(_defaults.ToArray());

            Sentence output = DomainFactory.Generator.GetSentences(1)[0];

            Assert.AreEqual("The partners diligently avoid gaps within the organisation.", output.Text);
        }

        [Test]
        public void VerifyEventualPlural()
        {
            _defaults.Add(14);
            _defaults.Add(2);
            MoqUtil.SetupRandMock(_defaults.ToArray());

            Sentence output = DomainFactory.Generator.GetSentences(1)[0];

            Assert.AreEqual("The partners diligently avoid gaps across the organisations.", output.Text);
        }

        [Test]
        public void VerifyGrowth()
        {
            _defaults.Add(18);
            _defaults.Add(3);
            _defaults.Add(4);
            _defaults.Add(6);
            _defaults.Add(3);
            _defaults.Add(8);
            MoqUtil.SetupRandMock(_defaults.ToArray());

            Sentence output = DomainFactory.Generator.GetSentences(1)[0];

            Assert.AreEqual("The partners diligently avoid gaps as a consequence of upper single-digit efficiency gain.", output.Text);
        }

        [Test]
        public void VerifyPluralVerb()
        {
            _defaults.Add(19);
            _defaults.Add(3);
            _defaults.Add(4);
            _defaults.Add(6);
            _defaults.Add(3);
            _defaults.Add(8);
            _defaults.Add(2);
            _defaults.Add(7);
            _defaults.Add(5);
            MoqUtil.SetupRandMock(_defaults.ToArray());

            Sentence output = DomainFactory.Generator.GetSentences(1)[0];

            Assert.AreEqual("The partners diligently avoid gaps because the key, constructive organizing principles produce proven yield enhancement.", output.Text);
        }
    }
}


text:
import Layout from '../layout/page'
import Head from '../components/Head'
import fetchLayoutData from '../libs/fetchLayoutData'
import Button from '../components/Button'

const LANG = 'en'

const NotFoundPage = (props) => {
  const errorCode = '404'
  const pageName = 'Not Found'
  const pageDesc = "That page can't be found."
  return (
    <>

      <Layout { ...{ lang: LANG, ...props } }>

        <div className={
          `flex flex-col justify-center border p-8 opacity-20 hover:opacity-100 duration-200`
        }>

              {errorCode}

            <Button
              to='/'
              className='text-4xl'
              text={<>Back
To
Home</>}
            />

            {pageName}

      </Layout>
    </>
  )
}

export const getStaticProps = async () => {
  const ret_props = await fetchLayoutData({ lang: LANG })
  return { props: ret_props }
}

export default NotFoundPage


text:
require 'rails_helper'

RSpec.describe "users/index", type: :view do

end


text:
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 * vim: set ts=4 sw=4 et tw=99 ft=cpp:
 */

#include <stdlib.h>

#include "ejs-error.h"
#include "ejs-function.h"
#include "ejs-ops.h"
#include "ejs-runloop.h"
#include "ejs-timers.h"

ejsval _ejs_Timer EJSVAL_ALIGNMENT;
ejsval _ejs_Timer_prototype EJSVAL_ALIGNMENT;

ejsval _ejs_setTimeout EJSVAL_ALIGNMENT;
ejsval _ejs_setInterval EJSVAL_ALIGNMENT;

ejsval _ejs_clearTimeout EJSVAL_ALIGNMENT;
ejsval _ejs_clearInterval EJSVAL_ALIGNMENT;

typedef struct {
    EJSTimer *timer;

    ejsval callbackfn;
    ejsval *args;
    uint32_t argc;
} TimerTaskArg;

static TimerTaskArg*
create_task_arg (ejsval callbackfn, uint32_t argc, ejsval *args)
{
    TimerTaskArg *rv = malloc(sizeof(TimerTaskArg));
    rv->callbackfn = callbackfn;
    rv->argc = argc;
    rv->args = args;

    _ejs_gc_add_root(&rv->callbackfn);
    for (int i = 0; i < rv->argc; i++)
        _ejs_gc_add_root(&rv->args[i]);

    return rv;
}

static void
destroy_task_arg (TimerTaskArg *arg)
{
    _ejs_gc_remove_root(&arg->callbackfn);
    for (int i = 0; i < arg->argc; i++)
        _ejs_gc_remove_root(&arg->args[i]);

    if (arg->argc > 0)
        free(arg->args);

    free(arg);
}

static void
call_timeout_task (void* data)
{
    TimerTaskArg *arg = (TimerTaskArg*)data;
    ejsval undef_this = _ejs_undefined;
    _ejs_invoke_closure (arg->callbackfn, &undef_this, arg->argc, arg->args, _ejs_undefined);
}

static void
dtor_timeout_task (void *data)
{
    destroy_task_arg((TimerTaskArg*)data);
}

static EJS_NATIVE_FUNC(_ejs_clearTimer) {
    ejsval timer = _ejs_undefined;

    if (argc >= 1)
        timer = args[0];

    /* it looks passing the wrong value doesn't cause any effect/error */
    if (!EJSVAL_IS_TIMER(timer))
        return _ejs_undefined;

    EJSTimer *timerObj = EJSVAL_TO_TIMER(timer);
    if (timerObj->handle == NULL)
        return _ejs_undefined;

    _ejs_runloop_remove_task(timerObj->handle);
    timerObj->handle = NULL;

    return _ejs_undefined;
}

EJS_NATIVE_FUNC(_ejs_clearInterval_impl) {
    return _ejs_clearTimer (env, _this, argc, args, _ejs_undefined);
}

EJS_NATIVE_FUNC(_ejs_clearTimeout_impl) {
    return _ejs_clearTimer (env, _this, argc, args, _ejs_undefined);
}

static ejsval
create_timer_value(void *handle)
{
    EJSObject *timer = (EJSObject*)_ejs_gc_new (EJSTimer);
    _ejs_init_object (timer, _ejs_Timer_prototype, &_ejs_Timer_specops);

    ((EJSTimer*)timer)->handle = handle;

    return OBJECT_TO_EJSVAL(timer);
}

static ejsval
_ejs_setTimer(uint32_t argc, ejsval* args, EJSBool repeats) {
    ejsval callbackfn = _ejs_undefined;
    ejsval interval = _ejs_undefined;

    if (argc >= 1)
        callbackfn = args[0];

    if (argc >= 2)
        interval = args[1];

    if (!IsCallable(callbackfn))
        _ejs_throw_nativeerror_utf8 (EJS_TYPE_ERROR, "argument is not a function");

    uint32_t timer_argc = 0;
    if (argc > 2)
        timer_argc = argc - 2;

    ejsval *timer_args = NULL;
    if (timer_argc > 0)
        timer_args = malloc(sizeof(ejsval) * timer_argc);

    for (int i = 0; i < timer_argc; i++)
        timer_args[i] = args[i + 2];

    TimerTaskArg *taskArg = create_task_arg (callbackfn, timer_argc, timer_args);
    void *handle = _ejs_runloop_add_task_timeout (call_timeout_task, taskArg, dtor_timeout_task, ToLength(interval), repeats);

    return create_timer_value (handle);
}

static EJS_NATIVE_FUNC(_ejs_setTimeout_impl) {
    return _ejs_setTimer(argc, args, EJS_FALSE);
}

static EJS_NATIVE_FUNC(_ejs_setInterval_impl) {
    return _ejs_setTimer(argc, args, EJS_TRUE);
}

static EJS_NATIVE_FUNC(_ejs_Timer_impl) {
    EJS_NOT_IMPLEMENTED();
    //return _this;
}

void
_ejs_timers_init(ejsval global)
{
    _ejs_Timer = _ejs_function_new_without_proto (_ejs_null, _ejs_atom_empty, _ejs_Timer_impl);

    _ejs_gc_add_root (&_ejs_Timer_prototype);
    _ejs_Timer_prototype = _ejs_object_new (_ejs_null, &_ejs_Object_specops);
    _ejs_object_setprop (_ejs_Timer, _ejs_atom_prototype, _ejs_Timer_prototype);
    _ejs_object_define_value_property (_ejs_Timer_prototype, _ejs_atom_constructor, _ejs_Timer,
            EJS_PROP_NOT_ENUMERABLE | EJS_PROP_CONFIGURABLE | EJS_PROP_WRITABLE);
#define GLOBAL_METHOD(x) EJS_MACRO_START                                \
    _ejs_##x = _ejs_function_new_native (_ejs_null, _ejs_atom_##x, _ejs_##x##_impl); \
    _ejs_object_setprop (global, _ejs_atom_##x, _ejs_##x);         \
    EJS_MACRO_END

    GLOBAL_METHOD(clearInterval);
    GLOBAL_METHOD(clearTimeout);
    GLOBAL_METHOD(setInterval);
    GLOBAL_METHOD(setTimeout);
#undef GLOBAL_METHOD
}

static EJSObject*
_ejs_timer_specop_allocate()
{
    return (EJSObject*)_ejs_gc_new (EJSTimer);
}

EJS_DEFINE_CLASS(Timer,
                 OP_INHERIT, // [[GetPrototypeOf]]
                 OP_INHERIT, // [[SetPrototypeOf]]
                 OP_INHERIT, // [[IsExtensible]]
                 OP_INHERIT, // [[PreventExtensions]]
                 OP_INHERIT, // [[GetOwnProperty]]
                 OP_INHERIT, // [[DefineOwnProperty]]
                 OP_INHERIT, // [[HasProperty]]
                 OP_INHERIT, // [[Get]]
                 OP_INHERIT, // [[Set]]
                 OP_INHERIT, // [[Delete]]
                 OP_INHERIT, // [[Enumerate]]
                 OP_INHERIT, // [[OwnPropertyKeys]]
                 OP_INHERIT, // [[Call]]
                 OP_INHERIT, // [[Construct]]
                 _ejs_timer_specop_allocate,
                 OP_INHERIT, // [[Finalize]]
                 OP_INHERIT  // [[Scan]] XXX?
                 )


text:
interface ObjectConstructor {
    assign(target: any, ...sources: any[]): any;
}

if (typeof Object.assign != "function") {
    (() => {
        Object.assign = function (target) {
            "use strict";
            if (target === undefined || target === null) {
                throw new TypeError("Cannot convert undefined or null to object");
            }
            const output = Object(target);
            for (let index = 1; index < arguments.length; index++) {
                const source = arguments[index];
                if (source !== undefined && source !== null) {
                    for (let nextKey in source) {
                        if (source.hasOwnProperty(nextKey)) {
                            output[nextKey] = source[nextKey];
                        }
                    }
                }
            }
            return output;
        };
    })();
}


text:
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes       #-}
{-# LANGUAGE TemplateHaskell   #-}

module Dupes.FileHash (
    FileHash,
    toByteString,
    hashFile,
    nullHash,
    hashByteString,
    testGroup,
    ) where

import           Control.Exception
import           Control.Monad
import           Crypto.Hash                      as Hash
import qualified Data.ByteArray                   as ByteArray
import qualified Data.ByteString                  as B
import qualified Data.ByteString.Lazy             as L
import           Data.Either
import           Data.Maybe
import           Data.String.Interpolate
import           Database.SQLite.Simple.FromField
import           Database.SQLite.Simple.ToField
import           System.IO
import           System.IO.Temp
import           Test
import           Test.Tasty.HUnit
import           Test.Tasty.TH

newtype FileHash = FileHash (Digest SHA1)
  deriving (Show, Eq, Ord)

instance FromField FileHash where
  fromField field = fromByteString <$> fromField field
    where
      fromByteString :: B.ByteString -> FileHash
      fromByteString = FileHash . fromJust . digestFromByteString

instance ToField FileHash where
  toField = toField . toByteString

toByteString :: FileHash -> B.ByteString
toByteString (FileHash digest) = ByteArray.convert digest

hashFile :: FilePath -> IO (Either String FileHash)
hashFile path = (Right <$> fileHash) `catch` returnIOException
  where
    fileHash = withBinaryFile path ReadMode hashHandle
    hashHandle handle = (FileHash . hashlazy) <$!> L.hGetContents handle
    returnIOException :: IOException -> IO (Either String FileHash)
    returnIOException = return . Left . show

case_hashFile_empty_file_is_correct = withSystemTempFile $(tempNameTemplate) $ \path handle -> do
  hClose handle
  result <- hashFile path
  Right nullHash @=? result

nullHash :: FileHash
nullHash = hashByteString ""

hashByteString :: B.ByteString -> FileHash
hashByteString = FileHash . hash

case_hashFile_exclusively_locked_file_is_Left = withSystemTempFile $(tempNameTemplate) $ \path _ -> do
  result <- hashFile path
  assertBool [i|Expected result to be a Left but was #{show result}|] (isLeft result)

testGroup = $(testGroupGenerator)


text:
package net.dongliu.requests.executor;

import net.dongliu.commons.io.InputStreams;
import net.dongliu.requests.*;
import net.dongliu.requests.body.RequestBody;
import net.dongliu.requests.exception.RequestsException;
import net.dongliu.requests.exception.TooManyRedirectsException;
import net.dongliu.requests.utils.Cookies;
import net.dongliu.requests.utils.NopHostnameVerifier;
import net.dongliu.requests.utils.SSLSocketFactories;
import net.dongliu.requests.utils.URLUtils;
import org.checkerframework.checker.nullness.qual.Nullable;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static net.dongliu.requests.HttpHeaders.*;
import static net.dongliu.requests.StatusCodes.*;

/**
 * Execute http request with url connection
 *
 * @author Liu Dong
 */
class URLConnectionExecutor implements HttpExecutor {

    static {
        // we can modify Host, and other restricted headers
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        System.setProperty("http.keepAlive", "true");
        // default is 5
        System.setProperty("http.maxConnections", "100");
    }

    @Override
    public RawResponse proceed(Request request) {
        RawResponse response = doRequest(request);

        int statusCode = response.statusCode();
        if (!request.followRedirect() || !isRedirect(statusCode)) {
            return response;
        }

        // handle redirect
        response.discardBody();
        int redirectTimes = 0;
        final int maxRedirectTimes = request.maxRedirectCount();
        URL redirectUrl = request.url();
        while (redirectTimes++ < maxRedirectTimes) {
            String location = response.getHeader(NAME_LOCATION);
            if (location == null) {
                throw new RequestsException("Redirect location not found");
            }
            try {
                redirectUrl = new URL(redirectUrl, location);
            } catch (MalformedURLException e) {
                throw new RequestsException("Resolve redirect url error, location: " + location, e);
            }
            String method = request.method();
            RequestBody<?> body = request.body();
            if (statusCode == MOVED_PERMANENTLY || statusCode == FOUND || statusCode == SEE_OTHER) {
                // 301/302 change method to get, due to historical reason.
                method = Methods.GET;
                body = null;
            }

            RequestBuilder builder = request.toBuilder().method(method).url(redirectUrl)
                    .followRedirect(false).body(body);
            response = builder.send();
            if (!isRedirect(response.statusCode())) {
                return response;
            }
            response.discardBody();
        }
        throw new TooManyRedirectsException(maxRedirectTimes);
    }

    private static boolean isRedirect(int status) {
        return status == MULTIPLE_CHOICES || status == MOVED_PERMANENTLY || status == FOUND || status == SEE_OTHER
                || status == TEMPORARY_REDIRECT || status == PERMANENT_REDIRECT;
    }

    private RawResponse doRequest(Request request) {
        Charset charset = request.charset();
        URL url = URLUtils.joinUrl(request.url(), URLUtils.toStringParameters(request.params()), charset);
        @Nullable RequestBody<?> body = request.body();
        CookieJar cookieJar;
        if (request.sessionContext() != null) {
            cookieJar = request.sessionContext().cookieJar();
        } else {
            cookieJar = NopCookieJar.instance;
        }

        @Nullable Proxy proxy = request.proxy();
        if (proxy == null) {
            proxy = Proxy.NO_PROXY;
        }
        HttpURLConnection conn;
        try {
            conn = (HttpURLConnection) url.openConnection(proxy);
        } catch (IOException e) {
            throw new RequestsException(e);
        }

        // disable cache
        conn.setUseCaches(false);

        // deal with https
        if (conn instanceof HttpsURLConnection) {
            HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
            if (!request.verify()) {
                SSLSocketFactory ssf = SSLSocketFactories.getTrustAllSSLSocketFactory();
                httpsConn.setSSLSocketFactory(ssf);
                // do not verify host of certificate
                httpsConn.setHostnameVerifier(NopHostnameVerifier.getInstance());
            } else if (request.keyStore() != null) {
                SSLSocketFactory ssf = SSLSocketFactories.getCustomTrustSSLSocketFactory(request.keyStore());
                httpsConn.setSSLSocketFactory(ssf);
            }
        }

        try {
            conn.setRequestMethod(request.method());
        } catch (ProtocolException e) {
            throw new RequestsException(e);
        }
        conn.setReadTimeout(request.socksTimeout());
        conn.setConnectTimeout(request.connectTimeout());
        // Url connection did not deal with cookie when handle redirect. Disable it and handle it manually
        conn.setInstanceFollowRedirects(false);
        if (body != null) {
            conn.setDoOutput(true);
            String contentType = body.contentType();
            if (contentType != null) {
                if (body.includeCharset()) {
                    contentType += "; charset=" + request.charset().name().toLowerCase();
                }
                conn.setRequestProperty(NAME_CONTENT_TYPE, contentType);
            }
        }

        // headers
        if (!request.userAgent().isEmpty()) {
            conn.setRequestProperty(NAME_USER_AGENT, request.userAgent());
        }
        if (request.acceptCompress()) {
            conn.setRequestProperty(NAME_ACCEPT_ENCODING, "gzip, deflate");
        }

        if (request.basicAuth() != null) {
            conn.setRequestProperty(NAME_AUTHORIZATION, request.basicAuth().encode());
        }

        // set cookies
        Collection<Cookie> sessionCookies = cookieJar.getCookies(url);
        if (!request.cookies().isEmpty() || !sessionCookies.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, ?> entry : request.cookies()) {
                sb.append(entry.getKey()).append("=").append(String.valueOf(entry.getValue())).append("; ");
            }
            for (Cookie cookie : sessionCookies) {
                sb.append(cookie.name()).append("=").append(cookie.value()).append("; ");
            }
            if (sb.length() > 2) {
                sb.setLength(sb.length() - 2);
                String cookieStr = sb.toString();
                conn.setRequestProperty(NAME_COOKIE, cookieStr);
            }
        }

        // set user custom headers
        for (Map.Entry<String, ?> header : request.headers()) {
            conn.setRequestProperty(header.getKey(), String.valueOf(header.getValue()));
        }

        // disable keep alive
        if (!request.keepAlive()) {
            conn.setRequestProperty("Connection", "close");
        }

        try {
            conn.connect();
        } catch (IOException e) {
            throw new RequestsException(e);
        }

        try {
            // send body
            if (body != null) {
                sendBody(body, conn, charset);
            }
            return getResponse(url, conn, cookieJar, request.method());
        } catch (IOException e) {
            conn.disconnect();
            throw new RequestsException(e);
        } catch (Throwable e) {
            conn.disconnect();
            throw e;
        }
    }

    /**
     * Wrap response, deal with headers and cookies
     */
    private RawResponse getResponse(URL url, HttpURLConnection conn, CookieJar cookieJar, String method)
            throws IOException {
        // read result
        int status = conn.getResponseCode();
        String host = url.getHost().toLowerCase();

        String statusLine = null;
        // headers and cookies
        List<Header> headerList = new ArrayList<>();
        List<Cookie> cookies = new ArrayList<>();
        int index = 0;
        while (true) {
            String key = conn.getHeaderFieldKey(index);
            String value = conn.getHeaderField(index);
            if (value == null) {
                break;
            }
            index++;
            //status line
            if (key == null) {
                statusLine = value;
                continue;
            }
            headerList.add(new Header(key, value));
            if (key.equalsIgnoreCase(NAME_SET_COOKIE)) {
                Cookie c = Cookies.parseCookie(value, host, Cookies.calculatePath(url.getPath()));
                if (c != null) {
                    cookies.add(c);
                }
            }
        }
        Headers headers = new Headers(headerList);

        InputStream input;
        try {
            input = conn.getInputStream();
        } catch (IOException e) {
            input = conn.getErrorStream();
        }
        if (input == null) {
            input = InputStreams.empty();
        }

        // update session
        cookieJar.storeCookies(cookies);
        return new RawResponse(method, url.toExternalForm(), status, statusLine == null ? "" : statusLine,
                cookies, headers, input, conn);
    }

    private void sendBody(RequestBody body, HttpURLConnection conn, Charset requestCharset) {
        try (OutputStream os = conn.getOutputStream()) {
            body.writeBody(os, requestCharset);
        } catch (IOException e) {
            throw new RequestsException(e);
        }
    }
}


text:
'use strict';

const assert = require('../../utils/assert.js');
const preq   = require('preq');
const Server = require('../../utils/server.js');

function generateTests(server, options) {
    it('should return valid revision info', () => {
        return preq.get({ uri: `${server.config.bucketURL(options.domain)}/title/${encodeURIComponent(options.pageName)}` })
        .then((res) => {
            assert.deepEqual(res.status, 200);
            assert.deepEqual(res.body.items.length, 1);
            assert.deepEqual(res.body.items[0].rev, options.pageLastRev);
            assert.deepEqual(res.body.items[0].title, options.pageName);
            assert.deepEqual(res.body.items[0].redirect, false);
        });
    });

    it('should return redirect true when included', () => {
        return preq.get({
            uri: `${server.config.bucketURL(options.domain)}/title/${encodeURIComponent(options.redirectPageName)}/${options.revRedirect}`
        })
        .then((res) => {
            assert.deepEqual(res.status, 200);
            assert.deepEqual(res.body.items.length, 1);
            assert.deepEqual(res.body.items[0].rev, options.revRedirect);
            assert.deepEqual(res.body.items[0].redirect, true);
        });
    });

    it('should query the MW API for revision info', () => {
        assert.recordRequests();
        return preq.get({
            uri: `${server.config.bucketURL(options.domain)}/title/${encodeURIComponent(options.pageName)}/${options.revPrevious}`,
            headers: { 'cache-control': 'no-cache' }
        })
        .then((res) => {
            assert.deepEqual(res.status, 200);
            assert.deepEqual(res.body.items.length, 1);
            assert.deepEqual(res.body.items[0].rev, options.revPrevious);
            assert.deepEqual(res.body.items[0].title, options.pageName);
            assert.remoteRequests(true);
        })
        .finally(() => assert.cleanupRecorder());
    });

    it('should fail for an invalid revision', () => {
        return preq.get({ uri: `${server.config.bucketURL(options.domain)}/title/${encodeURIComponent(options.pageName)}/faultyrevid` })
        .then((res) => {
            throw new Error(`Expected status 400 for an invalid revision, got ${res.status}`);
        },
        (res) => {
            assert.deepEqual(res.status, 400);
        });
    });

    it('should query the MW API for a non-existent revision and return a 404', () => {
        assert.recordRequests();
        return preq.get({ uri: `${server.config.bucketURL(options.domain)}/title/${encodeURIComponent(options.pageName)}/0` })
        .then((res) => {
            throw new Error(`Expected status 404 for an invalid revision, got ${res.status}`);
        },
        (res) => {
            assert.deepEqual(res.status, 404);
            assert.remoteRequests(true);
        })
        .finally(() => assert.cleanupRecorder());
    });

    it('should return latest revision for a page', () => {
        return preq.get({
            uri: `${server.config.bucketURL(options.domain)}/title/${encodeURIComponent(options.pageName)}`,
            headers: {
                'cache-control': 'no-cache'
            }
        })
        .then((res) => {
            assert.deepEqual(res.status, 200);
            assert.deepEqual(res.body.items.length, 1);
            assert.deepEqual(res.body.items[0].rev, options.pageLastRev);
        });
    });

}

describe('revision requests with en.wikipedia.org', function() {
    this.timeout(20000);
    const server = new Server();
    before(() =>  server.start());
    after(() =>  server.stop());

    const titleDeleted = 'User_talk:DivineAlpha/Q1_2015_discussions';
    const revDeleted = 645504917;

    generateTests(server,{
        domain: 'en.wikipedia.org',
        redirectPageName: 'Main_page',
        revRedirect: 591082967,
        pageName: 'User:GWicke/Date',
        pageLastRev: 653530930,
        revPrevious: 653529842
    });

    it('should fail for a restricted revision fetched from MW API', () => {
        return preq.get({
            uri: `${server.config.bucketURL()}/title/${encodeURIComponent(titleDeleted)}/${revDeleted}`,
            headers: { 'cache-control': 'no-cache' }
        })
        .then((res) => {
            throw new Error(`Expected status 403 for a restricted revision, got ${res.status}`);
        }, res => assert.deepEqual(res.status, 403));
    });

    it('should fail for a restricted revision present in storage', () => {
        return preq.get({
            uri: `${server.config.bucketURL()}/title/${encodeURIComponent(titleDeleted)}/${revDeleted}`,
        })
        .then((res) => {
            throw new Error(`Expected status 403 for a restricted revision, got ${res.status}`);
        }, res => assert.deepEqual(res.status, 403));
    });

    it('should restrict user and comment', () => {
        return preq.get({
            uri: `${server.config.bucketURL()}/title/User:Pchelolo%2fRestricted_Rev`
        })
        .then((res) => {
            assert.deepEqual(res.status, 200);
            const item = res.body.items[0];
            assert.deepEqual(!!item.user_id, false);
            assert.deepEqual(!!item.user_text, false);
            assert.deepEqual(!!item.comment, false);
        });
    });
});

describe('revision requests with test2.wikipedia.org', function() {
    this.timeout(20000);
    const server = new Server();
    before(() =>  server.start());
    after(() =>  server.stop());
    generateTests(server,{
        domain: 'test2.wikipedia.org',
        redirectPageName: 'User:Pchelolo/Redir',
        revRedirect: 157490,
        pageName: 'User:Pchelolo/Date',
        pageLastRev: 329034,
        revPrevious: 157487
    });
});

describe('revision requests with test.wikipedia.org', function() {
    this.timeout(20000);
    const server = new Server();
    before(() =>  server.start());
    after(() =>  server.stop());
    generateTests(server, {
        domain: 'test.wikipedia.org',
        redirectPageName: 'User:Pchelolo/Redir',
        revRedirect: 234965,
        pageName: 'User:Pchelolo/Date',
        pageLastRev: 234964,
        revPrevious: 234963
    });
});


text:
package technology.tikal.ventas.dao.producto;

import technology.tikal.gae.dao.template.ChildEntityDAO;
import technology.tikal.gae.pagination.model.PaginationData;
import technology.tikal.ventas.model.producto.ofy.CatalogoOfy;
import technology.tikal.ventas.model.producto.ofy.ProductoDeLineaOfy;

/**
 *
 * @author Nekorp
 *
 */
public interface ProductoDeLineaDao extends ChildEntityDAO<ProductoDeLineaOfy, Long, CatalogoOfy, ProductoDeLineaFilter, PaginationData<Long>> {

}


text:
package org.elasticsearch.join.mapper;

import org.elasticsearch.common.xcontent.support.XContentMapValues;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * Defines a relationship between a parent type and a set of child types
 */
class Relations {

    final String parent;
    final Set<String> children;

    Relations(String parent, Set<String> children) {
        this.parent = parent;
        this.children = children;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Relations relation = (Relations) o;
        return Objects.equals(parent, relation.parent) &&
            Objects.equals(children, relation.children);
    }

    @Override
    public int hashCode() {
        return Objects.hash(parent, children);
    }

    @Override
    public String toString() {
        return parent + "->" + children;
    }

    static List<Relations> parse(Object fieldNode) {
        List<Relations> parsed = new ArrayList<>();
        Map<String, Object> relations = XContentMapValues.nodeMapValue(fieldNode, "relations");
        for (Map.Entry<String, Object> relation : relations.entrySet()) {
            final String parent = relation.getKey();
            Set<String> children;
            if (XContentMapValues.isArray(relation.getValue())) {
                children = new HashSet<>(Arrays.asList(XContentMapValues.nodeStringArrayValue(relation.getValue())));
            } else {
                children = Collections.singleton(relation.getValue().toString());
            }
            parsed.add(new Relations(parent, children));
        }
        return parsed;
    }
}


text:
#include <string.h>
#include "../x11.h"

uint
textwidth(Font *font, const char *text) {
	return textwidth_l(font, text, strlen(text));
}


text:
Sequel.migration do
  up do
    extension :pg_json

    create_table(:classifiers) do
      primary_key :id
      String :section, null: false
      json :reference_values
    end

    run 'ALTER TABLE classifiers ADD COLUMN created_at TIMESTAMP DEFAULT NOW() NOT NULL;'
    run 'ALTER TABLE classifiers ADD COLUMN updated_at TIMESTAMP DEFAULT NOW() NOT NULL;'
  end

  down do
    drop_table(:classifiers)
  end
end


text:
using ECM7.Migrator.Framework;
using Framework.Migrator.Extensions;

namespace Core.Web.Migrations
{
    /// <summary>
    /// Adds ContentPages table.
    /// </summary>
    [Migration(14)]
    public class Migration_AddPageLayoutRows : Migration
    {
        /// <summary>
        /// Executes migration.
        /// </summary>
        public override void Apply()
        {
            Database.AddTable("PageLayoutRows", t =>
            {
                t.PrimaryKey();

                t.ForeignKey("PageLayoutRowsTemplate").Table("PageLayoutTemplates").Column("TemplateId");
            });
        }

       /// <summary>
        /// Rollbacks migration.
        /// </summary>
        public override void Revert()
        {
            Database.ChangeTable("PageLayoutRows", t => t.RemoveForeignKey("PageLayoutRowsTemplate").Table("PageLayoutTemplates"));

            Database.RemoveTable("PageLayoutRows");
        }
    }
}


text:
package sh.isaac.api.importers;

//~--- classes ----------------------------------------------------------------

import sh.isaac.api.util.StringUtils;

/**
 *
 * {@link ConverterOptionParamSuggestedValue}
 * Just a simple Pair object.
 *
 * @author Dan Armbrust
 */
public class ConverterOptionParamSuggestedValue {
   /** The value. */
   private String value;

   /** The description. */
   private String description;

   //~--- constructors --------------------------------------------------------

   /**
    * Instantiates a new converter option param suggested value.
    */
   @SuppressWarnings("unused")
   private ConverterOptionParamSuggestedValue() {
      // For serialization
   }

   /**
    * Instantiates a new converter option param suggested value.
    *
    * @param value the value
    */
   public ConverterOptionParamSuggestedValue(String value) {
      this.value = value;
   }

   /**
    * Instantiates a new converter option param suggested value.
    *
    * @param value the value
    * @param description the description
    */
   public ConverterOptionParamSuggestedValue(String value, String description) {
      this.value       = value;
      this.description = description;
   }

   //~--- methods -------------------------------------------------------------

   /**
    * Equals.
    *
    * @param obj the obj
    * @return true, if successful
    */
   @Override
   public boolean equals(Object obj) {
      if (this == obj) {
         return true;
      }

      if (obj == null) {
         return false;
      }

      if (getClass() != obj.getClass()) {
         return false;
      }

      final ConverterOptionParamSuggestedValue other = (ConverterOptionParamSuggestedValue) obj;

      if (this.value == null) {
         if (other.value != null) {
            return false;
         }
      } else if (!this.value.equals(other.value)) {
         return false;
      }

      if (getDescription() == null) {
         if (other.getDescription() != null) {
            return false;
         }
      } else if (!getDescription().equals(other.getDescription())) {
         return false;
      }

      return true;
   }

   /**
    * Hash code.
    *
    * @return the int
    */
   @Override
   public int hashCode() {
      final int prime  = 31;
      int       result = 1;

      result = prime * result + getDescription().hashCode();
      result = prime * result + ((this.value == null) ? 0
            : this.value.hashCode());
      return result;
   }

   /**
    * To string.
    *
    * @return the string
    */
   @Override
   public String toString() {
      return "ConverterOptionParamSuggestedValue [value=" + this.value + ", description=" + this.description + "]";
   }

   //~--- get methods ---------------------------------------------------------

   /**
    * A user friendly description of this value for use in user-facing GUIs.  If a description wasn't provided
    * upon construction, this will return the same thing as {@link #getValue()}
    *
    * @return the description
    */
   public String getDescription() {
      return StringUtils.isNotBlank(this.description) ? this.description
            : this.value;
   }

   /**
    * The value to be passed in to the {@link ConverterOptionParam} class.
    *
    * @return the value
    */
   public String getValue() {
      return this.value;
   }
}


text:
package com.belladati.sdk.exception.interval;

import com.belladati.sdk.exception.BellaDatiRuntimeException;
import com.belladati.sdk.intervals.IntervalUnit;

/**
 * Indicates that something went wrong with an interval.
 *
 * @author Chris Hennigfeld
 */
public abstract class InvalidIntervalException extends BellaDatiRuntimeException {

	/** The serialVersionUID */
	private static final long serialVersionUID = -7118929916818931716L;

	private final IntervalUnit intervalUnit;

	InvalidIntervalException(IntervalUnit intervalUnit, String message) {
		super(message);
		this.intervalUnit = intervalUnit;
	}

	/**
	 * Returns the unit set on the interval that caused the problem.
	 *
	 * @return the unit set on the interval
	 */
	public IntervalUnit getIntervalUnit() {
		return intervalUnit;
	}
}


text:
namespace arc {

TEST(ArcContentFileSystemUrlUtilTest, EncodeAndDecodeExternalFileUrl) {
  {
    GURL src("file://foo/bar/baz");
    GURL dest = ArcUrlToExternalFileUrl(src);
    EXPECT_TRUE(dest.is_valid());
    EXPECT_EQ(content::kExternalFileScheme, dest.scheme());
    GURL result = ExternalFileUrlToArcUrl(dest);
    EXPECT_TRUE(result.is_valid());
    EXPECT_EQ(src, result);
  }
  {
    GURL src("content://org.chromium.foo/bar/baz");
    GURL dest = ArcUrlToExternalFileUrl(src);
    EXPECT_TRUE(dest.is_valid());
    EXPECT_EQ(content::kExternalFileScheme, dest.scheme());
    GURL result = ExternalFileUrlToArcUrl(dest);
    EXPECT_TRUE(result.is_valid());
    EXPECT_EQ(src, result);
  }
  {
    GURL src("content://org.chromium.foo/bar/%19%20%21");
    GURL dest = ArcUrlToExternalFileUrl(src);
    EXPECT_TRUE(dest.is_valid());
    EXPECT_EQ(content::kExternalFileScheme, dest.scheme());
    GURL result = ExternalFileUrlToArcUrl(dest);
    EXPECT_TRUE(result.is_valid());
    EXPECT_EQ(src, result);
  }
  {
    GURL src("content://org.chromium.foo/!@#$%^&*()_+|~-=\\`[]{};':\"<>?,./");
    GURL dest = ArcUrlToExternalFileUrl(src);
    EXPECT_TRUE(dest.is_valid());
    EXPECT_EQ(content::kExternalFileScheme, dest.scheme());
    GURL result = ExternalFileUrlToArcUrl(dest);
    EXPECT_TRUE(result.is_valid());
    EXPECT_EQ(src, result);
  }
  {
    std::u16string utf16_string = {
        0x307b,  // HIRAGANA_LETTER_HO
        0x3052,  // HIRAGANA_LETTER_GE
    };
    GURL src("content://org.chromium.foo/" + base::UTF16ToUTF8(utf16_string));
    GURL dest = ArcUrlToExternalFileUrl(src);
    EXPECT_TRUE(dest.is_valid());
    EXPECT_EQ(content::kExternalFileScheme, dest.scheme());
    GURL result = ExternalFileUrlToArcUrl(dest);
    EXPECT_TRUE(result.is_valid());
    EXPECT_EQ(src, result);
  }
}

TEST(ArcContentFileSystemUrlUtilTest, FileSystemUrlToArcUrl) {
  GURL arc_url("content://org.chromium.foo/bar/baz");

  base::FilePath path =
      base::FilePath(kContentFileSystemMountPointPath)
          .Append(base::FilePath::FromUTF8Unsafe(EscapeArcUrl(arc_url)));
  storage::FileSystemURL file_system_url =
      storage::FileSystemURL::CreateForTest(
          blink::StorageKey(), storage::kFileSystemTypeArcContent, path);

  EXPECT_EQ(arc_url, FileSystemUrlToArcUrl(file_system_url));
}

TEST(ArcContentFileSystemUrlUtilTest, PathToArcUrl) {
  GURL arc_url("content://org.chromium.foo/bar/baz");

  base::FilePath path =
      base::FilePath(kContentFileSystemMountPointPath)
          .Append(base::FilePath::FromUTF8Unsafe(EscapeArcUrl(arc_url)));
  EXPECT_EQ(arc_url, PathToArcUrl(path));
}

}  // namespace arc


text:
<macros>
    <token name="@STRING2VECTOR@">
string2numericvector = function(string){
    #' Converts a string to a valid vector
    #'
    #' e.g. "-1,2:5,2"  evaluates to c(-1,2,3,4,5,2)
    #'
    #' @param add string2vector function to safe environment
    #' @return vector of integers
    terms = unlist(strsplit(string, split=","))
    res = lapply(terms, function(x){
        if (grepl(":",x)){
            l_r = as.integer(c(unlist(strsplit(x,split=":"))))
            return(seq(l_r[1],l_r[2]))
        }
        return(as.integer(x))
    })
    return(c(unlist(res)))
}

string2textvector = function(string){
    #' Converts a string to a valid string vector
    #'
    #'   e.g. "red,yellow,white" evaluates to c("red","yellow","white")
    return(unlist(strsplit(string,",")))
}
    </token>
    <token name="@TOOL_VERSION@">0.2.3</token>
    <token name="@VERSION_SUFFIX@">2</token>
    <token name="@PROFILE@">21.01</token>

    <macro name="version_command_config" token_prog="temp" token_cheetah="temp2" token_out="2> '$outlog'">
        <version_command><![CDATA[
Rscript '$__tool_directory__/scripts/@PROG@' 2>&1 | head -1 | cut -d' ' -f 2
        ]]></version_command>
        <command detect_errors="exit_code"><![CDATA[
Rscript '$__tool_directory__/scripts/@PROG@' '$userconf' @OUT@
]]>
        </command>
        <configfiles>
            <configfile name="userconf" ><![CDATA[
@STRING2VECTOR@

@@CHEETAH@@
]]></configfile>
        </configfiles>
    </macro>

    <macro name="requirements" >
        <requirements>
            <requirement type="package" version="@TOOL_VERSION@" >r-raceid</requirement>
            <!-- <requirement type="package" version="1.6.2">bioconductor-scran</requirement> -->
        </requirements>
    </macro>
    <macro name="yesno_checkedno" >
        <option value="yes" >Yes</option>
        <option value="no" selected="true" >No</option>
    </macro>
    <macro name="use_defaults_no" >
        <conditional name="use" >
            <param name="def" type="select" label="Use Defaults?" >
                <option value="yes" selected="true" >Yes</option>
                <option value="no" >No</option>
            </param>
            <when value="yes" />
            <when value="no" >
                <yield />
            </when>
        </conditional>
    </macro>
    <macro name="test_nondef" >
        <conditional name="use" >
            <param name="def" value="no" />
            <yield />
        </conditional>
    </macro>
    <macro name="section_test_nondef" >
        <section name="@SECTIONNAME@" >
            <expand macro="test_nondef" >
                <yield />
            </expand>
        </section>
    </macro>
    <macro name="citations" >
        <citations>
            <citation type="doi">10.1038/nature14966</citation>
            <citation type="doi">10.1038/nmeth.4662</citation>
        </citations>
    </macro>
    <!-- Sanitizers -->
    <macro name="sanitize_title">
        <sanitizer invalid_char="">
            <valid initial="string.letters,string.digits" >
                <add value=" " />
                <add value="_" />
            </valid>
        </sanitizer>
    </macro>
    <macro name="sanitize_regex" >
        <sanitizer invalid_char="">
            <valid initial="string.letters,string.digits">
                <add value="!"/>
                <add value="="/>
                <add value="-"/>
                <add value="."/>
                <add value="*"/>
                <add value="?"/>
                <add value="+"/>
                <add value="\\"/>
                <add value="_"/>
                <add value="|"/>
                <add value="["/> <!-- left square bracket, e.g subselecting from vec[1] -->
                <add value="]"/> <!-- right square bracket -->
                <add value="("/> <!-- left parenthesis -->
                <add value=")"/> <!-- right parenthesis -->
            </valid>
        </sanitizer>
    </macro>
    <macro name="sanitize_numeric_vector" >
        <sanitizer invalid_char="">
            <valid initial="string.digits">
                <add value=","/>
            </valid>
        </sanitizer>
    </macro>
    <macro name="sanitize_string_vector" >
        <sanitizer invalid_char="">
            <valid initial="string.letters,string.digits">
                <add value=","/>
                <add value="_"/>
                <add value="-"/>
                <add value="."/>
            </valid>
        </sanitizer>
    </macro>
</macros>


text:
/*
 * patternlab-node - v2.9.3 - 2017
 *
 * Brian Muenzenmeyer, Geoff Pursell, Raphael Okon, tburny and the web community.
 * Licensed under the MIT license.
 *
 * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice.
 *
 */

"use strict";

var diveSync = require('diveSync'),
  glob = require('glob'),
  _ = require('lodash'),
  path = require('path'),
  chalk = require('chalk'),
  cleanHtml = require('js-beautify').html,
  inherits = require('util').inherits,
  pm = require('./plugin_manager'),
  fs = require('fs-extra'),
  packageInfo = require('../../package.json'),
  plutils = require('./utilities'),
  jsonCopy = require('./json_copy'),
  ui = require('./ui_builder'),
  ui_builder = new ui(),
  pe = require('./pattern_exporter'),
  pattern_exporter = new pe(),
  PatternGraph = require('./pattern_graph').PatternGraph;

//register our log events
plutils.log.on('error', msg => console.log(msg));
plutils.log.on('debug', msg => console.log(msg));
plutils.log.on('warning', msg => console.log(msg));
plutils.log.on('info', msg => console.log(msg));

console.log(
  chalk.bold('\n====[ Pattern Lab / Node'),
  `- v${packageInfo.version}`,
  chalk.bold(']====\n')
);

var patternEngines = require('./pattern_engines');
var EventEmitter = require('events').EventEmitter;

function buildPatternData(dataFilesPath, fsDep) {
  var dataFiles = glob.sync(dataFilesPath + '*.json', {"ignore" : [dataFilesPath + 'listitems.json']});
  var mergeObject = {};
  dataFiles.forEach(function (filePath) {
    var jsonData = fsDep.readJSONSync(path.resolve(filePath), 'utf8');
    mergeObject = _.merge(mergeObject, jsonData);
  });
  return mergeObject;
}

// GTP: these two diveSync pattern processors factored out so they can be reused
// from unit tests to reduce code dupe!
function processAllPatternsIterative(pattern_assembler, patterns_dir, patternlab) {
  diveSync(
    patterns_dir,
    function (err, file) {
      //log any errors
      if (err) {
        console.log(err);
        return;
      }
      pattern_assembler.process_pattern_iterative(path.relative(patterns_dir, file), patternlab);
    }
  );
}

function processAllPatternsRecursive(pattern_assembler, patterns_dir, patternlab) {
  diveSync(
    patterns_dir,
    function (err, file) {
      //log any errors
      if (err) {
        console.log(err);
        return;
      }
      pattern_assembler.process_pattern_recursive(path.relative(patterns_dir, file), patternlab);
    }
  );
}

function checkConfiguration(patternlab) {
  //default the output suffixes if not present
  var outputFileSuffixes = {
    rendered: '.rendered',
    rawTemplate: '',
    markupOnly: '.markup-only'
  };

  if (!patternlab.config.outputFileSuffixes) {
    plutils.warning('Configuration Object "outputFileSuffixes" not found, and defaulted to the following:');
    console.log(outputFileSuffixes);
    plutils.warning('Since Pattern Lab Core 2.3.0 this configuration option is required. Suggest you add it to your patternlab-config.json file.');
    console.log();
  }
  patternlab.config.outputFileSuffixes = _.extend(outputFileSuffixes, patternlab.config.outputFileSuffixes);
}

/**
 * Finds and calls the main method of any found plugins.
 * @param patternlab - global data store
 */

//todo, move this to plugin_manager
function initializePlugins(patternlab) {

  if (!patternlab.config.plugins) { return; }

  var plugin_manager = new pm(patternlab.config, path.resolve(__dirname, '../../patternlab-config.json'));
  var foundPlugins = plugin_manager.detect_plugins();

  if (foundPlugins && foundPlugins.length > 0) {

    for (var i = 0; i < foundPlugins.length; i++) {

      let pluginKey = foundPlugins[i];

      if (patternlab.config.debug) {
        console.log('Found plugin: ', pluginKey);
        console.log('Attempting to load and initialize plugin.');
      }

      var plugin = plugin_manager.load_plugin(pluginKey);
      plugin(patternlab);
    }
  }
}

/**
 * Installs a given plugin. Assumes it has already been pulled down via npm
 * @param pluginName - the name of the plugin
 */
function installPlugin(pluginName) {
  //get the config
  var configPath = path.resolve(process.cwd(), 'patternlab-config.json');
  var config = fs.readJSONSync(path.resolve(configPath), 'utf8');
  var plugin_manager = new pm(config, configPath);

  plugin_manager.install_plugin(pluginName);
}

function PatternLabEventEmitter() {
  EventEmitter.call(this);
}
inherits(PatternLabEventEmitter, EventEmitter);

var patternlab_engine = function (config) {
  'use strict';

  var pa = require('./pattern_assembler'),
    lh = require('./lineage_hunter'),
    sm = require('./starterkit_manager'),
    Pattern = require('./object_factory').Pattern,
    CompileState = require('./object_factory').CompileState,
    patternlab = {};

  patternlab.engines = patternEngines;

  var pattern_assembler = new pa(),
    lineage_hunter = new lh();

  patternlab.package = fs.readJSONSync(path.resolve(__dirname, '../../package.json'));
  patternlab.config = config || fs.readJSONSync(path.resolve(__dirname, '../../patternlab-config.json'));
  patternlab.events = new PatternLabEventEmitter();

  // Initialized when building
  patternlab.graph = null;

  checkConfiguration(patternlab);

  //todo: determine if this is the best place to wire up plugins
  initializePlugins(patternlab);

  var paths = patternlab.config.paths;

  function getVersion() {
    console.log(patternlab.package.version);
  }

  function getSupportedTemplateExtensions() {
    return patternlab.engines.getSupportedFileExtensions();
  }

  function help() {

    console.log('');

    console.log('|=======================================|');
    plutils.debug('     Pattern Lab Node Help v' + patternlab.package.version);
    console.log('|=======================================|');

    console.log('');
    console.log('Command Line Interface - usually consumed by an edition');
    console.log('');

    plutils.debug(' patternlab:build');
    console.log('   > Compiles the patterns and frontend, outputting to config.paths.public');
    console.log('');

    plutils.debug(' patternlab:patternsonly');
    console.log('   > Compiles the patterns only, outputting to config.paths.public');
    console.log('');

    plutils.debug(' patternlab:version');
    console.log('   > Return the version of patternlab-node you have installed');
    console.log('');

    plutils.debug(' patternlab:help');
    console.log('   > Get more information about patternlab-node, pattern lab in general, and where to report issues.');
    console.log('');

    plutils.debug(' patternlab:liststarterkits');
    console.log('   > Returns a url with the list of available starterkits hosted on the Pattern Lab organization Github account');
    console.log('');

    plutils.debug(' patternlab:loadstarterkit');
    console.log('   > Load a starterkit into config.paths.source/*');
    console.log('   > NOTE: Overwrites existing content, and only cleans out existing directory if --clean=true argument is passed.');
    console.log('   > NOTE: In most cases, `npm install starterkit-name` will precede this call.');
    console.log('   > arguments:');
    console.log('      -- kit ');
    console.log('      > the name of the starter kit to load');
    console.log('      -- clean ');
    console.log('      > removes all files from config.paths.source/ prior to load');
    console.log('   > example (gulp):');
    console.log('    `gulp patternlab:loadstarterkit --kit=starterkit-mustache-demo`');
    console.log('');

    console.log('===============================');
    console.log('');
    console.log('Visit http://patternlab.io/ for more info about Pattern Lab');
    console.log('Visit https://github.com/pattern-lab/patternlab-node/issues to open an issue.');
    console.log('Visit https://github.com/pattern-lab/patternlab-node/wiki to view the changelog, roadmap, and other info.');
    console.log('');
    console.log('===============================');
  }

  function printDebug() {
    // A replacer function to pass to stringify below; this is here to prevent
    // the debug output from blowing up into a massive fireball of circular
    // references. This happens specifically with the Handlebars engine. Remove
    // if you like 180MB log files.
    function propertyStringReplacer(key, value) {
      if (key === 'engine' && value && value.engineName) {
        return '{' + value.engineName + ' engine object}';
      }
      return value;
    }

    //debug file can be written by setting flag on patternlab-config.json
    if (patternlab.config.debug) {
      console.log('writing patternlab debug file to ./patternlab.json');
      fs.outputFileSync('./patternlab.json', JSON.stringify(patternlab, propertyStringReplacer, 3));
    }
  }

  function setCacheBust() {
    if (patternlab.config.cacheBust) {
      if (patternlab.config.debug) {
        console.log('setting cacheBuster value for frontend assets.');
      }
      patternlab.cacheBuster = new Date().getTime();
    } else {
      patternlab.cacheBuster = 0;
    }
  }

  function listStarterkits() {
    var starterkit_manager = new sm(patternlab.config);
    return starterkit_manager.list_starterkits();
  }

  function loadStarterKit(starterkitName, clean) {
    var starterkit_manager = new sm(patternlab.config);
    starterkit_manager.load_starterkit(starterkitName, clean);
  }

  /**
   * Process the user-defined pattern head and prepare it for rendering
   */
  function processHeadPattern() {
    try {
      var headPath = path.resolve(paths.source.meta, '_00-head.mustache');
      var headPattern = new Pattern(headPath, null, patternlab);
      headPattern.template = fs.readFileSync(headPath, 'utf8');
      headPattern.isPattern = false;
      headPattern.isMetaPattern = true;
      pattern_assembler.decomposePattern(headPattern, patternlab, true);
      patternlab.userHead = headPattern.extendedTemplate;
    }
    catch (ex) {
      plutils.error('\nWARNING: Could not find the user-editable header template, currently configured to be at ' + path.join(config.paths.source.meta, '_00-head.mustache') + '. Your configured path may be incorrect (check paths.source.meta in your config file), the file may have been deleted, or it may have been left in the wrong place during a migration or update.\n');
      if (patternlab.config.debug) { console.log(ex); }
      process.exit(1);
    }
  }

  /**
   * Process the user-defined pattern footer and prepare it for rendering
   */
  function processFootPattern() {
    try {
      var footPath = path.resolve(paths.source.meta, '_01-foot.mustache');
      var footPattern = new Pattern(footPath, null, patternlab);
      footPattern.template = fs.readFileSync(footPath, 'utf8');
      footPattern.isPattern = false;
      footPattern.isMetaPattern = true;
      pattern_assembler.decomposePattern(footPattern, patternlab, true);
      patternlab.userFoot = footPattern.extendedTemplate;
    }
    catch (ex) {
      plutils.error('\nWARNING: Could not find the user-editable footer template, currently configured to be at ' + path.join(config.paths.source.meta, '_01-foot.mustache') + '. Your configured path may be incorrect (check paths.source.meta in your config file), the file may have been deleted, or it may have been left in the wrong place during a migration or update.\n');
      if (patternlab.config.debug) { console.log(ex); }
      process.exit(1);
    }
  }

  function writePatternFiles(headHTML, pattern, footerHTML) {
    const nullFormatter = str => str;
    const defaultFormatter = codeString => cleanHtml(codeString, {indent_size: 2});
    const makePath = type => path.join(paths.public.patterns, pattern.getPatternLink(patternlab, type));
    const patternPage = headHTML + pattern.patternPartialCode + footerHTML;
    const eng = pattern.engine;

    //beautify the output if configured to do so
    const formatters = config.cleanOutputHtml ? {
      rendered:     eng.renderedCodeFormatter || defaultFormatter,
      rawTemplate:  eng.rawTemplateCodeFormatter || defaultFormatter,
      markupOnly:   eng.markupOnlyCodeFormatter || defaultFormatter
    } : {
      rendered:     nullFormatter,
      rawTemplate:  nullFormatter,
      markupOnly:   nullFormatter
    };

    //prepare the path and contents of each output file
    const outputFiles = [
      { path: makePath('rendered'), content: formatters.rendered(patternPage, pattern) },
      { path: makePath('rawTemplate'), content: formatters.rawTemplate(pattern.template, pattern) },
      { path: makePath('markupOnly'), content: formatters.markupOnly(pattern.patternPartialCode, pattern) }
    ].concat(
      eng.addOutputFiles ? eng.addOutputFiles(paths, patternlab) : []
    );

    //write the compiled template to the public patterns directory
    outputFiles.forEach(outFile => fs.outputFileSync(outFile.path, outFile.content));
  }

  function renderSinglePattern(pattern, head) {
    // Pattern does not need to be built and recompiled more than once
    if (!pattern.isPattern || pattern.compileState === CompileState.CLEAN) {
      return false;
    }

    // Allows serializing the compile state
    patternlab.graph.node(pattern).compileState = pattern.compileState = CompileState.BUILDING;

    //todo move this into lineage_hunter
    pattern.patternLineages = pattern.lineage;
    pattern.patternLineageExists = pattern.lineage.length > 0;
    pattern.patternLineagesR = pattern.lineageR;
    pattern.patternLineageRExists = pattern.lineageR.length > 0;
    pattern.patternLineageEExists = pattern.patternLineageExists || pattern.patternLineageRExists;

    patternlab.events.emit('patternlab-pattern-before-data-merge', patternlab, pattern);

    //render the pattern, but first consolidate any data we may have
    var allData;
    try {
      allData = jsonCopy(patternlab.data, 'config.paths.source.data global data');
    } catch (err) {
      console.log('There was an error parsing JSON for ' + pattern.relPath);
      console.log(err);
    }
    allData = plutils.mergeData(allData, pattern.jsonFileData);
    allData.cacheBuster = patternlab.cacheBuster;

    //re-rendering the headHTML each time allows pattern-specific data to influence the head of the pattern
    pattern.header = head;
    var headHTML = pattern_assembler.renderPattern(pattern.header, allData);

    //render the extendedTemplate with all data
    pattern.patternPartialCode = pattern_assembler.renderPattern(pattern, allData);

    // stringify this data for individual pattern rendering and use on the styleguide
    // see if patternData really needs these other duped values
    pattern.patternData = JSON.stringify({
      cssEnabled: false,
      patternLineageExists: pattern.patternLineageExists,
      patternLineages: pattern.patternLineages,
      lineage: pattern.patternLineages,
      patternLineageRExists: pattern.patternLineageRExists,
      patternLineagesR: pattern.patternLineagesR,
      lineageR: pattern.patternLineagesR,
      patternLineageEExists: pattern.patternLineageExists || pattern.patternLineageRExists,
      patternDesc: pattern.patternDescExists ? pattern.patternDesc : '',
      patternBreadcrumb:
        pattern.patternGroup === pattern.patternSubGroup ? {
          patternType: pattern.patternGroup
        } : {
          patternType: pattern.patternGroup,
          patternSubtype: pattern.patternSubGroup
        },
      patternExtension: pattern.fileExtension.substr(1), //remove the dot because styleguide asset default adds it for us
      patternName: pattern.patternName,
      patternPartial: pattern.patternPartial,
      patternState: pattern.patternState,
      patternEngineName: pattern.engine.engineName,
      extraOutput: {}
    });

    //set the pattern-specific footer by compiling the general-footer with data, and then adding it to the meta footer
    var footerPartial = pattern_assembler.renderPattern(patternlab.footer, {
      isPattern: pattern.isPattern,
      patternData: pattern.patternData,
      cacheBuster: patternlab.cacheBuster
    });

    var allFooterData;
    try {
      allFooterData = jsonCopy(patternlab.data, 'config.paths.source.data global data');
    } catch (err) {
      console.log('There was an error parsing JSON for ' + pattern.relPath);
      console.log(err);
    }
    allFooterData = plutils.mergeData(allFooterData, pattern.jsonFileData);
    allFooterData.patternLabFoot = footerPartial;

    var footerHTML = pattern_assembler.renderPattern(patternlab.userFoot, allFooterData);

    patternlab.events.emit('patternlab-pattern-write-begin', patternlab, pattern);

    //write the compiled template to the public patterns directory
    writePatternFiles(headHTML, pattern, footerHTML);

    patternlab.events.emit('patternlab-pattern-write-end', patternlab, pattern);

    // Allows serializing the compile state
    patternlab.graph.node(pattern).compileState = pattern.compileState = CompileState.CLEAN;
    plutils.log.info("Built pattern: " + pattern.patternPartial);
    return true;
  }

  /**
   * If a graph was serialized and then {@code deletePatternDir == true}, there is a mismatch in the
   * pattern metadata and not all patterns might be recompiled.
   * For that reason an empty graph is returned in this case, so every pattern will be flagged as
   * "needs recompile". Otherwise the pattern graph is loaded from the meta data.
   *
   * @param patternlab
   * @param {boolean} deletePatternDir When {@code true}, an empty graph is returned
   * @return {PatternGraph}
   */
  function loadPatternGraph(deletePatternDir) {
    // Sanity check to prevent problems when code is refactored
    if (deletePatternDir) {
      return PatternGraph.empty();
    }
    return PatternGraph.loadFromFile(patternlab);
  }

  function buildPatterns(deletePatternDir) {

    patternlab.events.emit('patternlab-build-pattern-start', patternlab);

    let graph = patternlab.graph = loadPatternGraph(deletePatternDir);

    let graphNeedsUpgrade = !PatternGraph.checkVersion(graph);

    if (graphNeedsUpgrade) {
      plutils.log.info("Due to an upgrade, a complete rebuild is required and the public/patterns directory was deleted. " +
        "Incremental build is available again on the next successful run.");

      // Ensure that the freshly built graph has the latest version again.
      patternlab.graph.upgradeVersion();
    }

    // Flags
    let incrementalBuildsEnabled = !(deletePatternDir || graphNeedsUpgrade);

    if (incrementalBuildsEnabled) {
      plutils.log.info("Incremental builds enabled.");
    } else {
      // needs to be done BEFORE processing patterns
      fs.removeSync(paths.public.patterns);
      fs.emptyDirSync(paths.public.patterns);
    }

    try {
      patternlab.data = buildPatternData(paths.source.data, fs);
    } catch (ex) {
      plutils.error('missing or malformed' + paths.source.data + 'data.json  Pattern Lab may not work without this file.');
      patternlab.data = {};
    }
    try {
      patternlab.listitems = fs.readJSONSync(path.resolve(paths.source.data, 'listitems.json'));
    } catch (ex) {
      plutils.warning('WARNING: missing or malformed ' + paths.source.data + 'listitems.json file.  Pattern Lab may not work without this file.');
      patternlab.listitems = {};
    }
    try {
      patternlab.header = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'general-header.mustache'), 'utf8');
      patternlab.footer = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'general-footer.mustache'), 'utf8');
      patternlab.patternSection = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'patternSection.mustache'), 'utf8');
      patternlab.patternSectionSubType = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'partials', 'patternSectionSubtype.mustache'), 'utf8');
      patternlab.viewAll = fs.readFileSync(path.resolve(paths.source.patternlabFiles, 'viewall.mustache'), 'utf8');
    } catch (ex) {
      console.log(ex);
      plutils.error('\nERROR: missing an essential file from ' + paths.source.patternlabFiles + '. Pattern Lab won\'t work without this file.\n');
      process.exit(1);
    }
    patternlab.patterns = [];
    patternlab.subtypePatterns = {};
    patternlab.partials = {};
    patternlab.data.link = {};

    setCacheBust();

    pattern_assembler.combine_listItems(patternlab);

    patternlab.events.emit('patternlab-build-global-data-end', patternlab);

    // diveSync once to perform iterative populating of patternlab object
    processAllPatternsIterative(pattern_assembler, paths.source.patterns, patternlab);

    patternlab.events.emit('patternlab-pattern-iteration-end', patternlab);

    //now that all the main patterns are known, look for any links that might be within data and expand them
    //we need to do this before expanding patterns & partials into extendedTemplates, otherwise we could lose the data -> partial reference
    pattern_assembler.parse_data_links(patternlab);

    //diveSync again to recursively include partials, filling out the
    //extendedTemplate property of the patternlab.patterns elements
    // TODO we can reduce the time needed by only processing changed patterns and their partials
    processAllPatternsRecursive(pattern_assembler, paths.source.patterns, patternlab);

    //take the user defined head and foot and process any data and patterns that apply
    processHeadPattern();
    processFootPattern();

    //cascade any patternStates
    lineage_hunter.cascade_pattern_states(patternlab);

    //set pattern-specific header if necessary
    var head;
    if (patternlab.userHead) {
      head = patternlab.userHead;
    } else {
      head = patternlab.header;
    }

    //set the pattern-specific header by compiling the general-header with data, and then adding it to the meta header
    patternlab.data.patternLabHead = pattern_assembler.renderPattern(patternlab.header, {
      cacheBuster: patternlab.cacheBuster
    });

    // If deletePatternDir == true or graph needs to be updated
    // rebuild all patterns
    let patternsToBuild = null;

    if (incrementalBuildsEnabled) {
      // When the graph was loaded from file, some patterns might have been moved/deleted between runs
      // so the graph data become out of sync
      patternlab.graph.sync().forEach(n => {
        plutils.log.info("[Deleted/Moved] " + n);
      });

      // TODO Find created or deleted files
      let now = new Date().getTime();
      pattern_assembler.mark_modified_patterns(now, patternlab);
      patternsToBuild = patternlab.graph.compileOrder();
    } else {
      // build all patterns, mark all to be rebuilt
      patternsToBuild = patternlab.patterns;
      for (let p of patternsToBuild) {
        p.compileState = CompileState.NEEDS_REBUILD;
      }
    }

    //render all patterns last, so lineageR works
    patternsToBuild.forEach(pattern => renderSinglePattern(pattern, head));

    // Saves the pattern graph when all files have been compiled
    PatternGraph.storeToFile(patternlab);
    if (patternlab.config.exportToGraphViz) {
      PatternGraph.exportToDot(patternlab, "dependencyGraph.dot");
      plutils.log.info(`Exported pattern graph to ${path.join(config.paths.public.root, "dependencyGraph.dot")}`);
    }

    //export patterns if necessary
    pattern_exporter.export_patterns(patternlab);
  }

  return {
    version: function () {
      return getVersion();
    },
    build: function (callback, deletePatternDir) {
      if (patternlab && patternlab.isBusy) {
        console.log('Pattern Lab is busy building a previous run - returning early.');
        return;
      }
      patternlab.isBusy = true;
      buildPatterns(deletePatternDir);
      ui_builder.buildFrontend(patternlab);
      printDebug();
      patternlab.isBusy = false;
      callback();
    },
    help: function () {
      help();
    },
    patternsonly: function (callback, deletePatternDir) {
      if (patternlab && patternlab.isBusy) {
        console.log('Pattern Lab is busy building a previous run - returning early.');
        return;
      }
      patternlab.isBusy = true;
      buildPatterns(deletePatternDir);
      printDebug();
      patternlab.isBusy = false;
      callback();
    },
    liststarterkits: function () {
      return listStarterkits();
    },
    loadstarterkit: function (starterkitName, clean) {
      loadStarterKit(starterkitName, clean);
    },
    installplugin: function (pluginName) {
      installPlugin(pluginName);
    },
    getSupportedTemplateExtensions: function () {
      return getSupportedTemplateExtensions();
    }
  };
};

// export these free functions so they're available without calling the exported
// function, for use in reducing code dupe in unit tests. At least, until we
// have a better way to do this
patternlab_engine.build_pattern_data = buildPatternData;
patternlab_engine.process_all_patterns_iterative = processAllPatternsIterative;
patternlab_engine.process_all_patterns_recursive = processAllPatternsRecursive;

module.exports = patternlab_engine;