text:
PendingReviewItemView = ItemView.extend({
    templates: {
    },
    errorTypes: {
        "validation": "Validation Error. Please review for details.",
        "offline": "Offline during submission. Ok to resubmit",
        "network": "Network issue during submission. Ok to resubmit",
        "timeout": "Form Submission timeout. Please try again later",
        "defaults": "Unknown Error. Please review for details"
    },
    getIdText: function() {
        return "FormId: " + this.model.get("formId");
    },
    getItemTime: function() {
        return "Submitted At: <br/>" + moment(this.model.get("submitDate")).calendar();
    },
    getType: function(){
        return "review";
    },
    show: function() {
        var self = this;
        App.views.header.hideAll();

        self.model.loadSubmission(self.model.submissionMeta, function(err) {
            if (err) {
                $fh.forms.log.e("Error loading submission ", err);
            }
            var submission = self.model.coreModel;
            App.views.form = new FormView({
                "parentEl": $("#fh_appform_content"),
                "formId": submission.get("formId"),
                "autoShow": true,
                "submission": submission
            });
        });
    },
    getButtons : function(){
        var draftButtons = [
            {
                itemText: "Clear",
                itemClass: "delete-item fh_appform_button_cancel"
            },
            {
                itemText: "Edit",
                itemClass: "group-detail fh_appform_button_action"
            }
        ];

        return this.generateButtonHtml(draftButtons);
    }
});


text:
import sys, os.path
from aubio import pvoc, source, float_type
from numpy import zeros, log10, vstack
import matplotlib.pyplot as plt

def get_spectrogram(filename, samplerate = 0):
    win_s = 512                                        # fft window size
    hop_s = win_s // 2                                 # hop size
    fft_s = win_s // 2 + 1                             # spectrum bins

    a = source(filename, samplerate, hop_s)            # source file
    if samplerate == 0: samplerate = a.samplerate
    pv = pvoc(win_s, hop_s)                            # phase vocoder
    specgram = zeros([0, fft_s], dtype=float_type)     # numpy array to store spectrogram

    # analysis
    while True:
        samples, read = a()                              # read file
        specgram = vstack((specgram,pv(samples).norm))   # store new norm vector
        if read < a.hop_size: break

    return specgram

    # plotting
    # fig = plt.imshow(log10(specgram.T + .001), origin = 'bottom', aspect = 'auto', cmap=plt.cm.gray_r)
    # ax = fig.axes
    # ax.axis([0, len(specgram), 0, len(specgram[0])])
    # # show axes in Hz and seconds
    # time_step = hop_s / float(samplerate)
    # total_time = len(specgram) * time_step
    # outstr = "total time: %0.2fs" % total_time
    # print(outstr + ", samplerate: %.2fkHz" % (samplerate / 1000.))
    # n_xticks = 10
    # n_yticks = 10

    # def get_rounded_ticks( top_pos, step, n_ticks ):
        # top_label = top_pos * step
        # # get the first label
        # ticks_first_label = top_pos * step / n_ticks
        # # round to the closest .1
        # ticks_first_label = round ( ticks_first_label * 10. ) / 10.
        # # compute all labels from the first rounded one
        # ticks_labels = [ ticks_first_label * n for n in range(n_ticks) ] + [ top_label ]
        # # get the corresponding positions
        # ticks_positions = [ ticks_labels[n] / step for n in range(n_ticks) ] + [ top_pos ]
        # # convert to string
        # ticks_labels = [  "%.1f" % x for x in ticks_labels ]
        # # return position, label tuple to use with x/yticks
        # return ticks_positions, ticks_labels

    # # apply to the axis
    # x_ticks, x_labels = get_rounded_ticks ( len(specgram), time_step, n_xticks )
    # y_ticks, y_labels = get_rounded_ticks ( len(specgram[0]), (samplerate / 1000. / 2.) / len(specgram[0]), n_yticks )
    # ax.set_xticks( x_ticks )
    # ax.set_yticks ( y_ticks )
    # ax.set_xticklabels( x_labels )
    # ax.set_yticklabels ( y_labels )
    # ax.set_ylabel('Frequency (kHz)')
    # ax.set_xlabel('Time (s)')
    # ax.set_title(os.path.basename(filename))
    # for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
            # ax.get_xticklabels() + ax.get_yticklabels()):
        # item.set_fontsize('x-small')
    # return fig

# if __name__ == '__main__':
    # if len(sys.argv) < 2:
        # print("Usage: %s <filename>" % sys.argv[0])
    # else:
        # for soundfile in sys.argv[1:]:
            # fig = get_spectrogram(soundfile)
            # # display graph
            # plt.show()
            # #outimage = os.path.basename(soundfile) + '.png'
            # #print ("writing: " + outimage)
            # #plt.savefig(outimage)
            # plt.close()

redpajama_set_name: RedPajamaGithub


text:
import {TestBed, ComponentFixture}  from '@angular/core/testing';
import {Component} from '@angular/core';
import {createGenericTestComponent} from '../../test/util/helpers';
import {NglIconsModule} from './module';
import {provideNglConfig} from '../config/config';

const createTestComponent = (html?: string, detectChanges?: boolean) =>
  createGenericTestComponent(TestComponent, html, detectChanges) as ComponentFixture<TestComponent>;

function getElements(element: Element) {
  const assistiveEl = element.querySelector('.slds-assistive-text');

  return {
    host: <HTMLElement>element.firstElementChild,
    icon: <SVGSVGElement>element.querySelector('svg'),
    assistiveText: assistiveEl ? assistiveEl.textContent.trim() : null,
  };
}

describe('Icon Component', () => {

  beforeEach(() => TestBed.configureTestingModule({
    declarations: [TestComponent],
    imports: [NglIconsModule],
    providers: [provideNglConfig({svgPath: '/mypath'})],
  }));

  it('should render all the icon elements', () => {
    const fixture = createTestComponent(`<ngl-icon icon="warning" alt="Help!"></ngl-icon>`);

    const { nativeElement } = fixture;
    const { host, icon, assistiveText } = getElements(nativeElement);
    const use = icon.querySelector('use');

    expect(host).not.toHaveCssClass('slds-icon_container');
    expect(icon).toHaveCssClass('slds-icon');
    expect(icon).not.toHaveCssClass('slds-icon-text-error');
    expect(icon).not.toHaveCssClass('slds-icon-text-warning');
    expect(icon).not.toHaveCssClass('slds-icon-text-default');
    expect(use.getAttribute('xlink:href')).toBe('/mypath/utility-sprite/svg/symbols.svg#warning');
    expect(assistiveText).toEqual('Help!');
  });

  it('should set type based on input', () => {
    const fixture = createTestComponent(`<ngl-icon icon="warning" [type]="type"></ngl-icon>`);
    const { nativeElement, componentInstance } = fixture;
    const { icon } = getElements(nativeElement);

    componentInstance.type = 'default';
    fixture.detectChanges();
    expect(icon).toHaveCssClass('slds-icon-text-default');
    expect(icon).not.toHaveCssClass('slds-icon-text-error');
    expect(icon).not.toHaveCssClass('slds-icon-text-warning');

    componentInstance.type = 'warning';
    fixture.detectChanges();
    expect(icon).toHaveCssClass('slds-icon-text-warning');
    expect(icon).not.toHaveCssClass('slds-icon-text-error');
    expect(icon).not.toHaveCssClass('slds-icon-text-default');

    componentInstance.type = 'error';
    fixture.detectChanges();
    expect(icon).toHaveCssClass('slds-icon-text-error');
    expect(icon).not.toHaveCssClass('slds-icon-text-warning');
    expect(icon).not.toHaveCssClass('slds-icon-text-default');

    componentInstance.type = 'false';
    fixture.detectChanges();
    expect(icon).not.toHaveCssClass('slds-icon-text-error');
    expect(icon).not.toHaveCssClass('slds-icon-text-warning');
    expect(icon).not.toHaveCssClass('slds-icon-text-default');
  });

  it('should set size based on input', () => {
    const fixture = createTestComponent(`<ngl-icon icon="warning" [size]="size"></ngl-icon>`);
    const { nativeElement, componentInstance } = fixture;
    const { icon } = getElements(nativeElement);
    expect(icon).toHaveCssClass('slds-icon--small');

    componentInstance.size = 'large';
    fixture.detectChanges();
    expect(icon).not.toHaveCssClass('slds-icon--small');
    expect(icon).toHaveCssClass('slds-icon--large');
  });

  it('should allow extra svg classes', () => {
    const fixture = createTestComponent(`<ngl-icon [svgClass]="svgClass"></ngl-icon>`);
    const { nativeElement, componentInstance } = fixture;
    const { icon } = getElements(nativeElement);
    expect(icon).toHaveCssClass('anextra');
    expect(icon).toHaveCssClass('fancy');
    expect(icon).toHaveCssClass('one');

    componentInstance.svgClass = ['another', 'one'];
    fixture.detectChanges();
    expect(icon).not.toHaveCssClass('anextra');
    expect(icon).not.toHaveCssClass('fancy');
    expect(icon).toHaveCssClass('one');
    expect(icon).toHaveCssClass('another');

    componentInstance.svgClass = null;
    fixture.detectChanges();
    expect(icon).not.toHaveCssClass('one');
    expect(icon).not.toHaveCssClass('another');
    expect(icon).toHaveCssClass('slds-icon');
  });

  it('should support sprite category', () => {
    const fixture = createTestComponent(`<ngl-icon [category]="type" icon="add"></ngl-icon>`);
    const { nativeElement, componentInstance } = fixture;

    componentInstance.type = 'standard';
    fixture.detectChanges();

    const { host, icon } = getElements(nativeElement);
    const use = icon.querySelector('use');

    expect(host).toHaveCssClass('slds-icon_container');
    expect(host).toHaveCssClass('slds-icon-standard-add');
    expect(icon).not.toHaveCssClass('slds-icon-text-default');
    expect(use.getAttribute('xlink:href')).toBe('/mypath/standard-sprite/svg/symbols.svg#add');

    componentInstance.type = 'utility';
    fixture.detectChanges();
    expect(host).not.toHaveCssClass('slds-icon_container');
    expect(host).not.toHaveCssClass('slds-icon-standard-add');
    expect(icon).not.toHaveCssClass('slds-icon-text-default');
    expect(use.getAttribute('xlink:href')).toBe('/mypath/utility-sprite/svg/symbols.svg#add');
  });

  it('should handle icons with underscore', () => {
    const fixture = createTestComponent(`<ngl-icon [category]="type" [icon]="icon"></ngl-icon>`);
    const { nativeElement, componentInstance } = fixture;

    componentInstance.type = 'standard';
    componentInstance.icon = 'work_order';
    fixture.detectChanges();

    const { host, icon } = getElements(nativeElement);
    const use = icon.querySelector('use');

    expect(host).toHaveCssClass('slds-icon-standard-work-order');
    expect(use.getAttribute('xlink:href')).toBe('/mypath/standard-sprite/svg/symbols.svg#work_order');
  });

  it('should handle custom icons', () => {
    const fixture = createTestComponent(`<ngl-icon category="custom" icon="1"></ngl-icon>`);
    const { host, icon } = getElements(fixture.nativeElement);
    const use = icon.querySelector('use');
    expect(host).toHaveCssClass('slds-icon-custom-custom1');
    expect(use.getAttribute('xlink:href')).toBe('/mypath/custom-sprite/svg/symbols.svg#custom1');
  });
});

@Component({
  template: '',
})
export class TestComponent {
  size = 'small';
  icon: string;
  type: string;
  svgClass: any = 'anextra fancy one';
}


text:
package net.s6team.aquarius.maajan;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author kamiya<kamiya.tips@gmail.com>
 */
public class MaajanSet {

	private List<Maajan> maajanList = new ArrayList<Maajan>();

	public List<Maajan> getMaajanList() {
		return maajanList;
	}
}


text:
package org.optaplanner.examples.cloudbalancing.app;

import java.io.File;

import org.junit.Test;
import org.optaplanner.core.config.solver.EnvironmentMode;
import org.optaplanner.examples.cloudbalancing.persistence.CloudBalancingDao;
import org.optaplanner.examples.common.app.SolverPerformanceTest;
import org.optaplanner.examples.common.persistence.SolutionDao;

public class CloudBalancingPerformanceTest extends SolverPerformanceTest {

    @Override
    protected String createSolverConfigResource() {
        return "/org/optaplanner/examples/cloudbalancing/solver/cloudBalancingSolverConfig.xml";
    }

    @Override
    protected SolutionDao createSolutionDao() {
        return new CloudBalancingDao();
    }

    // ************************************************************************
    // Tests
    // ************************************************************************

    @Test(timeout = 600000)
    public void solveModel_cb_0200comp_0600() {
        File unsolvedDataFile = new File("data/cloudbalancing/unsolved/cb-0200comp-0600proc.xml");
        runSpeedTest(unsolvedDataFile, "0hard/-218850soft");
    }

    @Test(timeout = 600000)
    public void solveModel_cb_0200comp_0600FastAssert() {
        File unsolvedDataFile = new File("data/cloudbalancing/unsolved/cb-0200comp-0600proc.xml");
        runSpeedTest(unsolvedDataFile, "0hard/-223260soft", EnvironmentMode.FAST_ASSERT);
    }

}


text:
from claripy import Annotation

class StackLocationAnnotation(Annotation):
    def __init__(self, offset):
        super(StackLocationAnnotation, self).__init__()

        self.offset = offset

    @property
    def eliminatable(self):
        return False

    @property
    def relocatable(self):
        return False

    def __hash__(self):
        return hash(('stack_location', self.offset))

    def __eq__(self, other):
        if not isinstance(other, StackLocationAnnotation):
            return False

        return self.offset == other.offset

class VariableSourceAnnotation(Annotation):
    def __init__(self, block_addr, stmt_idx, ins_addr):
        super(VariableSourceAnnotation, self).__init__()

        self.block_addr = block_addr
        self.stmt_idx = stmt_idx
        self.ins_addr = ins_addr

    @property
    def eliminatable(self):
        return False

    @property
    def relocatable(self):
        return False

    def __hash__(self):
        return hash((self.block_addr, self.stmt_idx, self.ins_addr))

    def __eq__(self, other):
        if not isinstance(other, VariableSourceAnnotation):
            return False

        return self.block_addr == other.block_addr and \
               self.stmt_idx == other.stmt_idx and \
               self.ins_addr == other.ins_addr

    @staticmethod
    def from_state(state):
        return VariableSourceAnnotation(state.scratch.bbl_addr, state.scratch.stmt_idx, state.scratch.ins_addr)


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

var moduleExports = {};

//源文件根目录
moduleExports.staticRootDir = path.resolve(__dirname, '../../'); // 项目根目录
moduleExports.srcRootDir = path.resolve(moduleExports.staticRootDir, './src'); // 项目业务代码根目录
moduleExports.vendorDir = path.resolve(moduleExports.staticRootDir, './vendor'); // 存放所有不能用npm管理的第三方库

moduleExports.pagesDir = path.resolve(moduleExports.srcRootDir, './views'); // 存放各个页面独有的部分,如入口文件、只有该页面使用到的css、模板文件等

// 生成文件目录
moduleExports.buildDir = path.resolve(moduleExports.staticRootDir, './build'); // 存放编译后生成的所有代码、资源(图片、字体等,虽然只是简单的从源目录迁移过来)

module.exports = moduleExports;


text:
var buttonX = 100
var buttonY = 75
var buttonWidth = 100
var buttonHeight = 50
var buttonLabel = 'click me'

function setup() {

  createCanvas(1000, 500)

}

function draw() {

  background(255)

  rect(buttonX, buttonY, buttonWidth, buttonHeight)       // anything inside this rectangle will count as a
                                                          // click on the button

  textSize(20)
  textAlign(CENTER, CENTER)      // this affects both the horizontal and vertical alignment of the text

  text(buttonLabel, buttonX, buttonY, buttonWidth, buttonHeight)
}

function mouseReleased(){

    // check if the mouse is over the button
    // it counts as being over the button if the following four statements are true:
    //           mouseX > buttonX
    //           mouseX < (buttonX + buttonWidth)
    //           mouseY > buttonY
    //           mouseY < (buttonY + buttonHeight)

    // and the syntax for that is:

    if( (mouseX > buttonX) &&
        (mouseX < (buttonX + buttonWidth)) &&
        (mouseY > buttonY) &&
        (mouseY < (buttonY + buttonHeight))){

        buttonLabel = 'clicked'

    }

    // the brackets can be hard to keep track of in a large statement like this!
    // unfortunately there's not a lot we can do to simplify it...

}


text:
package google

import "fmt"

// Provide a separate asset type constant so we don't have to worry about name conflicts between IAM and non-IAM converter files
const DataCatalogEntryGroupIAMAssetType string = "datacatalog.googleapis.com/EntryGroup"

func resourceConverterDataCatalogEntryGroupIamPolicy() ResourceConverter {
	return ResourceConverter{
		AssetType:         DataCatalogEntryGroupIAMAssetType,
		Convert:           GetDataCatalogEntryGroupIamPolicyCaiObject,
		MergeCreateUpdate: MergeDataCatalogEntryGroupIamPolicy,
	}
}

func resourceConverterDataCatalogEntryGroupIamBinding() ResourceConverter {
	return ResourceConverter{
		AssetType:         DataCatalogEntryGroupIAMAssetType,
		Convert:           GetDataCatalogEntryGroupIamBindingCaiObject,
		FetchFullResource: FetchDataCatalogEntryGroupIamPolicy,
		MergeCreateUpdate: MergeDataCatalogEntryGroupIamBinding,
		MergeDelete:       MergeDataCatalogEntryGroupIamBindingDelete,
	}
}

func resourceConverterDataCatalogEntryGroupIamMember() ResourceConverter {
	return ResourceConverter{
		AssetType:         DataCatalogEntryGroupIAMAssetType,
		Convert:           GetDataCatalogEntryGroupIamMemberCaiObject,
		FetchFullResource: FetchDataCatalogEntryGroupIamPolicy,
		MergeCreateUpdate: MergeDataCatalogEntryGroupIamMember,
		MergeDelete:       MergeDataCatalogEntryGroupIamMemberDelete,
	}
}

func GetDataCatalogEntryGroupIamPolicyCaiObject(d TerraformResourceData, config *Config) ([]Asset, error) {
	return newDataCatalogEntryGroupIamAsset(d, config, expandIamPolicyBindings)
}

func GetDataCatalogEntryGroupIamBindingCaiObject(d TerraformResourceData, config *Config) ([]Asset, error) {
	return newDataCatalogEntryGroupIamAsset(d, config, expandIamRoleBindings)
}

func GetDataCatalogEntryGroupIamMemberCaiObject(d TerraformResourceData, config *Config) ([]Asset, error) {
	return newDataCatalogEntryGroupIamAsset(d, config, expandIamMemberBindings)
}

func MergeDataCatalogEntryGroupIamPolicy(existing, incoming Asset) Asset {
	existing.IAMPolicy = incoming.IAMPolicy
	return existing
}

func MergeDataCatalogEntryGroupIamBinding(existing, incoming Asset) Asset {
	return mergeIamAssets(existing, incoming, mergeAuthoritativeBindings)
}

func MergeDataCatalogEntryGroupIamBindingDelete(existing, incoming Asset) Asset {
	return mergeDeleteIamAssets(existing, incoming, mergeDeleteAuthoritativeBindings)
}

func MergeDataCatalogEntryGroupIamMember(existing, incoming Asset) Asset {
	return mergeIamAssets(existing, incoming, mergeAdditiveBindings)
}

func MergeDataCatalogEntryGroupIamMemberDelete(existing, incoming Asset) Asset {
	return mergeDeleteIamAssets(existing, incoming, mergeDeleteAdditiveBindings)
}

func newDataCatalogEntryGroupIamAsset(
	d TerraformResourceData,
	config *Config,
	expandBindings func(d TerraformResourceData) ([]IAMBinding, error),
) ([]Asset, error) {
	bindings, err := expandBindings(d)
	if err != nil {
		return []Asset{}, fmt.Errorf("expanding bindings: %v", err)
	}

	name, err := assetName(d, config, "//datacatalog.googleapis.com/projects/{{project}}/locations/{{region}}/entryGroups/{{entry_group}}")
	if err != nil {
		return []Asset{}, err
	}

	return []Asset{{
		Name: name,
		Type: DataCatalogEntryGroupIAMAssetType,
		IAMPolicy: &IAMPolicy{
			Bindings: bindings,
		},
	}}, nil
}

func FetchDataCatalogEntryGroupIamPolicy(d TerraformResourceData, config *Config) (Asset, error) {
	// Check if the identity field returns a value
	if _, ok := d.GetOk("region"); !ok {
		return Asset{}, ErrEmptyIdentityField
	}
	if _, ok := d.GetOk("entry_group"); !ok {
		return Asset{}, ErrEmptyIdentityField
	}

	return fetchIamPolicy(
		DataCatalogEntryGroupIamUpdaterProducer,
		d,
		config,
		"//datacatalog.googleapis.com/projects/{{project}}/locations/{{region}}/entryGroups/{{entry_group}}",
		DataCatalogEntryGroupIAMAssetType,
	)
}


text:
package org.jglrxavpok.shady.gui;

import java.io.IOException;

import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.resources.I18n;

import org.jglrxavpok.shady.shaders.PassRegistry;

public class GuiSelectPassType extends GuiScreen
{

    private static final int BACK_BUTTON = 0;
    private static final int ADD_BUTTON  = 1;
    private GuiEditPass      parent;
    private GuiPassTypeList  typeList;
    private GuiButton        addButton;

    public GuiSelectPassType(GuiEditPass parent)
    {
        this.parent = parent;
    }

    @SuppressWarnings("unchecked")
    public void initGui()
    {
        buttonList.clear();

        typeList = new GuiPassTypeList(mc, 20, 30, width, height, 15);

        for(String id : PassRegistry.getAllIDs())
        {
            typeList.addEntry(new PassTypeEntry(fontRendererObj, id));
        }

        typeList.sort();

        buttonList.add(new GuiButton(BACK_BUTTON, width / 2 + 5, height - height / 8, I18n.format("gui.back")));
        addButton = new GuiButton(ADD_BUTTON, width / 2 - 200 - 5, height - height / 8, I18n.format("shady.select"));
        buttonList.add(addButton);
    }

    public void handleMouseInput() throws IOException
    {
        super.handleMouseInput();
        this.typeList.handleMouseInput();
    }

    protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException
    {
        if(mouseButton != 0 || !this.typeList.mouseClicked(mouseX, mouseY, mouseButton))
        {
            super.mouseClicked(mouseX, mouseY, mouseButton);
        }
    }

    protected void mouseReleased(int mouseX, int mouseY, int state)
    {
        if(state != 0 || !this.typeList.mouseReleased(mouseX, mouseY, state))
        {
            super.mouseReleased(mouseX, mouseY, state);
        }
    }

    public void updateScreen()
    {
        super.updateScreen();
        addButton.enabled = typeList.getSelectedIndex() != -1;
    }

    public void actionPerformed(GuiButton button)
    {
        if(button.id == ADD_BUTTON)
        {
            parent.confirmType(typeList.getSelected().getType());
            mc.displayGuiScreen(parent);
        }
        else if(button.id == BACK_BUTTON)
        {
            mc.displayGuiScreen(parent);
        }
        else
            typeList.actionPerformed(button);
    }

    public void drawScreen(int mx, int my, float partialTicks)
    {
        typeList.drawScreen(mx, my, partialTicks);
        super.drawScreen(mx, my, partialTicks);
        drawCenteredString(fontRendererObj, I18n.format("shady.select.passtype.title"), width / 2, 10, 0xFFFFFFFF);
    }

}


text:
Executes a `function` on every element of the Array. It returns a new Array that contains only the elements for which the provided `function` returned `true`.

Example:
```
var myArray = [5, 6, 1, 2, 10];

var filteredArray = myArray.filter(function(num) {
    return num > 3; // Returns true only if the number is greater than 3
});

// filteredArray is [5, 6, 10]
```

#### .forEach(callback) ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach))
Allows to execute a `function` on each and every element of the Array.

Example:
```
var myArray = ['Mickey', 'Goofy', 'Donald'];

myArray.forEach(function(name) {
   console.log('Hello' + name);
};

// Console Output
Hello Mickey
Hello Goofy
Hello Donald
```

#### .push(element) ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push))
Appends an element at the end of the Array.

Example:
```
var myArray = [20, 100, 30];

myArray.push(50);

// myArray is now [20, 100, 30, 50]
```

## Event

#### .target ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/API/Event/target))
Returns the element on which the event was captured.

#### .preventDefault() ([see in MDN](https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault))
Cancels the default event behavior.

## String

#### .replace(pattern, replacement) ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace))
Returns a copy of the String with the given _pattern_ replaced with another String.

Example:
```
var myString = 'This and that';

var newString = myString.replace('and', 'or');

// newString is 'This or that'
```

#### .trim() ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim))
Returns the original String without the whitespaces that it might have at the beginning or at the end.

Example:
```
var myString = '    Chocolate  ';

var newString = myString.trim();

// newString is 'Chocolate'
```

## JSON

#### .parse(jsonString) ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse))
Converts a JSON string into a Javascript Object.

```
var myObject = JSON.parse('{"type": "door", "state": "open"}');

// myObject is { type: 'door', state: 'open' }
```

#### .stringify(object) ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify))
Converts a Javascript Object into a JSON string.

```
var myObject = { type: 'door', state: 'open' };
var jsonString = JSON.stringify(myObject);

// jsonString is '{"type":"door","state":"open"}'
```

## document

#### .querySelector(cssSelector) ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector))
Returns the first element that matches the provided CSS selector.

Example:
```
// HTML
<div class="container">
   <div id="myElement">
      <span>Hello!</span>
   </div>
</div>

// Javascript
var myElement = document.querySelector('#myElement');

// myElement contains a reference to <div id="myElement"></div>
```

## Element

#### .innerHTML ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML))
Returns the HTML contained inside an Element. It can be set to a new value.

Example:
```
// HTML
<div id="myElement">
  <span>Hello!</span>
</div>

// Javascript
var myElement = document.querySelector('#myElement');

// myElement.innerHTML returns '<span>Hello!</span>'

myElement.innerHTML = '<div>Something else</div>';

// Now the HTML is this:
<div id="myElement">
  <div>Something else</div>
</div>
```

#### .previousElementSibling ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/previousElementSibling))
Returns the Element before the selected one.

Example:
```
// HTML
<div class="container">
   <span>One</span>
   <span class="selected">Two</span>
   <span>Three</span>
</div>

// Javascript
var selected = document.querySelector('.selected');
var previous = selected.previousElementSibling;

// previous is <span>One</span>
```

#### .dataset ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset))
Returns the map of the `data-` attributes of the selected element.

Example:
```
// HTML
<div id="myElement" data-type="door" data-state="open"></div>

// Javascript
var door = document.querySelector('#myElement');
var dataSet = door.dataset;

// dataSet is { type: 'door', state: 'open' }
```

## <input>

#### .value ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input))
Returns or sets the value of the input field.

## console

#### .log(text) ([see in MDN](https://developer.mozilla.org/en-US/docs/Web/API/Console/log))
Writes a message in the browser's console.


text:
import rospy
import sys

from socket import error
from twisted.internet import reactor
from rosbridge_server import RosbridgeUdpSocket,RosbridgeUdpFactory
def shutdown_hook():
    reactor.stop()
if __name__ == "__main__":
    rospy.init_node("rosbridge_websocket")
    rospy.on_shutdown(shutdown_hook)    # register shutdown hook to stop the server

    ##################################################
    # Parameter handling                             #
    ##################################################
     # get RosbridgeProtocol parameters
    RosbridgeUdpSocket.fragment_timeout = rospy.get_param('~fragment_timeout',
                                                          RosbridgeUdpSocket.fragment_timeout)
    RosbridgeUdpSocket.delay_between_messages = rospy.get_param('~delay_between_messages',
                                                                RosbridgeUdpSocket.delay_between_messages)
    RosbridgeUdpSocket.max_message_size = rospy.get_param('~max_message_size',
                                                          RosbridgeUdpSocket.max_message_size)
    if RosbridgeUdpSocket.max_message_size == "None":
        RosbridgeUdpSocket.max_message_size = None

    # if authentication should be used
    RosbridgeUdpSocket.authenticate = rospy.get_param('~authenticate', False)
    port = rospy.get_param('~port', 9090)
    interface = rospy.get_param('~interface', "")

    if "--port" in sys.argv:
        idx = sys.argv.index("--port")+1
        if idx < len(sys.argv):
            port = int(sys.argv[idx])
        else:
            print "--port argument provided without a value."
            sys.exit(-1)

    if "--interface" in sys.argv:
        idx = sys.argv.index("--interface")+1
        if idx < len(sys.argv):
            interface = int(sys.argv[idx])
        else:
            print "--interface argument provided without a value."
            sys.exit(-1)

    if "--fragment_timeout" in sys.argv:
        idx = sys.argv.index("--fragment_timeout") + 1
        if idx < len(sys.argv):
            RosbridgeUdpSocket.fragment_timeout = int(sys.argv[idx])
        else:
            print "--fragment_timeout argument provided without a value."
            sys.exit(-1)

    if "--delay_between_messages" in sys.argv:
        idx = sys.argv.index("--delay_between_messages") + 1
        if idx < len(sys.argv):
            RosbridgeUdpSocket.delay_between_messages = float(sys.argv[idx])
        else:
            print "--delay_between_messages argument provided without a value."
            sys.exit(-1)

    if "--max_message_size" in sys.argv:
        idx = sys.argv.index("--max_message_size") + 1
        if idx < len(sys.argv):
            value = sys.argv[idx]
            if value == "None":
                RosbridgeUdpSocket.max_message_size = None
            else:
                RosbridgeUdpSocket.max_message_size = int(value)
        else:
            print "--max_message_size argument provided without a value. (can be None or <Integer>)"
            sys.exit(-1)

    ##################################################
    # Done with parameter handling                   #
    ##################################################

    rospy.loginfo("Rosbridge UDP server started on port %d", port)
    reactor.listenUDP(port, RosbridgeUdpFactory(), interface=interface)
    reactor.run()


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>anonymous type on A Developer's Experience</title>
    <link>/tags/anonymous-type/</link>
    <description>Recent content in anonymous type on A Developer's Experience</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <lastBuildDate>Mon, 24 Aug 2015 01:10:27 +0000</lastBuildDate><atom:link href="/tags/anonymous-type/index.xml" rel="self" type="application/rss+xml" />
    <item>
      <title>An Unfair World of Tuples, Anons., var and auto</title>
      <link>/2015/08/24/tuples-anons/</link>
      <pubDate>Mon, 24 Aug 2015 01:10:27 +0000</pubDate>

      <guid>/2015/08/24/tuples-anons/</guid>
      <description>
It all began when I wanted to return more than one value from one of the methods. Although my attempts ended futile, it was fun exploring and musing how things could have been.

There are at least a couple of options to return multiple values from a method:-

return an instance of a class that holds the values

return a tuple

</description>
    </item>

  </channel>
</rss>


text:
<?xml version="1.0" standalone="no"?>

<!DOCTYPE caldavtest SYSTEM "caldavtest.dtd">

<!--
 Copyright (c) 2013-2015 Apple Inc. All rights reserved.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 -->

<caldavtest>
	<description>Tests a bunch of bad data</description>

	<require-feature>
		<feature>caldav</feature>
	</require-feature>

	<start/>

	<test-suite name='PUT'>
		<test name='1'>
			<description>PUT bad calendar data</description>
			<request iterate-data="yes">
				<method>PUT</method>
				<ruri>$calendarpath1:/**</ruri>
				<data>
					<content-type>text/calendar; charset=utf-8</content-type>
					<filepath>Resource/CalDAV/bad-ical</filepath>
				</data>
				<verify>
					<callback>statusCode</callback>
					<arg>
						<name>status</name>
						<value>4xx</value>
					</arg>
				</verify>
			</request>
		</test>
	</test-suite>
	<end/>

</caldavtest>


text:
<?php

/**
 * Test cases for @{class:ArcanistSpellingLinter}.
 *
 * @group testcase
 */
final class ArcanistSpellingLinterTestCase
  extends ArcanistArcanistLinterTestCase {

  public function testSpellingLint() {
    $linter = new ArcanistSpellingLinter();
    $linter->removeLintRule('acc'.'out');
    $linter->addPartialWordRule('supermn', 'superman');
    $linter->addWholeWordRule('batmn', 'batman');
    $working_copy = ArcanistWorkingCopyIdentity::newFromPath(__FILE__);
    return $this->executeTestsInDirectory(
      dirname(__FILE__).'/spelling/',
      $linter,
      $working_copy);
  }

  public function testFixLetterCase() {
    $tests = array(
      'tst' => 'test',
      'Tst' => 'Test',
      'TST' => 'TEST',
      'tSt' => null,
    );
    foreach ($tests as $case => $expect) {
      foreach (array('test', 'TEST') as $string) {
        $result = ArcanistSpellingLinter::fixLetterCase($string, $case);
        $this->assertEqual($expect, $result, $case);
      }
    }
  }

}


text:
import sys

def dump_threads() -> None:
    import threading
    import traceback

    for th in threading.enumerate():
        print(th)
        if th.ident:
            traceback.print_stack(sys._current_frames()[th.ident])
        print()


text:
package com.streamsets.pipeline.stage.destination.hbase;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import com.streamsets.pipeline.api.Batch;
import com.streamsets.pipeline.api.ExecutionMode;
import com.streamsets.pipeline.api.Field;
import com.streamsets.pipeline.api.Field.Type;
import com.streamsets.pipeline.api.OnRecordError;
import com.streamsets.pipeline.api.Record;
import com.streamsets.pipeline.api.Stage;
import com.streamsets.pipeline.api.Stage.ConfigIssue;
import com.streamsets.pipeline.api.StageException;
import com.streamsets.pipeline.api.Target;
import com.streamsets.pipeline.api.impl.Utils;
import com.streamsets.pipeline.lib.hbase.common.Errors;
import com.streamsets.pipeline.lib.hbase.common.HBaseConnectionConfig;
import com.streamsets.pipeline.lib.util.JsonUtil;
import com.streamsets.pipeline.sdk.ContextInfoCreator;
import com.streamsets.pipeline.sdk.RecordCreator;
import com.streamsets.pipeline.sdk.TargetRunner;
import com.streamsets.pipeline.stage.common.hbase.HBaseTestUtil;
import com.streamsets.testing.SingleForkNoReuseTest;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
import org.apache.hadoop.security.UserGroupInformation;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.UUID;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

@Category(SingleForkNoReuseTest.class)
public class HBaseTargetIT {
  private static final Logger LOG = LoggerFactory.getLogger(HBaseTargetIT.class);
  private static HBaseTestingUtility utility;
  private static MiniZooKeeperCluster miniZK;
  private static final String tableName = "TestHBaseSink";
  private static final String familyName = "cf";
  private static final Configuration conf = HBaseTestUtil.getHBaseTestConfiguration();

  @BeforeClass
  public static void setUpBeforeClass() throws Exception {
    try {
      UserGroupInformation.createUserForTesting("foo", new String[]{"all"});
      utility = new HBaseTestingUtility(conf);
      utility.startMiniCluster();
      miniZK = utility.getZkCluster();
      HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(tableName));
      HColumnDescriptor hcd = new HColumnDescriptor(familyName);
      hcd.setMaxVersions(HConstants.ALL_VERSIONS);
      htd.addFamily(hcd);
      utility.getHBaseAdmin().createTable(htd);
    } catch (Throwable throwable) {
      LOG.error("Error in startup: " + throwable, throwable);
      throw throwable;
    }
  }

  @AfterClass
  public static void tearDown() throws Exception {
    try {
      utility.getHBaseAdmin().disableTable(tableName);
      utility.getHBaseAdmin().deleteTable(tableName);
    } finally {
      utility.shutdownMiniCluster();
    }
  }

  @Test(timeout=60000)
  public void validateNoConfigIssues() throws Exception {
    HBaseDTarget dTarget = new ForTestHBaseTarget();
    configure(dTarget);
    HBaseTarget target = (HBaseTarget) dTarget.createTarget();

    TargetRunner targetRunner =
        new TargetRunner.Builder(HBaseDTarget.class, target)
            .setOnRecordError(OnRecordError.DISCARD).build();
    assertTrue(targetRunner.runValidateConfigs().isEmpty());
  }

  @Test(timeout=60000)
  public void testInvalidConfigs() throws Exception {
    HBaseDTarget dTarget = new ForTestHBaseTarget();
    configure(dTarget);
    dTarget.hBaseConnectionConfig.zookeeperQuorum = "";
    dTarget.hBaseConnectionConfig.clientPort = 0;
    dTarget.hBaseConnectionConfig.zookeeperParentZnode = "";
    dTarget.timeDriver = "${time:now()}";
    HBaseTarget target = (HBaseTarget) dTarget.createTarget();

    TargetRunner runner = new TargetRunner.Builder(HBaseDTarget.class, target)
        .setOnRecordError(OnRecordError.STOP_PIPELINE)
        .build();

    List<Stage.ConfigIssue> issues = runner.runValidateConfigs();
    Assert.assertEquals(3, issues.size());
    assertTrue(issues.get(0).toString().contains("HBASE_04"));
    assertTrue(issues.get(1).toString().contains("HBASE_09"));
    assertTrue(issues.get(2).toString().contains("HBASE_13"));

    configure(dTarget);
    dTarget.hBaseConnectionConfig.tableName = "NonExistingTable";
    target = (HBaseTarget) dTarget.createTarget();
    runner = new TargetRunner.Builder(HBaseDTarget.class, target)
        .setOnRecordError(OnRecordError.STOP_PIPELINE)
        .build();
    issues = runner.runValidateConfigs();
    Assert.assertEquals(1, issues.size());
    assertTrue(issues.get(0).toString().contains("HBASE_07"));

    configure(dTarget);
    dTarget.hBaseConnectionConfig.zookeeperQuorum = "127.0.0.1, dummy, dummyyy ";
    target = (HBaseTarget) dTarget.createTarget();
    runner = new TargetRunner.Builder(HBaseDTarget.class, target)
        .setOnRecordError(OnRecordError.STOP_PIPELINE)
        .build();
    issues = runner.runValidateConfigs();
    Assert.assertEquals(2, issues.size());
    assertTrue(issues.get(0).toString().contains("HBASE_39"));
    assertTrue(issues.get(0).toString().contains("dummy"));
    assertTrue(issues.get(1).toString().contains("HBASE_39"));
    assertTrue(issues.get(1).toString().contains("dummyyy"));

    dTarget.hBaseConnectionConfig.zookeeperQuorum = " 127.0.0.1, 127.0.0.1, 127.0.0.1 ";
    target = (HBaseTarget) dTarget.createTarget();
    runner = new TargetRunner.Builder(HBaseDTarget.class, target)
        .setOnRecordError(OnRecordError.STOP_PIPELINE)
        .build();
    assertEquals(0, runner.runValidateConfigs().size());
  }

  @Test(timeout=60000)
  public void getGetHBaseConfiguration() throws Exception {
    HBaseDTarget dTarget = new ForTestHBaseTarget();
    configure(dTarget);
    HBaseTarget target = (HBaseTarget) dTarget.createTarget();
    try {
      target.init(null,
                  ContextInfoCreator.createTargetContext("n", false, OnRecordError.TO_ERROR));
      assertNotNull(target.getHBaseConfiguration());
    } finally {
      target.destroy();
    }
  }

  @Test(timeout=60000)
  public void testHBaseConfigs() throws Exception {
    HBaseDTarget dTarget = new ForTestHBaseTarget();
    configure(dTarget);
    HBaseTarget target = (HBaseTarget) dTarget.createTarget();
    try {
      target.init(null,
                  ContextInfoCreator.createTargetContext("n", false, OnRecordError.TO_ERROR));
      assertEquals("X", target.getHBaseConfiguration().get("x"));
    } finally {
      target.destroy();
    }
  }

  @Test(timeout=60000)
  public void testSingleRecordTextStorage() throws InterruptedException, StageException,
      IOException {
    List<HBaseFieldMappingConfig> fieldMappings =
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.TEXT),
          new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.TEXT),
          new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.TEXT),
          new HBaseFieldMappingConfig("cf:d", "[4]", StorageType.TEXT));

    Date d = new Date();

    TargetRunner targetRunner = buildRunner(fieldMappings, StorageType.TEXT, OnRecordError.DISCARD, "", false, "[0]", false, false);
    Record record = RecordCreator.create();
    List<Field> fields = new ArrayList<>();
    String rowKey = "row_key";
    fields.add(Field.create(rowKey));
    fields.add(Field.create(Type.LONG, 20));
    fields.add(Field.create(Type.DATE, d));
    fields.add(Field.create(Type.TIME, d));
    fields.add(Field.create(Type.DATETIME, d));
    record.set(Field.create(fields));

    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);
    targetRunner.runDestroy();

    HTable htable = new HTable(conf, tableName);

    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertEquals("20", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("a"))));
    assertEquals(d.toString(), Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("b"))));
    assertEquals(d.toString(), Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("c"))));
    assertEquals(d.toString(), Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("d"))));

  }

  @Test(timeout = 600000)
  public void testOnlyImplicitFieldMapping() throws Exception {
    String rowKeyFieldPath = "/row_key";
    String rowKey = "testOnlyImplicitFieldMapping";
    TargetRunner targetRunner =
      buildRunner(new ArrayList<HBaseFieldMappingConfig>(), StorageType.TEXT, OnRecordError.DISCARD, "", true, rowKeyFieldPath, false, false);
    Record record = RecordCreator.create();
    LinkedHashMap<String, Field> map = new LinkedHashMap<>();
    map.put("cf:a", Field.create("value_a"));
    map.put("cf:b", Field.create("value_b"));
    map.put(rowKeyFieldPath.substring(1), Field.create(rowKey));
    Field mapField = Field.createListMap(map);
    record.set(mapField);
    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);
    targetRunner.runDestroy();
    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertEquals("value_a", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("a"))));
    assertEquals("value_b", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("b"))));
  }

  @Test(timeout = 60000)
  public void testFieldMappings() throws Exception {
    String rowKeyFieldPath = "/row_key";
    String rowKey = "testFieldMappings";
    List<HBaseFieldMappingConfig> fieldMappings =
      ImmutableList.of(new HBaseFieldMappingConfig("cf:explicit", "/explicit", StorageType.TEXT));
    TargetRunner targetRunner = buildRunner(fieldMappings, StorageType.TEXT, OnRecordError.DISCARD, "", true, rowKeyFieldPath, false, false);
    Record record = RecordCreator.create();
    Map<String, Field> map = new HashMap<>();
    map.put("cf:a", Field.create("value_a"));
    map.put(rowKeyFieldPath.substring(1), Field.create(rowKey));
    map.put("cf:b", Field.create("value_b"));
    map.put("explicit", Field.create("explicitValue"));
    Field mapField = Field.create(map);
    record.set(mapField);
    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);
    targetRunner.runDestroy();

    HTable htable = new HTable(conf, tableName);

    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertEquals("value_a", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("a"))));
    assertEquals("value_b", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("b"))));
    assertEquals("explicitValue", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("explicit"))));
  }

  @Test(timeout = 60000)
  public void testFieldMappingIgnoreInvalidColumn() throws Exception {
    String rowKeyFieldPath = "/row_key";
    String rowKey = "testFieldMappingIgnoreOnError";
    List<HBaseFieldMappingConfig> fieldMappings =
      ImmutableList.of(new HBaseFieldMappingConfig("cf:explicit", "/explicit", StorageType.TEXT));
    TargetRunner targetRunner = buildRunner(fieldMappings, StorageType.TEXT, OnRecordError.DISCARD, "", true, rowKeyFieldPath, false, true);
    Record record = RecordCreator.create();
    Map<String, Field> map = new HashMap<>();
    Map<String, Field> dummyInnerMap = new HashMap<>();
    dummyInnerMap.put("f1", Field.create("abc"));
    // some invalid fieldpath as it cannot be mapped to column
    map.put("mymap", Field.create(dummyInnerMap));
    map.put("cf:a", Field.create("value_a"));
    map.put(rowKeyFieldPath.substring(1), Field.create(rowKey));
    map.put("cf:b", Field.create("value_b"));
    // some invalid fieldpath as it cannot be mapped to column
    map.put("dummy", Field.create("value_b"));
    map.put("explicit", Field.create("explicitValue"));
    Field mapField = Field.create(map);
    record.set(mapField);
    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);
    targetRunner.runDestroy();

    HTable htable = new HTable(conf, tableName);

    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertEquals("value_a", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("a"))));
    assertEquals("value_b", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("b"))));
    assertEquals("explicitValue", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("explicit"))));
  }

  @Test(timeout = 60000)
  public void testFieldMappingNotIgnoreInvalidColumn() throws Exception {
    String rowKeyFieldPath = "/row_key";
    String rowKey = "testAllFieldMappingError";
    List<HBaseFieldMappingConfig> fieldMappings =
      ImmutableList.of(new HBaseFieldMappingConfig("cf:explicit", "/explicit", StorageType.TEXT));
    TargetRunner targetRunner = buildRunner(fieldMappings, StorageType.TEXT, OnRecordError.TO_ERROR, "", true, rowKeyFieldPath, true, false);
    Record record = RecordCreator.create();
    Map<String, Field> map = new HashMap<>();
    Map<String, Field> dummyInnerMap = new HashMap<>();
    dummyInnerMap.put("f1", Field.create("abc"));
    map.put("mymap", Field.create(dummyInnerMap));
    map.put(rowKeyFieldPath.substring(1), Field.create(rowKey));
    map.put("dummy", Field.create("value_b"));
    Field mapField = Field.create(map);
    record.set(mapField);
    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);
    assertEquals(1, targetRunner.getErrorRecords().size());
    assertEquals(record.getHeader().getSourceId(), targetRunner.getErrorRecords().get(0).getHeader().getSourceId());
    assertTrue(targetRunner.getErrors().isEmpty());
    targetRunner.runDestroy();

    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertTrue(r.isEmpty());

  }

  @Test
  public void testWriteWrongColumn() throws Exception {
    String rowKeyFieldPath = "/row_key";
    String rowKey = "testWriteWrongColumn";
    TargetRunner targetRunner = buildRunner(new ArrayList<HBaseFieldMappingConfig>(), StorageType.TEXT,  OnRecordError.TO_ERROR, "", true, rowKeyFieldPath, true, false);
    Record record = RecordCreator.create();
    Map<String, Field> map = new HashMap<>();
    map.put("invalidcf:a", Field.create("value_a"));
    map.put("cf:b", Field.create("value_b"));
    map.put(rowKeyFieldPath.substring(1), Field.create(rowKey));
    record.set(Field.create(map));
    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);
    assertEquals(1, targetRunner.getErrorRecords().size());
    assertEquals(record.getHeader().getSourceId(), targetRunner.getErrorRecords().get(0).getHeader().getSourceId());
    assertTrue(targetRunner.getErrors().isEmpty());
    targetRunner.runDestroy();

    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertTrue(r.isEmpty());

  }

  @Test
  public void testInvalidRowKey() throws Exception {
    String rowKeyFieldPath = "/row_key";
    TargetRunner targetRunner = buildRunner(new ArrayList<HBaseFieldMappingConfig>(), StorageType.TEXT,  OnRecordError.TO_ERROR, "", true, rowKeyFieldPath, true, false);

    Record record1 = RecordCreator.create();
    Map<String, Field> map = new HashMap<>();
    map.put("cf:a", Field.create("value_a"));
    map.put("cf:b", Field.create("value_b"));
    map.put(rowKeyFieldPath.substring(1), Field.create(""));
    record1.set(Field.create(map));

    Record record2 = RecordCreator.create();
    map = new HashMap<>();
    map.put("cf:a", Field.create("value_a"));
    map.put("cf:b", Field.create("value_b"));
    record2.set(Field.create(map));

    List<Record> records = ImmutableList.of(record1, record2);
    targetRunner.runInit();
    targetRunner.runWrite(records);
    assertEquals(2, targetRunner.getErrorRecords().size());
    assertEquals(Errors.HBASE_35.getCode(), targetRunner.getErrorRecords().get(0).getHeader().getErrorCode());
    assertEquals(Errors.HBASE_27.getCode(), targetRunner.getErrorRecords().get(1).getHeader().getErrorCode());
    targetRunner.runDestroy();
  }

  @Test(timeout = 60000)
  public void testNotFlatMap() throws Exception {
    String rowKeyFieldPath = "/row_key";
    String rowKey = "testNotFlatMapError";
    TargetRunner targetRunner =
      buildRunner(new ArrayList<HBaseFieldMappingConfig>(), StorageType.TEXT, OnRecordError.DISCARD, "", true, rowKeyFieldPath, false, false);
    Record record = RecordCreator.create();
    Map<String, Field> map = new HashMap<>();
    map.put("cf:a", Field.create("value_a"));
    map.put("cf:b", Field.create("value_b"));
    map.put("cf:c", Field.create(ImmutableMap.of("key_1", Field.create(60), "key_2", Field.create(70))));
    map.put(rowKeyFieldPath.substring(1), Field.create(rowKey));
    Field mapField = Field.create(map);
    record.set(mapField);
    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);
    targetRunner.runDestroy();
    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertTrue(!r.isEmpty());
    assertEquals("value_a", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("a"))));
    assertEquals("value_b", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("b"))));
    Field field = JsonUtil.bytesToField(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("c")));
    assertTrue(field.getType() == Type.MAP);
    map = field.getValueAsMap();
    assertEquals(60, map.get("key_1").getValueAsInteger());
    assertEquals(70, map.get("key_2").getValueAsInteger());
  }

  @Test(timeout = 60000)
  public void testNotMapError() throws Exception {
    String rowKey = "testNotMapError";
    TargetRunner targetRunner =
      buildRunner(new ArrayList<HBaseFieldMappingConfig>(), StorageType.TEXT, OnRecordError.TO_ERROR, "", true, "[0]", false, true);
    Record record = RecordCreator.create();
    List<Field> fields = new ArrayList<Field>();
    fields.add(Field.create(rowKey));
    fields.add(Field.create("20"));
    record.set(Field.create(fields));
    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);
    assertEquals(1, targetRunner.getErrorRecords().size());
    assertEquals(record.getHeader().getSourceId(), targetRunner.getErrorRecords().get(0).getHeader().getSourceId());
    assertTrue(targetRunner.getErrors().isEmpty());
    targetRunner.runDestroy();
    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertTrue(r.isEmpty());
  }

  @Test(timeout=60000)
  public void testSingleRecordBinaryStorage() throws InterruptedException, StageException,
      IOException {
    List<HBaseFieldMappingConfig> fieldMappings =
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.BINARY),
          new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.BINARY),
          new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.TEXT),
          new HBaseFieldMappingConfig("cf:d", "[4]", StorageType.TEXT));

    TargetRunner targetRunner =
        buildRunner(fieldMappings, StorageType.BINARY, OnRecordError.DISCARD, "", false, "[0]", false, false);

    Record record = RecordCreator.create();
    List<Field> fields = new ArrayList<>();
    int rowKey = 123;
    fields.add(Field.create(rowKey));
    fields.add(Field.create(20));
    fields.add(Field.create(30));
    fields.add(Field.create(40));
    fields.add(Field.create(50));
    record.set(Field.create(fields));

    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);

    // Should not be any error records.
    assertTrue(targetRunner.getErrorRecords().isEmpty());
    assertTrue(targetRunner.getErrors().isEmpty());

    targetRunner.runDestroy();

    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertEquals(20, Bytes.toInt(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("a"))));
    assertEquals(30, Bytes.toInt(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("b"))));
    assertEquals("40", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("c"))));
    assertEquals("50", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("d"))));
  }

  public void testSingleRecordBinaryStorageDateTimeTypes(Field.Type type) throws Exception {
    List<HBaseFieldMappingConfig> fieldMappings = ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.BINARY));

    TargetRunner targetRunner = buildRunner(fieldMappings, StorageType.BINARY, OnRecordError.STOP_PIPELINE, "", false, "[0]", false, false);

    Record record = RecordCreator.create();
    List<Field> fields = new ArrayList<>();
    fields.add(Field.create(123));
    fields.add(Field.create(type, new Date()));
    record.set(Field.create(fields));

    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    try {
      targetRunner.runWrite(singleRecord);
      fail(Utils.format("Expected exception when converting {} type to binary", type.name()));
    } catch(StageException e) {
      Assert.assertTrue(e.getMessage().contains(Utils.format("HBASE_12 - Cannot convert type: {} to BINARY", type.name())));
    } finally {
      targetRunner.runDestroy();
    }
  }

  @Test(timeout=60000)
  public void testSingleRecordBinaryStorageDate() throws Exception {
    testSingleRecordBinaryStorageDateTimeTypes(Type.DATE);
  }

  @Test(timeout=60000)
  public void testSingleRecordBinaryStorageTime() throws Exception {
    testSingleRecordBinaryStorageDateTimeTypes(Type.TIME);
  }

  @Test(timeout=60000)
  public void testSingleRecordBinaryStorageDateTime() throws Exception {
    testSingleRecordBinaryStorageDateTimeTypes(Type.DATETIME);
  }

  @Test(timeout=60000)
  public void testMultipleRecords() throws InterruptedException, StageException, IOException {
    // first two columns are binary, other are text
    List<HBaseFieldMappingConfig> fieldMappings =
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.BINARY),
          new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.BINARY),
          new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.TEXT),
          new HBaseFieldMappingConfig("cf:d", "[4]", StorageType.TEXT));

    TargetRunner targetRunner =
        buildRunner(fieldMappings, StorageType.BINARY, OnRecordError.DISCARD, "", false, "[0]", false, false);

    // Add two records
    Record record = RecordCreator.create();
    List<Field> fields = new ArrayList<>();
    int rowKey = 1111;
    fields.add(Field.create(rowKey));
    fields.add(Field.create(20));
    fields.add(Field.create(30));
    fields.add(Field.create(40));
    fields.add(Field.create(50));
    record.set(Field.create(fields));

    Record record2 = RecordCreator.create();
    List<Field> fields2 = new ArrayList<>();
    int rowKey2 = 2222;
    fields2.add(Field.create(rowKey2));
    fields2.add(Field.create(60));
    fields2.add(Field.create(70));
    fields2.add(Field.create(80));
    fields2.add(Field.create(90));
    record2.set(Field.create(fields2));

    List<Record> multipleRecords = ImmutableList.of(record, record2);
    targetRunner.runInit();
    targetRunner.runWrite(multipleRecords);

    // Should not be any error records.
    assertTrue(targetRunner.getErrorRecords().isEmpty());
    assertTrue(targetRunner.getErrors().isEmpty());

    targetRunner.runDestroy();

    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertEquals(20, Bytes.toInt(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("a"))));
    assertEquals(30, Bytes.toInt(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("b"))));
    assertEquals("40", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("c"))));
    assertEquals("50", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("d"))));

    g = new Get(Bytes.toBytes(rowKey2));
    r = htable.get(g);
    assertEquals(60, Bytes.toInt(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("a"))));
    assertEquals(70, Bytes.toInt(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("b"))));
    assertEquals("80", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("c"))));
    assertEquals("90", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("d"))));

  }

  @Test(timeout=60000)
  public void testCollectionTypes() throws InterruptedException, StageException, IOException {
    // first column binary, second text and last two are json string
    List<HBaseFieldMappingConfig> fieldMappings =
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.BINARY),
          new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.TEXT),
          new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.JSON_STRING),
          new HBaseFieldMappingConfig("cf:d", "[4]", StorageType.JSON_STRING));

    TargetRunner targetRunner =
        buildRunner(fieldMappings, StorageType.BINARY, OnRecordError.DISCARD, "", false, "[0]", false, false);

    Record record = RecordCreator.create();
    List<Field> fields = new ArrayList<>();
    int rowKey = 123;
    fields.add(Field.create(rowKey));
    fields.add(Field.create(20));
    fields.add(Field.create(30));
    fields.add(Field.create(ImmutableList.of(Field.create(40), Field.create(50))));
    fields.add(Field.create(ImmutableMap.of("key_1", Field.create(60), "key_2", Field.create(70))));
    record.set(Field.create(fields));

    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);

    // Should not be any error records.
    assertTrue(targetRunner.getErrorRecords().isEmpty());
    assertTrue(targetRunner.getErrors().isEmpty());

    targetRunner.runDestroy();

    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertEquals(20, Bytes.toInt(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("a"))));
    assertEquals("30", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("b"))));
    // deserialize to json
    Field field = JsonUtil.bytesToField(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("c")));
    assertTrue(field.getType() == Type.LIST);
    List<Field> list = field.getValueAsList();
    assertEquals(40, list.get(0).getValueAsInteger());
    assertEquals(50, list.get(1).getValueAsInteger());

    field = JsonUtil.bytesToField(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("d")));
    assertTrue(field.getType() == Type.MAP);
    Map<String, Field> map = field.getValueAsMap();
    assertEquals(60, map.get("key_1").getValueAsInteger());
    assertEquals(70, map.get("key_2").getValueAsInteger());
  }

  @Test(timeout=60000)
  public void testWriteRecordsOnErrorDiscard() throws InterruptedException, StageException,
      IOException {
    List<HBaseFieldMappingConfig> fieldMappings =
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.BINARY),
          new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.BINARY),
          new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.TEXT),
          new HBaseFieldMappingConfig("cf:d", "[4]", StorageType.TEXT));

    TargetRunner targetRunner =
        buildRunner(fieldMappings, StorageType.BINARY, OnRecordError.DISCARD, "", false, "[0]", false, false);

    Record record = RecordCreator.create();
    List<Field> fields = new ArrayList<>();
    String rowKey = "val"; // Invalid as row key storage type is binary
    fields.add(Field.create(rowKey));
    fields.add(Field.create(20)); // Invalid
    fields.add(Field.create(30)); // Invalid
    fields.add(Field.create(40));
    fields.add(Field.create(50));
    record.set(Field.create(fields));

    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);

    // Should not be any error records if we are discarding.
    assertTrue(targetRunner.getErrorRecords().isEmpty());
    assertTrue(targetRunner.getErrors().isEmpty());

    targetRunner.runDestroy();

    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertTrue(r.isEmpty());

  }

  @Test(timeout=60000)
  public void testWriteRecordsOnErrorToError() throws InterruptedException, StageException,
      IOException {
    List<HBaseFieldMappingConfig> fieldMappings =
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.BINARY),
          new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.BINARY),
          new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.TEXT),
          new HBaseFieldMappingConfig("cf:d", "[4]", StorageType.TEXT));

    TargetRunner targetRunner =
        buildRunner(fieldMappings, StorageType.BINARY, OnRecordError.TO_ERROR, "", false, "[0]", false, false);

    Record record = RecordCreator.create();
    List<Field> fields = new ArrayList<>();
    int rowKey = 123;
    fields.add(Field.create(rowKey));
    fields.add(Field.create("20")); // Invalid field as this cannot be mapped to binary
    fields.add(Field.create("30")); // Invalid field as this cannot be mapped to binary
    fields.add(Field.create(40));
    fields.add(Field.create(50));
    record.set(Field.create(fields));

    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);

    // Should not be any error records if we are discarding.
    assertEquals(1, targetRunner.getErrorRecords().size());
    assertTrue(targetRunner.getErrors().isEmpty());

    targetRunner.runDestroy();

    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertTrue(r.isEmpty());

  }

  @Test(timeout=60000)
  public void testWriteRecordsOnErrorToStopPipeline() throws InterruptedException, StageException,
      IOException {
    List<HBaseFieldMappingConfig> fieldMappings =
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.JSON_STRING),
          new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.TEXT),
          new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.TEXT),
          new HBaseFieldMappingConfig("cf:d", "[4]", StorageType.TEXT));

    TargetRunner targetRunner =
        buildRunner(fieldMappings, StorageType.BINARY, OnRecordError.STOP_PIPELINE, "", false, "[0]", false, false);

    Record record = RecordCreator.create();
    List<Field> fields = new ArrayList<>();
    int rowKey = 123;
    fields.add(Field.create(rowKey));
    fields.add(Field.create("20")); // Invalid field as this cannot be mapped to json string
    fields.add(Field.create("30"));
    fields.add(Field.create(40));
    fields.add(Field.create(50));
    record.set(Field.create(fields));

    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    try {
      targetRunner.runWrite(singleRecord);
      fail("Expected exception but didn't get any");
    } catch (Exception e) {
      assertTrue(e.getCause() instanceof StageException);
    }
  }

  @Test(timeout=60000)
  public void testMultipleRecordsOnError() throws InterruptedException, StageException, IOException {
    List<HBaseFieldMappingConfig> fieldMappings =
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.BINARY),
          new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.BINARY),
          new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.TEXT),
          new HBaseFieldMappingConfig("cf:d", "[4]", StorageType.TEXT));

    TargetRunner targetRunner =
        buildRunner(fieldMappings, StorageType.TEXT, OnRecordError.TO_ERROR, "", false, "[0]", false, false);

    Record record = RecordCreator.create();
    List<Field> fields = new ArrayList<>();

    String rowKey = "testMultipleRecordsOnError1";
    // / Invalid record
    fields.add(Field.create(rowKey));
    fields.add(Field.create("20")); // Invalid
    fields.add(Field.create("30")); // Invalid
    fields.add(Field.create(40));
    fields.add(Field.create(50));
    record.set(Field.create(fields));

    // Now enter a valid record
    Record record2 = RecordCreator.create();
    List<Field> fields2 = new ArrayList<>();
    String rowKey2 = "testMultipleRecordsOnError2";
    fields2.add(Field.create(rowKey2));
    fields2.add(Field.create(60));
    fields2.add(Field.create(70));
    fields2.add(Field.create(80));
    fields2.add(Field.create(90));
    record2.set(Field.create(fields2));

    List<Record> multipleRecords = ImmutableList.of(record, record2);
    targetRunner.runInit();
    // Record1 is invalid, record 2 is valid
    targetRunner.runWrite(multipleRecords);

    assertEquals(1, targetRunner.getErrorRecords().size());
    assertTrue(targetRunner.getErrors().isEmpty());

    targetRunner.runDestroy();

    // First row is not inserted
    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    Result r = htable.get(g);
    assertTrue(r.isEmpty());

    g = new Get(Bytes.toBytes(rowKey2));
    r = htable.get(g);
    assertEquals(60, Bytes.toInt(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("a"))));
    assertEquals(70, Bytes.toInt(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("b"))));
    assertEquals("80", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("c"))));
    assertEquals("90", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("d"))));
  }

  @Test(timeout=60000)
  public void testCustomTimeBasis() throws InterruptedException, StageException, IOException, ParseException {
    List<HBaseFieldMappingConfig> fieldMappings =
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.TEXT),
            new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.TEXT),
            new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.TEXT),
            new HBaseFieldMappingConfig("cf:d", "[4]", StorageType.TEXT));

    TargetRunner targetRunner =
        buildRunner(fieldMappings, StorageType.TEXT, OnRecordError.TO_ERROR, "", false, "[0]", false, false,
            "${record:value('[4]')}");

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Record record1 = RecordCreator.create();
    List<Field> fields1 = new ArrayList<>();
    String rowKey = "testCustomTimeBasis1";
    fields1.add(Field.create(rowKey));
    fields1.add(Field.create(70));
    fields1.add(Field.create(80));
    fields1.add(Field.create(90));
    Date d = sdf.parse("1986-01-17");
    fields1.add(Field.create(Type.DATE, d));
    record1.set(Field.create(fields1));

    Record record2 = RecordCreator.create();
    List<Field> fields2 = new ArrayList<>();
    String rowKey2 = "testCustomTimeBasis2";
    fields2.add(Field.create(rowKey2));
    fields2.add(Field.create(60));
    fields2.add(Field.create(70));
    fields2.add(Field.create(80));
    d = sdf.parse("1988-01-19");
    fields2.add(Field.create(Type.DATE, d));
    record2.set(Field.create(fields2));

    Record record3 = RecordCreator.create();
    List<Field> fields3 = new ArrayList<>();
    fields3.add(Field.create(rowKey));
    fields3.add(Field.create(60));
    fields3.add(Field.create(70));
    fields3.add(Field.create(80));
    d = sdf.parse("1993-01-18");
    fields3.add(Field.create(Type.DATE, d));
    record3.set(Field.create(fields3));

    List<Record> multipleRecords = ImmutableList.of(record1, record2, record3);
    targetRunner.runInit();
    targetRunner.runWrite(multipleRecords);

    targetRunner.runDestroy();

    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    g.setMaxVersions(HConstants.ALL_VERSIONS);
    Result r = htable.get(g);
    NavigableMap<Long, byte[]> map = r.getMap().get(Bytes.toBytes("cf")).get(Bytes.toBytes("a"));

    assertEquals(2, map.size());
    Set<Long> timestamps = Sets.newHashSet(sdf.parse("1993-01-18").getTime(), sdf.parse("1986-01-17").getTime());
    for (Long ts : map.keySet()) {
      assertTrue(timestamps.contains(ts));
    }

    g = new Get(Bytes.toBytes(rowKey2));
    g.setMaxVersions(HConstants.ALL_VERSIONS);
    r = htable.get(g);
    map = r.getMap().get(Bytes.toBytes("cf")).get(Bytes.toBytes("a"));
    assertEquals(1, map.size());
    assertEquals(Long.valueOf(sdf.parse("1988-01-19").getTime()), map.firstKey());
  }

  @Test(timeout=60000)
  public void testEmptyTimeBasis() throws InterruptedException, StageException, IOException, ParseException {
    List<HBaseFieldMappingConfig> fieldMappings =
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.BINARY),
            new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.TEXT),
            new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.TEXT));

    TargetRunner targetRunner =
        buildRunner(fieldMappings, StorageType.TEXT, OnRecordError.TO_ERROR, "", false, "[0]", false, false, "");

    Record record1 = RecordCreator.create();
    List<Field> fields1 = new ArrayList<>();
    String rowKey = "testEmptyTimeBasis1";
    fields1.add(Field.create(rowKey));
    fields1.add(Field.create(70));
    fields1.add(Field.create(80));
    fields1.add(Field.create(90));
    record1.set(Field.create(fields1));

    Record record2 = RecordCreator.create();
    List<Field> fields2 = new ArrayList<>();
    fields2.add(Field.create(rowKey));
    fields2.add(Field.create(60));
    fields2.add(Field.create(70));
    fields2.add(Field.create(80));
    record2.set(Field.create(fields2));

    targetRunner.runInit();
    targetRunner.runWrite(ImmutableList.of(record1));
    targetRunner.runWrite(ImmutableList.of(record2));

    assertEquals(0, targetRunner.getErrorRecords().size());

    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    g.setMaxVersions(HConstants.ALL_VERSIONS);
    Result r = htable.get(g);
    NavigableMap<Long, byte[]> map = r.getMap().get(Bytes.toBytes("cf")).get(Bytes.toBytes("a"));
    assertEquals(2, map.size());
    assertArrayEquals(Bytes.toBytes(60), map.firstEntry().getValue());
    assertArrayEquals(Bytes.toBytes(70), map.lastEntry().getValue());
  }

  @Test(timeout=60000)
  public void testTimeNowTimeBasis() throws InterruptedException, StageException, IOException, ParseException {
    List<HBaseFieldMappingConfig> fieldMappings =
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.BINARY),
            new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.TEXT),
            new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.TEXT));

    TargetRunner targetRunner =
        buildRunner(fieldMappings, StorageType.TEXT, OnRecordError.TO_ERROR, "", false, "[0]", false, false,
            "${time:now()}");

    Record record1 = RecordCreator.create();
    List<Field> fields1 = new ArrayList<>();
    String rowKey = "testTimeNowTimeBasis1";
    fields1.add(Field.create(rowKey));
    fields1.add(Field.create(70));
    fields1.add(Field.create(80));
    fields1.add(Field.create(90));
    record1.set(Field.create(fields1));

    Record record2 = RecordCreator.create();
    List<Field> fields2 = new ArrayList<>();
    String rowKey2 = "testTimeNowTimeBasis2";
    fields2.add(Field.create(rowKey2));
    fields2.add(Field.create(60));
    fields2.add(Field.create(70));
    fields2.add(Field.create(80));
    record2.set(Field.create(fields2));

    Record record3 = RecordCreator.create();
    List<Field> fields3 = new ArrayList<>();
    fields3.add(Field.create(rowKey));
    fields3.add(Field.create(60));
    fields3.add(Field.create(70));
    fields3.add(Field.create(80));
    record3.set(Field.create(fields3));

    List<Record> multipleRecords = ImmutableList.of(record1, record2, record3);
    targetRunner.runInit();
    targetRunner.runWrite(multipleRecords);

    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowKey));
    g.setMaxVersions(HConstants.ALL_VERSIONS);
    Result r = htable.get(g);
    NavigableMap<Long, byte[]> map = r.getMap().get(Bytes.toBytes("cf")).get(Bytes.toBytes("a"));
    assertEquals(1, map.size());
    // last one wins with a single batch
    assertArrayEquals(Bytes.toBytes(60), map.firstEntry().getValue());

    targetRunner.runWrite(ImmutableList.of(record1));
    targetRunner.runDestroy();

    g = new Get(Bytes.toBytes(rowKey));
    g.setMaxVersions(HConstants.ALL_VERSIONS);
    r = htable.get(g);
    map = r.getMap().get(Bytes.toBytes("cf")).get(Bytes.toBytes("a"));
    assertEquals(2, map.size());
    assertArrayEquals(Bytes.toBytes(70), map.firstEntry().getValue());

    g = new Get(Bytes.toBytes(rowKey2));
    g.setMaxVersions(HConstants.ALL_VERSIONS);
    r = htable.get(g);
    map = r.getMap().get(Bytes.toBytes("cf")).get(Bytes.toBytes("a"));
    assertEquals(1, map.size());
  }

  @Test(timeout = 60000)
  public void testInvalidColumnFamily() throws Exception {
    List<HBaseFieldMappingConfig> fieldMappings =
      ImmutableList.of(new HBaseFieldMappingConfig("invalid_cf:a", "[1]", StorageType.BINARY), new HBaseFieldMappingConfig(
        "cf:b", "[2]", StorageType.BINARY));
    TargetRunner targetRunner =
      buildRunner(fieldMappings, StorageType.TEXT, OnRecordError.TO_ERROR, "", false, "[0]", false, false);
    List<ConfigIssue> configIssues = targetRunner.runValidateConfigs();
    assertEquals(1, configIssues.size());
    assertTrue(configIssues.get(0).toString().contains(Errors.HBASE_32.getCode()));
  }

  static class ForTestHBaseTarget extends HBaseDTarget {
    @Override
    protected Target createTarget() {
      return new HBaseTarget(hBaseConnectionConfig.zookeeperQuorum, hBaseConnectionConfig.clientPort,
          hBaseConnectionConfig.zookeeperParentZnode, hBaseConnectionConfig.tableName, hbaseRowKey,
          rowKeyStorageType, hbaseFieldColumnMapping, hBaseConnectionConfig.kerberosAuth, hBaseConnectionConfig.hbaseConfDir,
          hBaseConnectionConfig.hbaseConfigs, hBaseConnectionConfig.hbaseUser, implicitFieldMapping,
          ignoreMissingFieldPath, ignoreInvalidColumn, timeDriver
      ) {
        @Override
        public void write(Batch batch) throws StageException {
        }
      };
    }
  }

  @Test
  public void testGetHBaseConfigurationWithResources() throws Exception {
    File resourcesDir = new File("target", UUID.randomUUID().toString());
    File fooDir = new File(resourcesDir, "foo");
    Assert.assertTrue(fooDir.mkdirs());
    Files.write("<configuration><property><name>xx</name><value>XX</value></property></configuration>",
                new File(fooDir, "hbase-site.xml"), StandardCharsets.UTF_8);
    HBaseDTarget dTarget = new ForTestHBaseTarget();
    configure(dTarget);
    dTarget.hBaseConnectionConfig.hbaseConfDir = fooDir.getName();
    HBaseTarget target = (HBaseTarget) dTarget.createTarget();
    try {
      target.init(null, ContextInfoCreator.createTargetContext(HBaseDTarget.class, "n", false,
                                                               OnRecordError.TO_ERROR,
                                                               resourcesDir.getAbsolutePath()));
      Configuration conf = target.getHBaseConfiguration();
      Assert.assertEquals("XX", conf.get("xx"));
    } finally {
      target.destroy();
    }

    // Provide hbaseConfDir as an absolute path
    File absoluteFilePath = new File(new File("target", UUID.randomUUID().toString()), "foo");
    Assert.assertTrue(absoluteFilePath.mkdirs());
    Files.write("<configuration><property><name>zz</name><value>ZZ</value></property></configuration>",
      new File(absoluteFilePath, "hbase-site.xml"), StandardCharsets.UTF_8);
    dTarget.hBaseConnectionConfig.hbaseConfDir = absoluteFilePath.getAbsolutePath();
    dTarget.timeDriver = "${time:now()}";
    target = (HBaseTarget) dTarget.createTarget();
    try {
      target.init(null, ContextInfoCreator.createTargetContext(HBaseDTarget.class, "n", false,
                                                               OnRecordError.TO_ERROR,
                                                               resourcesDir.getAbsolutePath()));
      Configuration conf = target.getHBaseConfiguration();
      Assert.assertEquals("ZZ", conf.get("zz"));
    } finally {
      target.destroy();
    }
  }

  private void configure(HBaseDTarget target) {
    target.hBaseConnectionConfig.zookeeperQuorum = "127.0.0.1";
    target.hBaseConnectionConfig.clientPort = miniZK.getClientPort();
    target.hBaseConnectionConfig.zookeeperParentZnode = "/hbase";
    target.hBaseConnectionConfig.tableName = tableName;
    target.hbaseRowKey = "[0]";
    target.rowKeyStorageType = StorageType.BINARY;
    target.hBaseConnectionConfig.hbaseConfigs = new HashMap<String, String>();
    target.hBaseConnectionConfig.hbaseConfigs.put("x", "X");
    target.hbaseFieldColumnMapping = new ArrayList<HBaseFieldMappingConfig>();
    target.hbaseFieldColumnMapping
        .add(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.TEXT));
    target.hBaseConnectionConfig.kerberosAuth = false;
    target.hBaseConnectionConfig.hbaseConfDir = "";
    target.hBaseConnectionConfig.hbaseUser = "";
    target.timeDriver = "${time:now()}";
  }

  private TargetRunner buildRunner(List<HBaseFieldMappingConfig> fieldMappings,
                                   StorageType storageType, OnRecordError onRecordError, String hbaseUser, boolean implicitFieldMapping,
                                   String hbaseRowKey, boolean ignoreMissingFieldPath, boolean ignoreInvalidColumn) {
    return buildRunner(fieldMappings, storageType, onRecordError, hbaseUser, implicitFieldMapping, hbaseRowKey,
        ignoreMissingFieldPath, ignoreInvalidColumn, "${time:now()}");
  }

  private TargetRunner buildRunner(List<HBaseFieldMappingConfig> fieldMappings,
      StorageType storageType, OnRecordError onRecordError, String hbaseUser, boolean implicitFieldMapping,
      String hbaseRowKey, boolean ignoreMissingFieldPath, boolean ignoreInvalidColumn, String timeDriver) {

    HBaseDTarget dTarget = new HBaseDTarget();
    configure(dTarget);
    dTarget.hbaseFieldColumnMapping = fieldMappings;
    dTarget.rowKeyStorageType = storageType;
    dTarget.hBaseConnectionConfig.hbaseUser = hbaseUser;
    dTarget.implicitFieldMapping = implicitFieldMapping;
    dTarget.hbaseRowKey = hbaseRowKey;
    dTarget.ignoreMissingFieldPath = ignoreMissingFieldPath;
    dTarget.ignoreInvalidColumn = ignoreInvalidColumn;
    dTarget.timeDriver = timeDriver;
    HBaseTarget target = (HBaseTarget)dTarget.createTarget();
    //new TargetRunner.Builder(HBaseDTarget.class, target);

    TargetRunner targetRunner =
        new TargetRunner.Builder(HBaseDTarget.class, target)
            .setOnRecordError(onRecordError)
            .build();
    return targetRunner;
  }

  private void testUser(String user) throws Exception {
    List<HBaseFieldMappingConfig> fieldMappings =
      ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.TEXT),
        new HBaseFieldMappingConfig("cf:b", "[2]", StorageType.TEXT),
        new HBaseFieldMappingConfig("cf:c", "[3]", StorageType.TEXT),
        new HBaseFieldMappingConfig("cf:d", "[4]", StorageType.TEXT));

    TargetRunner targetRunner = buildRunner(fieldMappings, StorageType.TEXT, OnRecordError.DISCARD, user, false, "[0]", false, false);

    Record record = RecordCreator.create();
    List<Field> fields = new ArrayList<>();
    String rowkey = "row_key";
    fields.add(Field.create(rowkey));
    fields.add(Field.create(20));
    fields.add(Field.create(30));
    fields.add(Field.create(40));
    fields.add(Field.create(50));
    record.set(Field.create(fields));
    assertTrue(targetRunner.runValidateConfigs().isEmpty());
    List<Record> singleRecord = ImmutableList.of(record);
    targetRunner.runInit();
    targetRunner.runWrite(singleRecord);
    targetRunner.runDestroy();
    HTable htable = new HTable(conf, tableName);
    Get g = new Get(Bytes.toBytes(rowkey));
    Result r = htable.get(g);
    assertEquals("20", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("a"))));
    assertEquals("30", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("b"))));
    assertEquals("40", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("c"))));
    assertEquals("50", Bytes.toString(r.getValue(Bytes.toBytes(familyName), Bytes.toBytes("d"))));
  }

  @Test
  public void testRegularUser() throws Exception {
    testUser("");
  }

  @Test
  public void testProxyUser() throws Exception {
    testUser("foo");
  }

  @Test(timeout=60000)
  public void testClusterModeHbaseConfDirAbsPath() throws Exception {
    File dir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
    Assert.assertTrue(dir.mkdirs());

    HBaseDTarget dTarget = new ForTestHBaseTarget();
    configure(dTarget);
    dTarget.hBaseConnectionConfig.hbaseConfDir = dir.getAbsolutePath();

    HBaseTarget target = (HBaseTarget) dTarget.createTarget();

    TargetRunner targetRunner =
      new TargetRunner.Builder(HBaseDTarget.class, target)
      .setOnRecordError(OnRecordError.DISCARD)
      .setExecutionMode(ExecutionMode.CLUSTER_BATCH).build();

    try {
      targetRunner.runInit();
      Assert.fail(Utils.format("Expected StageException as absolute hbaseConfDir path '{}' is specified in cluster mode",
        dir.getAbsolutePath()));
    } catch (StageException e) {
      Assert.assertTrue(e.getMessage().contains("HBASE_24"));
    }
  }

  private HBaseTarget getDefaultTarget() {
    return new HBaseTarget(
        "localhost",
        miniZK.getClientPort(),
        "/hbase",
        tableName,
        "[0]",
        StorageType.TEXT,
        ImmutableList.of(new HBaseFieldMappingConfig("cf:a", "[1]", StorageType.TEXT)),
        false,
        "",
        new HashMap<String, String>(),
        "",
        false,
        false,
        false,
        "${time:now()}"
    );
  }

  private HBaseConnectionConfig getDefaultConfig() {
    HBaseConnectionConfig config = new HBaseConnectionConfig();
    config.zookeeperQuorum = "127.0.0.1";
    config.clientPort = miniZK.getClientPort();
    config.zookeeperParentZnode = "/hbase";
    config.tableName = tableName;
    config.hbaseUser = "";
    config.hbaseConfigs = new HashMap<String, String>();
    return config;
  }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace freelunch.uk.Models
{
    public class SpecialistViewModel
    {
        public SpecialistViewModel()
        {
            Links = new List<Link>();
            Specialisms = new List<Specialism>();
            Locations = new List<Location>();
            DisplayLocation = new Location();
            DummyLink = new Link();
            DummySpecialism = new Specialism();
        }
        public string UserId { get; set; }

        [Required]
        [DataType(DataType.Text)]
        public string Name { get; set; }

        [DataType(DataType.Text)]
        public string Description { get; set; }

        public virtual ICollection<Location> Locations { get; set; }

        public Location DisplayLocation { get; set; }

        public virtual ICollection<Specialism> Specialisms { get; set; }

        public virtual ICollection<Link> Links { get; set; }

        //These are only used to get the Display text for their properties
        public Link DummyLink { get; private set; }
        public Specialism DummySpecialism { get; private set; }
    }
}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title><%= _.classify(moduleName) %> [component] - SUIT</title>
<meta name="viewport" content="initial-scale=1,width=device-width">
<link rel="stylesheet" href="build/build.css">

SUIT CSS: <a href="https://github.com/suitcss/<%= modulePackageName %>"><%= _.classify(moduleName) %> component tests

.<%= _.classify(moduleName) %>

renders

    <div class="<%= _.classify(moduleName) %>">

does something else

    <div class="<%= _.classify(moduleName) %>">

.<%= _.classify(moduleName) %>--modifier

renders differently

    <div class="<%= _.classify(moduleName) %>--modifier">


text:
class AddActiveToUser < ActiveRecord::Migration
  def self.up
    add_column :users, :active, :boolean, :default => false, :null => false
  end

  def self.down
    remove_column :users, :active
  end
end


text:
<?php

namespace AppBundle\Infrastructure\Order;

class ItemStatusHistory extends \Domain\Order\ItemStatusHistory{}


text:
package com.github.fluentxml4j.internal.transform;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(namespace = "", name = "source")
public class JaxbSource
{
}


text:
/**
 * @file
 * Motion effects for off-canvas dialog.
 *
 * Motion effects are in a separate file so that they can be easily turned off
 * to improve performance if desired.
 *
 * @todo Move motion effects file into a core Off-Canvas library and add a
 *   configuration option for browser rendering performance to disable this
 *   file: https://www.drupal.org/node/2784443.
 */

.dialog-off-canvas__main-canvas {
  transition: all .7s ease;
}


text:
package at.willhaben.willtest.test;

import at.willhaben.willtest.junit5.BrowserUtil;
import at.willhaben.willtest.junit5.OptionCombiner;
import at.willhaben.willtest.junit5.OptionModifier;
import at.willhaben.willtest.util.AnnotationHelper;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxOptions;

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

import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class BrowserOptionsTest {

    ExtensionContext context;

    @BeforeEach
    void setup() {
        context = mock(ExtensionContext.class);

        when(context.getRequiredTestClass())
                .thenReturn(((Class) TestClass.class));
    }

    @Test
    void mergeOptionsTest() {
        List<OptionModifier> optionAnnotationList
                = AnnotationHelper.getBrowserUtilExtensionList(context, OptionModifier.class, false);
        ChromeOptions modifiedFirefoxOptions = new OptionCombiner(optionAnnotationList)
                .getBrowserOptions(ChromeOptions.class);
        Map<Object, Object> chromeOptionsMap =
                (Map<Object, Object>) modifiedFirefoxOptions.asMap().get(ChromeOptions.CAPABILITY);
        List<String> chromeArguments = (List<String>) chromeOptionsMap.get("args");
        assertThat(chromeArguments, Matchers.containsInAnyOrder("--headless", "--disable-gpu"));
    }

    public static class TestOptions implements OptionModifier {

        @Override
        public ChromeOptions modifyChromeOptions(ChromeOptions options) {
            return options.setHeadless(true);
        }
    }

    @BrowserUtil(TestOptions.class)
    public class TestClass {

    }
}


text:
package tenant

/*
 * All of the setters will return either nil or ERROR. This is atypical of most
 * other routines, but this is where rules are enforced for the record's fields
 */

import (
	"github.com/cgentry/gus/ecode"
	"github.com/cgentry/gus/library/encryption"
	"strings"
	"time"
)

// Set, or reset, the user's ID. When an ID is set, the GUID is reset.
func (user *User) SetID(id int) error {

	if id > 0 && user.Id == 0 {
		user.Id = id
		return nil
	}
	return ecode.ErrCannotSetId

}

// SetName sets the fullname for the user
func (user *User) SetName(name string) error {
	name = strings.TrimSpace(name)
	if name == "" {
		return ecode.ErrMissingName
	}
	user.FullName = name
	return nil
}

func (user *User) SetEmail(val string) error {
	user.Email = val
	return nil
}

func (user *User) SetGuid(val string) error {
	if len(val) < 32 {
		return ecode.ErrShortGuid
	}
	user.Guid = val
	return nil
}

func (user *User) SetLoginName(name string) error {
	user.LoginName = name
	return nil
}

func (user *User) SetToken(val string) error {
	user.Token = val
	return nil
}

func (user *User) SetLoginAt(t time.Time) error {
	user.LoginAt = t
	return nil
}
func (user *User) SetUpdatedAt(t time.Time) error {
	user.UpdatedAt = t
	return nil
}

// SetDomain will set the domain name for this record.
func (user *User) SetDomain(val string) error {
	user.Domain = val
	return nil
}

func (user *User) SetPasswordStr(pwd string) error {
	user.Password = pwd
	return nil
}
func (user *User) SetPassword(newPassword string) error {
	newPassword = strings.TrimSpace(newPassword)
	if newPassword == "" {
		return ecode.ErrMissingPassword
	}
	if len(newPassword) < 6 {
		return ecode.ErrPasswordTooShort
	}
	user.Password = encryption.GetDefaultDriver().EncryptPassword(newPassword, user.Salt)
	return nil
}

func (user *User) SetSalt(val string) error {
	user.Salt = val
	return nil
}

func (user *User) SetIsActive(val bool) error {
	user.IsActive = val
	return nil
}

func (user *User) SetIsLoggedIn(val bool) error {
	user.IsLoggedIn = val
	return nil
}

func (user *User) SetIsSystem(val bool) error {
	user.IsSystem = val
	return nil
}

func (user *User) SetLogoutAt(t time.Time) error {
	user.LogoutAt = t
	return nil
}

func (user *User) SetLastFailedAt(t time.Time) error {
	user.LastFailedAt = t
	return nil
}

func (user *User) SetLastAuthAt(t time.Time) error {
	user.LastAuthAt = t
	return nil
}

func (user *User) SetFailCount(i int) error {
	user.FailCount = i
	return nil
}

func (user *User) SetMaxSessionAt(t time.Time) error {
	user.MaxSessionAt = t
	return nil
}

func (user *User) SetTimeoutAt(t time.Time) error {
	user.TimeoutAt = t
	return nil
}

func (user *User) SetCreatedAt(t time.Time) error {
	user.CreatedAt = t
	return nil
}

func (user *User) SetDeletedAt(t time.Time) error {
	user.DeletedAt = t
	return nil
}


text:
package org.springframework.boot.logging;

import java.net.URLClassLoader;
import java.util.Arrays;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.boot.context.event.ApplicationFailedEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;

/**
 * A {@link SmartApplicationListener} that reacts to {@link ApplicationStartedEvent start
 * events} by logging the classpath of the thread context class loader (TCCL) at
 * {@code DEBUG} level and to {@link ApplicationFailedEvent error events} by logging the
 * TCCL's classpath at {@code INFO} level.
 *
 * @author Andy Wilkinson
 */
public final class ClasspathLoggingApplicationListener implements
		GenericApplicationListener {

	private static final int ORDER = Ordered.HIGHEST_PRECEDENCE + 12;

	private final Log logger = LogFactory.getLog(getClass());

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof ApplicationStartedEvent) {
			if (this.logger.isDebugEnabled()) {
				this.logger
						.debug("Application started with classpath: " + getClasspath());
			}
		}
		else if (event instanceof ApplicationFailedEvent) {
			if (this.logger.isInfoEnabled()) {
				this.logger.info("Application failed to start with classpath: "
						+ getClasspath());
			}
		}
	}

	@Override
	public int getOrder() {
		return ORDER;
	}

	@Override
	public boolean supportsEventType(ResolvableType resolvableType) {
		Class<?> type = resolvableType.getRawClass();
		if (type == null) {
			return false;
		}
		return ApplicationStartedEvent.class.isAssignableFrom(type)
				|| ApplicationFailedEvent.class.isAssignableFrom(type);
	}

	@Override
	public boolean supportsSourceType(Class<?> sourceType) {
		return true;
	}

	private String getClasspath() {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		if (classLoader instanceof URLClassLoader) {
			return Arrays.toString(((URLClassLoader) classLoader).getURLs());
		}
		return "unknown";
	}

}


text:
layout: page
title: Angel Light Entertainment Award Ceremony
date: 2016-05-24
author: Bobby Beard
tags: weekly links, java
status: published
summary: Pellentesque tempor nibh non quam suscipit.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 03/26/2016
  endDate: 03/30/2016
  ctyhocn: GAIMDHX
  groupCode: ALEAC
published: true
---
Morbi porttitor ex nec leo pellentesque efficitur. Donec sodales nulla a elit molestie tristique. Cras leo elit, rutrum sit amet nunc non, dignissim molestie justo. Praesent maximus congue vestibulum. Duis magna metus, dapibus et leo vitae, vehicula fermentum ante. Phasellus egestas augue lectus, ac sodales lorem bibendum sollicitudin. Nam quam elit, volutpat vel tellus rhoncus, congue tristique dui.

* Ut rhoncus metus ultricies vulputate faucibus
* Proin ac risus vulputate, lacinia nibh id, facilisis velit.

Morbi sed porttitor ipsum. Nulla facilisi. Etiam sit amet quam eu ante pharetra cursus. Maecenas tempus ultrices posuere. Suspendisse non mollis neque. In commodo a urna tempus molestie. Nulla sed dignissim enim. Vivamus id justo sit amet nunc luctus sodales. Sed nunc orci, facilisis feugiat nisl ac, porta suscipit justo. Suspendisse sit amet erat placerat, suscipit mi vitae, efficitur urna. Etiam ornare rhoncus massa viverra gravida. Phasellus dignissim mauris massa, vel fermentum tellus vestibulum commodo. Donec in lobortis mi. Proin semper lectus in posuere aliquam. Etiam a rutrum tortor.
Morbi hendrerit ut ex eget bibendum. Pellentesque dignissim suscipit ultricies. Nulla diam justo, laoreet eget nibh non, finibus condimentum orci. Fusce non lacus tristique, ornare lorem in, dictum ex. Sed ut purus at dui sollicitudin venenatis. Nulla at blandit justo. Nam nec lobortis nulla. Pellentesque diam tortor, semper non ex a, bibendum dapibus dolor. Duis vitae urna volutpat, ornare sem eget, laoreet turpis. Etiam vitae dapibus libero, sed efficitur nunc. Quisque ultrices justo vitae faucibus elementum. Nulla facilisi. Phasellus odio dolor, bibendum eget laoreet ac, tempus id nisl.