text:
import mock
from oslo_config import cfg

from cinder import context
from cinder import db
from cinder import exception
from cinder import objects
from cinder import test
from cinder.tests.unit import fake_constants as fake
from cinder.tests.unit import utils as tests_utils
from cinder.volume import api as volume_api
from cinder.volume import configuration as conf

CONF = cfg.CONF

class AttachmentManagerTestCase(test.TestCase):
    """Attachment related test for volume/api.py."""

    def setUp(self):
        """Setup test class."""
        super(AttachmentManagerTestCase, self).setUp()
        self.configuration = mock.Mock(conf.Configuration)
        self.context = context.get_admin_context()
        self.context.user_id = fake.USER_ID
        self.project_id = fake.PROJECT3_ID
        self.context.project_id = self.project_id
        self.volume_api = volume_api.API()

    @mock.patch('cinder.volume.api.check_policy')
    def test_attachment_create_no_connector(self, mock_policy):
        """Test attachment_create no connector."""
        volume_params = {'status': 'available'}

        vref = tests_utils.create_volume(self.context, **volume_params)
        aref = self.volume_api.attachment_create(self.context,
                                                 vref,
                                                 fake.UUID2)
        self.assertEqual(fake.UUID2, aref.instance_uuid)
        self.assertIsNone(aref.attach_time)
        self.assertEqual('reserved', aref.attach_status)
        self.assertIsNone(aref.attach_mode)
        self.assertEqual(vref.id, aref.volume_id)
        self.assertEqual({}, aref.connection_info)

    @mock.patch('cinder.volume.api.check_policy')
    @mock.patch('cinder.volume.rpcapi.VolumeAPI.attachment_update')
    def test_attachment_create_with_connector(self,
                                              mock_rpc_attachment_update,
                                              mock_policy):
        """Test attachment_create with connector."""
        volume_params = {'status': 'available'}
        connection_info = {'fake_key': 'fake_value',
                           'fake_key2': ['fake_value1', 'fake_value2']}
        mock_rpc_attachment_update.return_value = connection_info

        vref = tests_utils.create_volume(self.context, **volume_params)
        connector = {'fake': 'connector'}
        attachment = self.volume_api.attachment_create(self.context,
                                                       vref,
                                                       fake.UUID2,
                                                       connector)
        mock_rpc_attachment_update.assert_called_once_with(self.context,
                                                           mock.ANY,
                                                           connector,
                                                           mock.ANY)
        new_attachment = objects.VolumeAttachment.get_by_id(self.context,
                                                            attachment.id)
        self.assertEqual(connection_info, new_attachment.connection_info)

    @mock.patch('cinder.volume.api.check_policy')
    @mock.patch('cinder.volume.rpcapi.VolumeAPI.attachment_delete')
    def test_attachment_delete_reserved(self,
                                        mock_rpc_attachment_delete,
                                        mock_policy):
        """Test attachment_delete with reserved."""
        volume_params = {'status': 'available'}

        vref = tests_utils.create_volume(self.context, **volume_params)
        aref = self.volume_api.attachment_create(self.context,
                                                 vref,
                                                 fake.UUID2)
        aobj = objects.VolumeAttachment.get_by_id(self.context,
                                                  aref.id)
        self.assertEqual('reserved', aref.attach_status)
        self.assertEqual(vref.id, aref.volume_id)
        self.volume_api.attachment_delete(self.context,
                                          aobj)

        # Since it's just reserved and never finalized, we should never make an
        # rpc call
        mock_rpc_attachment_delete.assert_not_called()

    @mock.patch('cinder.volume.api.check_policy')
    @mock.patch('cinder.volume.rpcapi.VolumeAPI.attachment_delete')
    @mock.patch('cinder.volume.rpcapi.VolumeAPI.attachment_update')
    def test_attachment_create_update_and_delete(
            self,
            mock_rpc_attachment_update,
            mock_rpc_attachment_delete,
            mock_policy):
        """Test attachment_delete."""
        volume_params = {'status': 'available'}
        connection_info = {'fake_key': 'fake_value',
                           'fake_key2': ['fake_value1', 'fake_value2']}
        mock_rpc_attachment_update.return_value = connection_info

        vref = tests_utils.create_volume(self.context, **volume_params)
        aref = self.volume_api.attachment_create(self.context,
                                                 vref,
                                                 fake.UUID2)
        aref = objects.VolumeAttachment.get_by_id(self.context,
                                                  aref.id)
        vref = objects.Volume.get_by_id(self.context,
                                        vref.id)

        connector = {'fake': 'connector'}
        self.volume_api.attachment_update(self.context,
                                          aref,
                                          connector)
        aref = objects.VolumeAttachment.get_by_id(self.context,
                                                  aref.id)
        self.assertEqual(connection_info, aref.connection_info)
        # We mock the actual call that updates the status
        # so force it here
        values = {'volume_id': vref.id,
                  'volume_host': vref.host,
                  'attach_status': 'attached',
                  'instance_uuid': fake.UUID2}
        aref = db.volume_attach(self.context, values)

        aref = objects.VolumeAttachment.get_by_id(self.context,
                                                  aref.id)
        self.assertEqual(vref.id, aref.volume_id)
        self.volume_api.attachment_delete(self.context,
                                          aref)

        mock_rpc_attachment_delete.assert_called_once_with(self.context,
                                                           aref.id,
                                                           mock.ANY)

    @mock.patch('cinder.volume.api.check_policy')
    def test_additional_attachment_create_no_connector(self, mock_policy):
        """Test attachment_create no connector."""
        volume_params = {'status': 'available'}

        vref = tests_utils.create_volume(self.context, **volume_params)
        aref = self.volume_api.attachment_create(self.context,
                                                 vref,
                                                 fake.UUID2)
        self.assertEqual(fake.UUID2, aref.instance_uuid)
        self.assertIsNone(aref.attach_time)
        self.assertEqual('reserved', aref.attach_status)
        self.assertIsNone(aref.attach_mode)
        self.assertEqual(vref.id, aref.volume_id)
        self.assertEqual({}, aref.connection_info)

        self.assertRaises(exception.InvalidVolume,
                          self.volume_api.attachment_create,
                          self.context,
                          vref,
                          fake.UUID1)
        self.volume_api.attachment_create(self.context,
                                          vref,
                                          fake.UUID2)
        vref = objects.Volume.get_by_id(self.context,
                                        vref.id)
        self.assertEqual(2, len(vref.volume_attachment))

    @mock.patch('cinder.volume.api.check_policy')
    @mock.patch('cinder.volume.rpcapi.VolumeAPI.attachment_update')
    def test_attachment_create_reserve_delete(
            self,
            mock_rpc_attachment_update,
            mock_policy):
        volume_params = {'status': 'available'}
        connector = {
            "initiator": "iqn.1993-08.org.debian:01:cad181614cec",
            "ip": "192.168.1.20",
            "platform": "x86_64",
            "host": "tempest-1",
            "os_type": "linux2",
            "multipath": False}

        connection_info = {'fake_key': 'fake_value',
                           'fake_key2': ['fake_value1', 'fake_value2']}
        mock_rpc_attachment_update.return_value = connection_info

        vref = tests_utils.create_volume(self.context, **volume_params)
        aref = self.volume_api.attachment_create(self.context,
                                                 vref,
                                                 fake.UUID2,
                                                 connector=connector)
        vref = objects.Volume.get_by_id(self.context,
                                        vref.id)
        # Need to set the status here because our mock isn't doing it for us
        vref.status = 'in-use'
        vref.save()

        # Now a second attachment acting as a reserve
        self.volume_api.attachment_create(self.context,
                                          vref,
                                          fake.UUID2)

        # We should now be able to delete the original attachment that gave us
        # 'in-use' status, and in turn we should revert to the outstanding
        # attachments reserve
        self.volume_api.attachment_delete(self.context,
                                          aref)
        vref = objects.Volume.get_by_id(self.context,
                                        vref.id)
        self.assertEqual('reserved', vref.status)

    @mock.patch('cinder.volume.api.check_policy')
    def test_reserve_reserve_delete(self, mock_policy):
        """Test that we keep reserved status across multiple reserves."""
        volume_params = {'status': 'available'}

        vref = tests_utils.create_volume(self.context, **volume_params)
        aref = self.volume_api.attachment_create(self.context,
                                                 vref,
                                                 fake.UUID2)
        vref = objects.Volume.get_by_id(self.context,
                                        vref.id)
        self.assertEqual('reserved', vref.status)

        self.volume_api.attachment_create(self.context,
                                          vref,
                                          fake.UUID2)
        vref = objects.Volume.get_by_id(self.context,
                                        vref.id)
        self.assertEqual('reserved', vref.status)
        self.volume_api.attachment_delete(self.context,
                                          aref)
        vref = objects.Volume.get_by_id(self.context,
                                        vref.id)
        self.assertEqual('reserved', vref.status)
        self.assertEqual(1, len(vref.volume_attachment))


text:
package com.dyuproject.jetg.parser.code;

/**
 * 用于存储一行源代码
 */
public class LineCode extends Code {
    private final String source;

    public LineCode(String source, boolean proc) {
        this.source = source;
        this.proc = proc;
        readNextNewLine = proc;
    }

    public LineCode(String source) {
        this(source, false);
    }

    @Override
    public String toString() {
        return source;
    }
}

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Entity } from 'draft-js';
import classNames from 'classnames';
import styles from './styles.css'; // eslint-disable-line no-unused-vars

class Hashtag {

  constructor(config) {
    this.className = config.className;
    this.hashCharacter = config.hashCharacter || '#';
    this.separator = config.separator || ' ';
  }

  getHashtagComponent = () => {
    const className = this.className;
    return class HashtagComponent extends Component {
      static PropTypes = {
        children: PropTypes.object,
      }
      render() {
        const { children } = this.props;
        const text = children[0].props.text;
        return (
          <a href={text} className={classNames('rdw-hashtag-link', className)}>
            {children}
          </a>
        );
      }
    };
  };

  findHashtagEntities = (contentBlock, callback) => {
    let text = contentBlock.getText();
    let startIndex = 0;
    let counter = 0;

    for (;text.length > 0 && startIndex >= 0;) {
      if (text[0] === this.hashCharacter) {
        startIndex = 0;
        counter = 0;
        text = text.substr(this.hashCharacter.length);
      } else {
        startIndex = text.indexOf(this.separator + this.hashCharacter);
        if (startIndex >= 0) {
          text = text.substr(startIndex + (this.separator + this.hashCharacter).length);
          counter += startIndex + this.separator.length;
        }
      }
      if (startIndex >= 0) {
        const endIndex =
          text.indexOf(this.separator) >= 0 ? text.indexOf(this.separator) : text.length;
        const hashtagText = text.substr(0, endIndex);
        if (hashtagText && hashtagText.length > 0) {
          callback(counter, counter + hashtagText.length + this.hashCharacter.length);
          counter += this.hashCharacter.length;
        }
      }
    }
  };

  getHashtagDecorator = () => {
    return {
      strategy: this.findHashtagEntities,
      component: this.getHashtagComponent(),
    }
  };
}

const getDecorator = (config) => (new Hashtag(config)).getHashtagDecorator();

module.exports = getDecorator;


text:
'use strict';

const debug = require('debug')('knc-render:lib:nunjucks:tag_component');
const nunjucks = require('nunjucks');

/**
 * 组件TAG
 * @param {object} options
 */
function Component(options) {
    this.tags = ['component'];

    this.parse = function(parser, nodes) {
        const tok = parser.nextToken();
        const args = parser.parseSignature(null, true);

        parser.advanceAfterBlockEnd(tok.value);
        return new nodes.CallExtensionAsync(this, 'run', args, null);
    };

    this.run = function(context, params, callback) {
        const config = options.config;
        const dataFilter = config.dataFilter;
        const componentName = params.name;
        const theme = params.theme || 'default';
        const extra = params.extra || {};
        let data = params.data || {};

        if (!componentName) {
            debug('Component name can not be empty.');
            callback(null, '');
        }

        if (typeof dataFilter === 'function') {
            data = dataFilter(data, extra) || {};
        }

        debug('Data render, %s', componentName);

        // 当前组件模板
        const currComponentTmpl = `${config.componentPath}/${componentName}/${config.componentDefaultTmpl}${config.ext}`;
        let renderResult = nunjucks.render(currComponentTmpl, data);

        renderResult = `<div class="${componentName}_${theme}" data-component-name="${componentName}">${renderResult}</div>`;
        callback(null, new nunjucks.runtime.SafeString(renderResult));
    };
}

module.exports = Component;


text: mvn -DMAVEN_OPTS="-Xmx1024m -Xms512m" clean install -Pproduction


text:
import nls = require('vs/nls');
import * as dom from 'vs/base/browser/dom';
import { $ } from 'vs/base/browser/builder';
import { Widget } from 'vs/base/browser/ui/widget';
import { Checkbox } from 'vs/base/browser/ui/checkbox/checkbox';
import { IContextViewProvider } from 'vs/base/browser/ui/contextview/contextview';
import { InputBox, IInputValidator } from 'vs/base/browser/ui/inputbox/inputBox';
import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent';
import { KeyCode } from 'vs/base/common/keyCodes';
import CommonEvent, { Emitter } from 'vs/base/common/event';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { attachInputBoxStyler, attachCheckboxStyler } from 'vs/platform/theme/common/styler';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { HistoryNavigator } from 'vs/base/common/history';

export interface IOptions {
	placeholder?: string;
	width?: number;
	validation?: IInputValidator;
	ariaLabel?: string;
}

export class PatternInputWidget extends Widget {

	static OPTION_CHANGE: string = 'optionChange';

	public inputFocusTracker: dom.IFocusTracker;

	protected onOptionChange: (event: Event) => void;
	private width: number;
	private placeholder: string;
	private ariaLabel: string;

	private domNode: HTMLElement;
	private inputNode: HTMLInputElement;
	protected inputBox: InputBox;

	private history: HistoryNavigator<string>;

	private _onSubmit = this._register(new Emitter<boolean>());
	public onSubmit: CommonEvent<boolean> = this._onSubmit.event;

	private _onCancel = this._register(new Emitter<boolean>());
	public onCancel: CommonEvent<boolean> = this._onCancel.event;

	constructor(parent: HTMLElement, private contextViewProvider: IContextViewProvider, protected themeService: IThemeService, options: IOptions = Object.create(null)) {
		super();
		this.history = new HistoryNavigator<string>();
		this.onOptionChange = null;
		this.width = options.width || 100;
		this.placeholder = options.placeholder || '';
		this.ariaLabel = options.ariaLabel || nls.localize('defaultLabel', "input");

		this.domNode = null;
		this.inputNode = null;
		this.inputBox = null;

		this.render();

		parent.appendChild(this.domNode);
	}

	public dispose(): void {
		super.dispose();
		if (this.inputFocusTracker) {
			this.inputFocusTracker.dispose();
		}
	}

	public on(eventType: string, handler: (event: Event) => void): PatternInputWidget {
		switch (eventType) {
			case 'keydown':
			case 'keyup':
				$(this.inputBox.inputElement).on(eventType, handler);
				break;
			case PatternInputWidget.OPTION_CHANGE:
				this.onOptionChange = handler;
				break;
		}
		return this;
	}

	public setWidth(newWidth: number): void {
		this.width = newWidth;
		this.domNode.style.width = this.width + 'px';
		this.contextViewProvider.layout();
		this.setInputWidth();
	}

	public getValue(): string {
		return this.inputBox.value;
	}

	public setValue(value: string): void {
		if (this.inputBox.value !== value) {
			this.inputBox.value = value;
		}
	}

	public select(): void {
		this.inputBox.select();
	}

	public focus(): void {
		this.inputBox.focus();
	}

	public inputHasFocus(): boolean {
		return this.inputBox.hasFocus();
	}

	private setInputWidth(): void {
		this.inputBox.width = this.width - this.getSubcontrolsWidth() - 2; // 2 for input box border
	}

	protected getSubcontrolsWidth(): number {
		return 0;
	}

	public getHistory(): string[] {
		return this.history.getHistory();
	}

	public setHistory(history: string[]) {
		this.history = new HistoryNavigator<string>(history);
	}

	public onSearchSubmit(): void {
		const value = this.getValue();
		if (value) {
			this.history.addIfNotPresent(value);
		}
	}

	public showNextTerm() {
		let next = this.history.next();
		if (next) {
			this.setValue(next);
		}
	}

	public showPreviousTerm() {
		let previous;
		if (this.getValue().length === 0) {
			previous = this.history.current();
		} else {
			this.history.addIfNotPresent(this.getValue());
			previous = this.history.previous();
		}
		if (previous) {
			this.setValue(previous);
		}
	}

	private render(): void {
		this.domNode = document.createElement('div');
		this.domNode.style.width = this.width + 'px';
		$(this.domNode).addClass('monaco-findInput');

		this.inputBox = new InputBox(this.domNode, this.contextViewProvider, {
			placeholder: this.placeholder || '',
			ariaLabel: this.ariaLabel || '',
			validationOptions: {
				validation: null,
				showMessage: true
			}
		});
		this._register(attachInputBoxStyler(this.inputBox, this.themeService));
		this.inputFocusTracker = dom.trackFocus(this.inputBox.inputElement);
		this.onkeyup(this.inputBox.inputElement, (keyboardEvent) => this.onInputKeyUp(keyboardEvent));

		let controls = document.createElement('div');
		controls.className = 'controls';
		this.renderSubcontrols(controls);

		this.domNode.appendChild(controls);
		this.setInputWidth();
	}

	protected renderSubcontrols(controlsDiv: HTMLDivElement): void {
	}

	private onInputKeyUp(keyboardEvent: IKeyboardEvent) {
		switch (keyboardEvent.keyCode) {
			case KeyCode.Enter:
				this._onSubmit.fire();
				return;
			case KeyCode.Escape:
				this._onCancel.fire();
				return;
			default:
				return;
		}
	}
}

export class ExcludePatternInputWidget extends PatternInputWidget {

	constructor(parent: HTMLElement, contextViewProvider: IContextViewProvider, themeService: IThemeService, private telemetryService: ITelemetryService, options: IOptions = Object.create(null)) {
		super(parent, contextViewProvider, themeService, options);
	}

	private useIgnoreFilesBox: Checkbox;
	private useExcludeSettingsBox: Checkbox;

	public dispose(): void {
		super.dispose();
		this.useIgnoreFilesBox.dispose();
		this.useExcludeSettingsBox.dispose();
	}

	public useExcludeSettings(): boolean {
		return this.useExcludeSettingsBox.checked;
	}

	public setUseExcludeSettings(value: boolean) {
		this.useExcludeSettingsBox.checked = value;
	}

	public useIgnoreFiles(): boolean {
		return this.useIgnoreFilesBox.checked;
	}

	public setUseIgnoreFiles(value: boolean): void {
		this.useIgnoreFilesBox.checked = value;
	}

	protected getSubcontrolsWidth(): number {
		return super.getSubcontrolsWidth() + this.useIgnoreFilesBox.width() + this.useExcludeSettingsBox.width();
	}

	protected renderSubcontrols(controlsDiv: HTMLDivElement): void {
		this.useIgnoreFilesBox = new Checkbox({
			actionClassName: 'useIgnoreFiles',
			title: nls.localize('useIgnoreFilesDescription', "Use Ignore Files"),
			isChecked: false,
			onChange: (viaKeyboard) => {
				this.telemetryService.publicLog('search.useIgnoreFiles.toggled');
				this.onOptionChange(null);
				if (!viaKeyboard) {
					this.inputBox.focus();
				}
			}
		});
		this._register(attachCheckboxStyler(this.useIgnoreFilesBox, this.themeService));

		this.useExcludeSettingsBox = new Checkbox({
			actionClassName: 'useExcludeSettings',
			title: nls.localize('useExcludeSettingsDescription', "Use Exclude Settings"),
			isChecked: false,
			onChange: (viaKeyboard) => {
				this.telemetryService.publicLog('search.useExcludeSettings.toggled');
				this.onOptionChange(null);
				if (!viaKeyboard) {
					this.inputBox.focus();
				}
			}
		});
		this._register(attachCheckboxStyler(this.useExcludeSettingsBox, this.themeService));

		controlsDiv.appendChild(this.useIgnoreFilesBox.domNode);
		controlsDiv.appendChild(this.useExcludeSettingsBox.domNode);
		super.renderSubcontrols(controlsDiv);
	}
}


text:
package org.dyndns.buefield.vmm.action;

import java.util.List;

import javax.annotation.Resource;

import org.dyndns.bluefield.craysas.html.config.ListTableConfig;
import org.dyndns.bluefield.craysas.html.field.Field;
import org.dyndns.buefield.vmm.entity.VirtualMachine;
import org.seasar.extension.jdbc.JdbcManager;
import org.seasar.struts.annotation.Execute;
import static org.dyndns.bluefield.craysas.html.field.Field.field;

public class VirtualMachineAction {

	public static final Field[] ITEMS = new Field[] {
		field("name").text(),
		field("ipAddress").text(),
		field("statusDisp").text(),
		field("runOnDisp").text().link("/vpjrm/physicalHost/show", "id", "runOn"),
		field("vcpu").number(),
		field("memory").number(),
		field("updateDt").text()
	};

	// DI
	@Resource protected JdbcManager jdbcManager;

	//
	public ListTableConfig<VirtualMachine> config;

	@Execute(validator=false)
	public String index() {
		List<VirtualMachine> vms = jdbcManager.from(VirtualMachine.class)
		.leftOuterJoin("runOnMahcine").getResultList();

		config = new ListTableConfig<VirtualMachine>("virtualMachine.", ITEMS, vms);
		return "index.jsp";
	}
}


text:
/*! Hello World Example
    This example shows the most basic of tasks with Phoenix: Saying hello.
*/

/*!
    Include our header.
*/
#include "Phoenix.h"

/*!
    We'll use the phoenix namespace so that we don't
    have to type phoenix:: in front of everything.
*/
using namespace phoenix;

/*!
    Your standard main() function.
*/
int main()
{

    /*!
        We'll create a RenderSystem. This opens up a window and gets everything
        ready for us to draw. We could optionally set a different screen size
        (the default is 640x480) and tell it to be fullscreen.
    */
	RenderSystem system;

    /*! The Loop.
        The loop is the main feature of most games. The loop runs until the user
        decides to exit ( by closing the window or pressing the escape key ).
        We'll call the system's run() function. The function does some magic
        behind the scenes to swap buffers, update events, calcuate frame per
        second, and other things.
    */
    while( system.run() )
    {
        /*!
            Now we say hello. System has a method called drawText that can do just that.
            The first parameter is obviously the text we'd like to draw. The second is a
            Vector2d that tells the system where to draw it. And we'd also like the color
            of that text to be red.
        */
        system.drawText( "Hello, World!", Vector2d(50,50), Color( 255,0,0 ) );

    }

    return 0;

}


text:
#import <Foundation/Foundation.h>

#import "ABI11_0_0ARTRenderable.h"
#import "ABI11_0_0ARTTextFrame.h"

@interface ABI11_0_0ARTText : ABI11_0_0ARTRenderable

@property (nonatomic, assign) CTTextAlignment alignment;
@property (nonatomic, assign) ABI11_0_0ARTTextFrame textFrame;

@end


text:
class VncError(Exception):
    pass
# end class VncError

class NoIdError(VncError):

    def __init__(self, unknown_id):
        self._unknown_id = unknown_id
    # end __init__

    def __str__(self):
        return 'Unknown id: %s' % (self._unknown_id)
    # end __str__
# end class NoIdError

class MaxRabbitPendingError(VncError):

    def __init__(self, npending):
        self._npending = npending
    # end __init__

    def __str__(self):
        return 'Too many pending updates to RabbitMQ: %s' % (self._npending)
    # end __str__
# end class MaxRabbitPendingError

class ResourceExistsError(VncError):
    def __init__(self, eexists_fq_name, eexists_id):
        self._eexists_fq_name = eexists_fq_name
        self._eexists_id = eexists_id
    # end __init__

    def __str__(self):
        return 'FQ Name: %s exists already with ID: %s' \
            % (self._eexists_fq_name, self._eexists_id)
    # end __str__
# end class ResourceExistsError

class PermissionDenied(VncError):
    pass
# end class PermissionDenied

class RefsExistError(VncError):
    pass
# end class RefsExistError

class ResourceExhaustionError(VncError):
    pass
# end class ResourceExhaustionError

class NoUserAgentKey(VncError):
    pass
# end class NoUserAgentKey

class UnknownAuthMethod(VncError):
    pass
# end class UnknownAuthMethod

class HttpError(VncError):

    def __init__(self, status_code, content):
        self.status_code = status_code
        self.content = content
    # end __init__

    def __str__(self):
        return 'HTTP Status: %s Content: %s' % (self.status_code, self.content)
    # end __str__
# end class HttpError

class AmbiguousParentError(VncError):
    pass


text:
**Maintainer:** [Stibbons](https://github.com/Stibbons)

This plugin mainly add support automatic completion for the repo command line tool:
http://code.google.com/p/git-repo/

* `r` aliases `repo`


text:
var ClientManager = new require("../clientManager");
var fs = require("fs");
var program = require("commander");
var Helper = require("../helper");

program
	.command("remove <name>")
	.description("Remove an existing user")
	.action(function(name) {
		try {
			var path = Helper.HOME + "/users";
			var test = path + "/.test";
			fs.mkdirSync(test);
			fs.rmdirSync(test);
		} catch (e) {
			console.log("");
			console.log("You have no permissions to delete from " + path);
			console.log("Try running the command as sudo.");
			console.log("");
			return;
		}
		var manager = new ClientManager();
		if (manager.removeUser(name)) {
			console.log("");
			console.log("Removed '" + name + "'.");
			console.log("");
		} else {
			console.log("");
			console.log("User '" + name + "' doesn't exist.");
			console.log("");
		}
	});


text:
module Azure::RecoveryServicesBackup::Mgmt::V2017_07_01
  module Models
    #
    # Azure Recovery Services Vault specific protection intent item.
    #
    class AzureWorkloadAutoProtectionIntent < AzureRecoveryServiceVaultProtectionIntent

      include MsRestAzure

      def initialize
        @protectionIntentItemType = "AzureWorkloadAutoProtectionIntent"
      end

      attr_accessor :protectionIntentItemType

      #
      # Mapper for AzureWorkloadAutoProtectionIntent class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'AzureWorkloadAutoProtectionIntent',
          type: {
            name: 'Composite',
            class_name: 'AzureWorkloadAutoProtectionIntent',
            model_properties: {
              backup_management_type: {
                client_side_validation: true,
                required: false,
                serialized_name: 'backupManagementType',
                type: {
                  name: 'String'
                }
              },
              source_resource_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'sourceResourceId',
                type: {
                  name: 'String'
                }
              },
              item_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'itemId',
                type: {
                  name: 'String'
                }
              },
              policy_id: {
                client_side_validation: true,
                required: false,
                serialized_name: 'policyId',
                type: {
                  name: 'String'
                }
              },
              protection_state: {
                client_side_validation: true,
                required: false,
                serialized_name: 'protectionState',
                type: {
                  name: 'String'
                }
              },
              protectionIntentItemType: {
                client_side_validation: true,
                required: true,
                serialized_name: 'protectionIntentItemType',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
<?php

namespace Zap;

/**
 * This file was automatically generated.
 */
class Script {

	public function __construct ($zap) {
		$this->zap = $zap;
	}

	/**
	 * Lists the script engines available
	 */
	public function listEngines() {
		return $this->zap->request($this->zap->base . 'script/view/listEngines/')->{'listEngines'};
	}

	/**
	 * Lists the scripts available, with its engine, name, description, type and error state.
	 */
	public function listScripts() {
		return $this->zap->request($this->zap->base . 'script/view/listScripts/')->{'listScripts'};
	}

	/**
	 * Enables the script with the given name
	 */
	public function enable($scriptname, $apikey='') {
		return $this->zap->request($this->zap->base . 'script/action/enable/', array('scriptName' => $scriptname, 'apikey' => $apikey));
	}

	/**
	 * Disables the script with the given name
	 */
	public function disable($scriptname, $apikey='') {
		return $this->zap->request($this->zap->base . 'script/action/disable/', array('scriptName' => $scriptname, 'apikey' => $apikey));
	}

	/**
	 * Loads a script into ZAP from the given local file, with the given name, type and engine, optionally with a description
	 */
	public function load($scriptname, $scripttype, $scriptengine, $filename, $scriptdescription=NULL, $apikey='') {
		$params = array('scriptName' => $scriptname, 'scriptType' => $scripttype, 'scriptEngine' => $scriptengine, 'fileName' => $filename, 'apikey' => $apikey);
		if ($scriptdescription !== NULL) {
			$params['scriptDescription'] = $scriptdescription;
		}
		return $this->zap->request($this->zap->base . 'script/action/load/', $params);
	}

	/**
	 * Removes the script with the given name
	 */
	public function remove($scriptname, $apikey='') {
		return $this->zap->request($this->zap->base . 'script/action/remove/', array('scriptName' => $scriptname, 'apikey' => $apikey));
	}

	/**
	 * Runs the stand alone script with the give name
	 */
	public function runStandAloneScript($scriptname, $apikey='') {
		return $this->zap->request($this->zap->base . 'script/action/runStandAloneScript/', array('scriptName' => $scriptname, 'apikey' => $apikey));
	}

}


text:
install.packages(c('rzmq','repr','IRkernel','IRdisplay'),
                 repos = c('http://irkernel.github.io/', getOption('repos')),
                 type = 'source')

IRkernel::installspec(user = FALSE)


text:
include(FindPackageHandleStandardArgs)

if (NOT WIN32)
  find_package(PkgConfig REQUIRED)

  pkg_check_modules(GLIB2 "glib-2.0>=${GLIB_REQUIRED}" "gobject-2.0>=${GLIB_REQUIRED}")

  find_package_handle_standard_args(GLib DEFAULT_MSG GLIB2_LIBRARIES GLIB2_CFLAGS)

endif(NOT WIN32)


text:
CDN (Powered by Fastly)
=======================

The PSF has a CDN donated by Fastly which is available to any service hosted on
our infrastructure. This CDN is running a geo distributed varnish cluster
which respects various headers for handling caching. HTTPS is available from
fastly for any ``*.python.org`` domain including the EV Certificate.

The setup of our infrastructure means that the only configuration which needs
to change to move a service between fronted by the CDN or not is what address
the service CNAME points to. Everything else is identically configured.

Setup a Service with Fastly
===========================

Services served through Fastly are still hosted through the loadbalancers and
should be configured as normal there. Note that if you're using nginx you can
include the ``fastly_params`` file inside the server block to set up some
common settings for fastly backends (``include fastly_params;``). In order to
configure these services in Fastly you should do:

#. Create a new Service at Fastly.
#. Configure the backends in Fastly to match all of the loadbalancers
   (currently ``lb0.psf.io`` and ``lb1.psf.io``) on port ``20004``. These
   should also have TLS setup with the hostname ``lb.psf.io``, and the PSF_CA
   certificate (see below). The SSL Client Certificate and Key should be blank.
#. Configure a Header under the "Content" tab to set a ``Fastly-Token`` header
   set to the static value from ``pillar/prod/secrets/fastly.sls``.

PSF_CA
------

The current value of the PSF CA is::

    -----BEGIN CERTIFICATE-----
    MIIFIjCCBAqgAwIBAgIVAJRtfWNZoFYyqBv7Ol8/voe3sH/gMA0GCSqGSIb3DQEB
    CwUAMIGsMQswCQYDVQQGEwJVUzELMAkGA1UECBMCTkgxEjAQBgNVBAcTCVdvbGZl
    Ym9ybzEjMCEGA1UEChMaUHl0aG9uIFNvZnR3YXJlIEZvdW5kYXRpb24xHDAaBgNV
    BAsTE0luZnJhc3RydWN0dXJlIFRlYW0xDzANBgNVBAMUBlBTRl9DQTEoMCYGCSqG
    SIb3DQEJARYZaW5mcmFzdHJ1Y3R1cmVAcHl0aG9uLm9yZzAeFw0xNDEwMTkxOTUx
    MTlaFw0xOTEwMTgxOTUxMTlaMIGsMQswCQYDVQQGEwJVUzELMAkGA1UECBMCTkgx
    EjAQBgNVBAcTCVdvbGZlYm9ybzEjMCEGA1UEChMaUHl0aG9uIFNvZnR3YXJlIEZv
    dW5kYXRpb24xHDAaBgNVBAsTE0luZnJhc3RydWN0dXJlIFRlYW0xDzANBgNVBAMU
    BlBTRl9DQTEoMCYGCSqGSIb3DQEJARYZaW5mcmFzdHJ1Y3R1cmVAcHl0aG9uLm9y
    ZzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALPFdrBHn1e3j4HiWKLr
    VKOD07y1Vv+qhJbIEhcGS71aqjBvrdV5enKTdTMp+/66l/hZs272/w8ozNMy7fTk
    zmQ9CTw+JALYuRkuY2IKDx1TYviu/r9ssLwUdCknIMD5iSlrcBzW1XXB/FnoN0Qd
    lrxjYLUbG5b+xVULG+gCg26yMk5iJoAqwRAK3iiBdRzZBP+lOspS2bC6H9srsmJb
    26bOpofOBZa3Mt+xDtspA6w2QOMMPPPxbUV4VvSdazpNjAkYEsR0FKivWTHUDe9m
    wATEXxDX4XZoNM0L2vc7DkCS0MgyJy3gHT5sVj2+hWUEYH67WSu3TvotWMMzckrC
    c68CAwEAAaOCATcwggEzMBIGA1UdEwEB/wQIMAYBAf8CAQAwDgYDVR0PAQH/BAQD
    AgEGMB0GA1UdDgQWBBRvXo8qm3WXAuvKe5Ig5AuE28obNjCB7QYDVR0jBIHlMIHi
    gBRvXo8qm3WXAuvKe5Ig5AuE28obNqGBsqSBrzCBrDELMAkGA1UEBhMCVVMxCzAJ
    BgNVBAgTAk5IMRIwEAYDVQQHEwlXb2xmZWJvcm8xIzAhBgNVBAoTGlB5dGhvbiBT
    b2Z0d2FyZSBGb3VuZGF0aW9uMRwwGgYDVQQLExNJbmZyYXN0cnVjdHVyZSBUZWFt
    MQ8wDQYDVQQDFAZQU0ZfQ0ExKDAmBgkqhkiG9w0BCQEWGWluZnJhc3RydWN0dXJl
    QHB5dGhvbi5vcmeCFQCUbX1jWaBWMqgb+zpfP76Ht7B/4DANBgkqhkiG9w0BAQsF
    AAOCAQEAR57NNg5fvj+tSrgdu6CmXvP65E1buECC7dRedRnJ2yDenI8o1jiFmMBD
    jG/+x0whosZREsQIdRIm0f+1cmiN7voYs3tJB8j2EKH9i3+usifQJiOxN0jv2i0E
    7ty2LLKwVhvYZQ8VxHGFdGnwUwGqKFtg+0C0ybrSmklGPY7uTxCio2sx28x4tIuU
    HhNzp4DeCelgj+1OodrBW0GcZm1O9fnCew3nsuiN+E94/ptaN5F0FkLuEYC8qqq9
    AqD60RC7HEJDWY+I33sSG0qcCNmkbyHkUUFxgD4+OrM7YA9/X9mixvRaUeS78EtS
    YdKdKzNYasuc6cNDSo2I7HccjGE3ig==
    -----END CERTIFICATE-----


text:
package com.jscheng.mr_horse.adapter;

import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.jscheng.mr_horse.R;
import com.jscheng.mr_horse.model.QuestionDoneType;
import com.jscheng.mr_horse.model.QuestionModel;
import com.jscheng.mr_horse.model.PatternStatus;
import com.jscheng.mr_horse.model.QuestionType;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by cheng on 17-1-7.
 */
public class AnswerViewPaperAdapter extends PagerAdapter {
    private static int patternStatus;//看题模式,做题模式
    private Context mContext;
    private List<QuestionModel> mData;
    private LinkedList<View> mViewCache = null;
    private LayoutInflater mLayoutInflater = null;
    private List<AnswerPageChangeListener> listenerList = null;

    public AnswerViewPaperAdapter(Context context,List data,int patternStatus){
        this.mContext = context;
        this.mData = data;
        this.mViewCache = new LinkedList<>();
        this.mLayoutInflater = LayoutInflater.from(mContext) ;
        this.listenerList = new ArrayList<>();
        this.patternStatus = patternStatus;
    }

    public void addAnswerPageListener(AnswerPageChangeListener listener){
        if(listenerList!=null){
            listenerList.add(listener);
        }
    }

    public void removeAnswerPageListener(AnswerPageChangeListener listener){
        if(listenerList!=null && listenerList.contains(listener)){
            listenerList.remove(listener);
        }
    }

    @Override
    public Object instantiateItem(ViewGroup container, final int position) {
        SingleViewHolder viewHolder = null;
        View convertView = null;
        final QuestionModel model = mData.get(position);

        if(mViewCache.size() == 0){
            convertView = this.mLayoutInflater.inflate(R.layout.pageview_item,
                    null ,false);
            TextView textView = (TextView)convertView.findViewById(R.id.question_text);
            ListView listView = (ListView)convertView.findViewById(R.id.option_listview);
            Button confirmBtn = (Button)convertView.findViewById(R.id.confirm);

            viewHolder = new SingleViewHolder();
            viewHolder.textView = textView;
            viewHolder.listView = listView;
            viewHolder.confirmBtn = confirmBtn;
            convertView.setTag(viewHolder);
        }else {
            convertView = mViewCache.removeFirst();
            viewHolder = (SingleViewHolder)convertView.getTag();
        }
        viewHolder.textView.setText("("+model.getQuestionType().toString()+") "+model.getQuestion());
        final AnswerListViewAdapter listViewAdapter = new AnswerListViewAdapter(mContext,model);
        viewHolder.listView.setAdapter(listViewAdapter);

        if (patternStatus == PatternStatus.DATI_PATTERN) {//答题模式
            datiPattern(viewHolder,listViewAdapter,model,position);
        }
        else {//看题模式
            beitiPattern(viewHolder);
        }

        container.addView(convertView ,ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT );
        return convertView;
    }

    private void datiPattern(SingleViewHolder viewHolder,final AnswerListViewAdapter listViewAdapter,final QuestionModel model, final int position){

        if( model.getNewDone()==QuestionDoneType.NOT_DONE){//未作题
            ((AnswerListViewAdapter) viewHolder.listView.getAdapter()).hideAnswer();
            viewHolder.listView.setOnItemClickListener(new OptionItemListener(position,model));
            if (model.getQuestionType() == QuestionType.MULTIPLE ) {//多选模式
                viewHolder.confirmBtn.setVisibility(View.VISIBLE);
                viewHolder.confirmBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        confirmAnswer(position,listViewAdapter, model);
                    }
                });
            }else {
                viewHolder.confirmBtn.setVisibility(View.GONE);
            }

        }else {//已经做了
            viewHolder.confirmBtn.setVisibility(View.GONE);
            ((AnswerListViewAdapter)viewHolder.listView.getAdapter()).showAnswer(true);
        }
    }

    private void beitiPattern(SingleViewHolder viewHolder){
        viewHolder.confirmBtn.setVisibility(View.GONE);
        ((AnswerListViewAdapter)viewHolder.listView.getAdapter()).showAnswer(false);
    }

    public int getCount() {
        return this.mData.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view==object;
    }

    @Override
    public int getItemPosition(Object object) {
        // TODO Auto-generated method stub
        return POSITION_NONE;
    }

    @Override
    public void restoreState(Parcelable arg0, ClassLoader arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public Parcelable saveState() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        View contentView = (View) object;
        container.removeView(contentView);
        this.mViewCache.add(contentView);
    }

    public QuestionType getItemType(int postion){
        return mData.get(postion).getQuestionType();
    }

    public final class SingleViewHolder{
        public TextView textView ;
        public ListView listView;
        public Button confirmBtn;
    }

    public class AnswerViewPaperListener implements ViewPager.OnPageChangeListener{

        public AnswerViewPaperListener(){
            super();
        }
        /**
         * @param position 当前页面,及你点击滑动的页面
         * @param positionOffset 当前页面偏移的百分比
         * @param positionOffsetPixels 当前页面偏移的像素位置
         */
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        /**
         * @param position (int) 判断当前是哪个view
         */
        @Override
        public void onPageSelected(int position) {
            if(listenerList!=null && !listenerList.isEmpty()){
                for(AnswerPageChangeListener listener:listenerList){
                    listener.onPageSelected(position);
                }
            }
        }

        /**
         * @param state 1正在滑动,2默示滑动完毕了,0什么都没做。
         */
        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    public interface AnswerPageChangeListener{
        void onPageSelected(int position);
        void onAnswerRight(int postion);
        void onAnswerWrong(int postion);
    }

    private class OptionItemListener implements AdapterView.OnItemClickListener{
        private QuestionModel questionModel;
        private int position;

        public OptionItemListener(int position,QuestionModel questionModel){
            this.questionModel = questionModel;
            this.position = position;
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int optionPostion, long id) {

            if (questionModel.getNewDone()!=QuestionDoneType.NOT_DONE)return;

            if(questionModel.getUserAnswerList().contains(optionPostion)){
                questionModel.getUserAnswerList().remove((Integer)(optionPostion));
            }else {
                questionModel.getUserAnswerList().add(optionPostion);
            }
            if(questionModel.getQuestionType()==QuestionType.MULTIPLE)
                ((AnswerListViewAdapter)parent.getAdapter()).clickOption(optionPostion);
            else {
                confirmAnswer(position,(AnswerListViewAdapter)parent.getAdapter(),questionModel);
            }
        }
    }

    private void confirmAnswer(int position,AnswerListViewAdapter adapter,QuestionModel questionModel){

        List list1 = questionModel.getAnswerList();
        Collections.sort(list1);
        List list2 = questionModel.getUserAnswerList();
        Collections.sort(list2);
        if(list1.equals(list2)) {//答案正确
            questionModel.setNewDone(QuestionDoneType.DONE_RIGHT);
            adapter.showAnswer(true);
            if(listenerList!=null && !listenerList.isEmpty()){
                for(AnswerPageChangeListener listener:listenerList){
                    listener.onAnswerRight(position);
                }
            }
        }else {
            questionModel.setNewDone(QuestionDoneType.DONE_WRONG);
            adapter.showAnswer(true);
            if(listenerList!=null && !listenerList.isEmpty()){
                for(AnswerPageChangeListener listener:listenerList){
                    listener.onAnswerWrong(position);
                }
            }
        }
        notifyDataSetChanged();
    }

    public void changePatternStatus(int status){
        patternStatus = status;
        this.notifyDataSetChanged();
    }

}


text:
from day16_part1 import *

def filter_aunt(key, value):
    if key in ['cats', 'trees']:
        return lambda aunt: aunt[key] is None or aunt[key] > value
    elif key in ['pomeranians', 'goldfish']:
        return lambda aunt: aunt[key] is None or aunt[key] < value
    else:
        return lambda aunt: aunt[key] in [None, value]

# Main
known = {'children':3, 'cats':7, 'samoyeds':2, 'pomeranians':3, 'akitas':0, 'vizslas':0, 'goldfish':5, 'trees':3, 'cars':2, 'perfumes':1}
print(aunt_number(filter_aunts(filter_aunt, known, parse_input(sys.stdin.readlines()))))


text:
# myApp/config/i18n.js
### Purpose
This file contains your Sails app's [supported locales](http://en.wikipedia.org/wiki/Locales).

<docmeta name="uniqueID" value="i18njs28306">
<docmeta name="displayName" value="i18n.js">

```
/**
 * Internationalization / Localization Settings
 * (sails.config.i18n)
 *
 * If your app will touch people from all over the world, i18n (or internationalization)
 * may be an important part of your international strategy.
 *
 *
 * For more information, check out:
 * http://links.sailsjs.org/docs/config/i18n
 */

module.exports.i18n = {

  // Which locales are supported?
  locales: ['en', 'es', 'fr', 'de']

};

```


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="display.xsl" type="text/stylesheet" alternate="yes"?>
<a/>


text:
const util = require('util');
const sqlite3 = require('sqlite3').verbose();
const Base = require('db-migrate-base');
const Promise = require('bluebird');

var defaultMode = sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE;
var internals = {};

var Sqlite3Driver = Base.extend({
  init: function (connection, intern) {
    this.log = intern.mod.log;
    this.type = intern.mod.type;
    this._escapeString = '"';
    this._super(internals);
    this.connection = connection;
  },

  _translateSpecialDefaultValues: function (
    spec,
    options,
    tableName,
    columnName
  ) {
    switch (spec.defaultValue.special) {
      case 'CURRENT_TIMESTAMP':
        spec.defaultValue.prep = 'CURRENT_TIMESTAMP';
        break;
      default:
        this.super(spec, options, tableName, columnName);
        break;
    }
  },

  createDatabase: function (cb) {
    // sqlite does this automatically if needed
    return Promise.resolve(null).nodeify(cb);
  },

  startMigration: function (cb) {
    if (!internals.notransactions) {
      return Promise.promisify(this.runSql.bind(this))(
        'BEGIN TRANSACTION;'
      ).nodeify(cb);
    } else return Promise.resolve().nodeify(cb);
  },

  endMigration: function (cb) {
    if (!internals.notransactions) {
      return Promise.promisify(this.runSql.bind(this))('COMMIT;').nodeify(cb);
    } else return Promise.resolve(null).nodeify(cb);
  },

  mapDataType: function (str) {
    switch (str) {
      case this.type.DATE_TIME:
        return 'datetime';
      case this.type.TIME:
        return 'time';
    }
    return this._super(str);
  },

  switchDatabase: function (options, callback) {
    callback(null);
  },

  createColumnDef: function (name, spec, options) {
    name = '"' + name + '"';
    var dType = this.mapDataType(spec.type);
    var len = spec.length ? util.format('(%s)', spec.length) : '';
    var constraint = this.createColumnConstraint(spec, options);

    if (spec.type === this.type.INTEGER) len = '';

    return {
      foreignKey: null,
      constraints: [name, dType, len, constraint].join(' ')
    };
  },

  createColumnConstraint: function (spec, options) {
    var constraint = [];
    if (spec.primaryKey && options.emitPrimaryKey) {
      constraint.push('PRIMARY KEY');
      if (spec.autoIncrement) {
        constraint.push('AUTOINCREMENT');
      }
    }

    if (spec.notNull === true) {
      constraint.push('NOT NULL');
    }

    if (spec.unique) {
      constraint.push('UNIQUE');
    }

    if (spec.defaultValue !== undefined) {
      constraint.push('DEFAULT');

      if (typeof spec.defaultValue === 'string') {
        constraint.push('"' + spec.defaultValue + '"');
      } else if (typeof spec.defaultValue.prep === 'string') {
        constraint.push(spec.defaultValue.prep);
      } else {
        constraint.push(spec.defaultValue);
      }
    }

    return constraint.join(' ');
  },

  renameTable: function (tableName, newTableName, callback) {
    var sql = util.format(
      'ALTER TABLE %s RENAME TO %s',
      tableName,
      newTableName
    );

    return this.runSql(sql).nodeify(callback);
  },

  // removeColumn: function(tableName, columnName, callback) {
  // },

  // renameColumn: function(tableName, oldColumnName, newColumnName, callback) {
  // };

  // changeColumn: function(tableName, columnName, columnSpec, callback) {
  // },

  runSql: function () {
    var callback = arguments[arguments.length - 1];
    var params = arguments;

    this.log.sql.apply(null, arguments);
    if (internals.dryRun) {
      return Promise.resolve().nodeify(callback);
    }

    return new Promise(
      function (resolve, reject) {
        var prCB = function (err, data) {
          return err ? reject(err) : resolve(data);
        };

        if (typeof params[params.length - 1] === 'function') {
          params[params.length - 1] = prCB;
        } else params[params.length++] = prCB;

        if (
          params.length === 1 ||
          (callback && typeof params[1] === 'function')
        ) {
          this.connection.exec.apply(this.connection, params);
        } else this.connection.run.apply(this.connection, params);
      }.bind(this)
    ).nodeify(callback);
  },

  all: function () {
    var params = arguments;

    this.log.sql.apply(null, params);

    return new Promise((resolve, reject) => {
      this.connection.all(params[0], function (err, result) {
        return err ? reject(err) : resolve(result);
      });
    }).nodeify(params[1]);
  },

  close: function (callback) {
    this.connection.close();

    if (typeof callback === 'function') callback(null);
    else return Promise.resolve();
  }
});

Promise.promisifyAll(Sqlite3Driver);

exports.connect = function (config, intern, callback) {
  var mode = config.mode || defaultMode;

  internals = intern;

  if (config.db) {
    callback(null, new Sqlite3Driver(config.db));
  } else {
    if (typeof config.filename === 'undefined') {
      console.error('filename is required in database.json');
      return;
    }
    var db = new sqlite3.Database(config.filename, mode);
    db.on('error', callback);
    db.on('open', function () {
      callback(null, new Sqlite3Driver(db, intern));
    });
  }
};


text:
package business

import (
	"backend/common"
	"backend/common/messaging"
	req "backend/common/request"
	"backend/common/sql"
	tx "backend/common/transaction"
	"backend/domain"
	"backend/errors"
	"backend/storage"
	"fmt"
	log "github.com/cihub/seelog"
	"github.com/ericmort/go-clickhouse"
	"github.com/jimlawless/whereami"
	"strconv"
	"strings"
	"time"
)

var queueManager messaging.QueueManager

func StartQueueManager() {
	queueManager = messaging.NewQueueManager(ProcessEvents)
}

var datasetsInCache = (&common.Cache{}).Init()

func SaveEvents(projectId, nsName, datasetName string, events messaging.EventArray, context *req.RequestContext) *errors.Error {
	name := datasetName
	if !domain.IsValidDatasetName(name) {
		err := errors.New("ErrBadRequest", "name not valid", "name was not valid (cannot start with numbers).")
		return err

	}

	dataset, err := storage.FindDatasetByName(nsName, name, projectId, context)
	if err != nil && err.Code != "ErrDatasetNotFound" {
		return err
	}
	if err != nil && err.Code == "ErrDatasetNotFound" {
		log.Tracef("Could not find dataset: %s", err)
		if err.Code == "ErrDatasetNotFound" {
			pk := name + "_pk"

			cols := []interface{}{
				map[string]interface{}{
					"name":     pk,
					"dataType": "date",
					"default":  "now()",
				},
			}
			data := map[string]interface{}{
				"name":       name,
				"type":       "fact",
				"updateMode": "append",
				"namespace":  nsName,
				"columns":    cols,
				"primaryKey": pk,
				"dateColumn": pk,
			}
			dataset, err = CreateDataset(projectId, data, context)
			if err != nil {
				return err
			}
			/*columns := domain.Columns{
				{Name: pk, DataType: "date", Default: "now()"},
				{Name: "__created", DataType: "datetime", Default: "now()"},
			}

			namespace, err := business.CreateNamespace(projectId, map[string]interface{}{"name": nsName}, context)
			log.Tracef("RETURNED: %s %s", namespace, err)
			if err != nil && err.Code != "ErrNamespaceExists" {
				return rq.ApiError(context, err)
			}
			created := time.Now()
			dataset = &domain.Dataset{DatasetId: common.UniqueId(), ProjectId: projectId, Name: name, NamespaceId: namespace.NamespaceId, Type: "fact", Columns: columns, PrimaryKey: pk, Created: created, Updated: created, DateColumn: pk}
			err = storage.CreateDataset(dataset, context)
			if err != nil {
				return rq.ApiError(context, err)
			}*/
		} else {
			return err
		}
	}

	return QueueEvents(projectId, dataset, events, context)

}

func QueueEvents(projectId string, dataset *domain.Dataset, events messaging.EventArray, ctx *req.RequestContext) *errors.Error {
	if projectId == "" {
		return errors.New("ErrBadRequest", "projectId", "projectId was empty or not a valid string.")
	}
	created := time.Now()

	ev := &messaging.Events{DatasetId: dataset.DatasetId, ProjectId: projectId, Created: created, Events: events}

	queue := "events:" + projectId + ":" + dataset.Name
	err := queueManager.Add(queue, ev)
	if err != nil {
		return err
	}

	return nil
}

func ProcessEvents(queue string, batch messaging.Batch, events messaging.EventArray) bool {
	context := req.NewRequestContext(nil, nil)
	log.Tracef("Process count: %d", len(events))

	datasetId := batch[0].Events.DatasetId
	context.ClickHouseTransaction.(*tx.ClickHouseTransaction).Engine.(*sql.ClickHouseSqlEngine).SetDefaultDatabase("pr_" + batch[0].Events.ProjectId)

	dataset, err := storage.FindDatasetById(datasetId, context)
	if err != nil {
		log.Errorf("PANIC from FindNamespaceById: %s", err)
		return true
	}
	dataset.Namespace, err = storage.FindNamespaceById(dataset.NamespaceId, context)
	if err != nil {
		log.Errorf("PANIC from FindNamespaceById2: %s", err)
		return true
	}
	if err := addColumnsFromRelationshipTrees(dataset, events, context); err != nil {
		log.Errorf("PANIC from addColumnsFromRelationshipTrees: %s", err)
		return true
	}

	var foundChanges bool
	for _, event := range events {
		didAdd := addColumnsIfNecessary(dataset, event, context)
		if didAdd {
			foundChanges = true
		}
	}

	if foundChanges {
		log.Tracef("foundChanges, calling updateDatasetColumns")
		err := updateDatasetColumns(dataset, context)
		if err != nil {
			log.Errorf("updateDasetColumns returned error: %s", err)
			return true
		}
	}

	if err = insertRows(dataset, events, context); err != nil {
		log.Errorf("insertRows: returned error: %s", err)
		log.Errorf("insertRows: will try createDatasetInClickHouse: %s", err)
		return false
	}
	return true
}

func addColumnsFromRelationshipTrees(dataset *domain.Dataset, events messaging.EventArray, ctx *req.RequestContext) *errors.Error {
	trees, err := GetRelationshipTreesForDataset(dataset.DatasetId, ctx)
	log.Tracef("%s Logdata: relationshipTrees for dataset %s=%s", whereami.WhereAmI(), dataset.Name, common.ToJson(trees))
	if err != nil {
		return err
	}

	for _, tree := range trees {
		if tree.ResolutionMode == "" || tree.ResolutionMode == "onIngestion" {
			log.Tracef("%s Logdata: tree.ResolutionMode is onIngestion for tree %s", whereami.WhereAmI(), tree.Name)
			if err := addColumnsFromRelationshipTree(dataset, tree, events, ctx); err != nil {
				return err
			}
		}
	}
	return nil
}

func addColumnsFromRelationshipTree(dataset *domain.Dataset, tree *domain.RelationshipTree, events messaging.EventArray, ctx *req.RequestContext) *errors.Error {
	return addColumnsFromRelationship(dataset, tree.Children, events, ctx)
}

func addColumnsFromRelationship(dataset *domain.Dataset, children []*domain.Relationship, events messaging.EventArray, ctx *req.RequestContext) *errors.Error {
	for _, child := range children {
		log.Tracef("Working on child: %s", common.ToJson(child))
		for i, event := range events {
			event, ok := event.(map[string]interface{})
			if !ok {
				continue
			}

			fromValue := event[child.FromColumn]
			if fromValue != nil {
				err := addColumnsInRelatedDataset(child, dataset.ProjectId, toString(fromValue), event, ctx)
				if err != nil {
					log.Errorf("addColumnsFromRelationship2: i=%d, event=%s, err=%s", i, event, err)
					return err
				}
			} else {
				log.Tracef("fromValue was nil, ie not found in event: event=%s, dataset=%s, FromColumn=%s", dataset.Name, event, child.FromColumn)
			}

		}
		if err := addColumnsFromRelationship(dataset, child.Children, events, ctx); err != nil {
			log.Errorf("addColumnsFromRelationship1: %s", err)
			return err
		}

	}
	return nil
}

func addColumnsInRelatedDataset(child *domain.Relationship, projectId string, fromValue string, event map[string]interface{}, ctx *req.RequestContext) *errors.Error {
	// has the dataset been loaded?
	//log.Tracef("%s Logdata: %s=%s", whereami.WhereAmI(), child.ToDimen)
	rowCache, err := loadDatasetIfNeeded(projectId, child.ToDimension, child.ToColumn, ctx)
	if err != nil {
		return err
	}
	//keyValue := projectId + ":" + child.ToDimension + ":" + child.ToColumn + ":" + fromValue
	keyValue := fromValue
	object := rowCache.Get(keyValue)
	if object == nil {
		log.Tracef("Key not found after load, missing key? (%s)", keyValue)
		if event["__skiprows"] == nil {
			event["__skiprows"] = make([]map[string]interface{}, 0)
		}
		ev := make(map[string]interface{})
		ev["toDimension"] = child.ToDimension
		ev["toColumn"] = child.ToColumn
		ev["fromValue"] = fromValue
		event["__skiprows"] = append(event["__skiprows"].([]map[string]interface{}), ev)
		//log.Tracef("__skiprows: dataset=%s, projectId=%s, key=%s, event[skiprows]=%v", child.ToDimension, projectId, key, event["__skiprows"])
		return nil
	}
	objectasmap, ok := object.(map[string]interface{})
	if !ok {
		panic(fmt.Sprintf("object was not map, was %T (%v)", object, object))
	}
	for _, col := range child.ExposeColumns {
		event[col] = objectasmap[col]
	}
	for _, child := range child.Children {
		event[child.FromColumn] = objectasmap[child.FromColumn]
	}
	log.Tracef("event: %s, objectasmap: %s", common.ToJson(event), common.ToJson(objectasmap))
	return nil
}

func loadDatasetIfNeeded(projectId, datasetName, pkColumn string, ctx *req.RequestContext) (*common.UnsafeCache, *errors.Error) {
	key := projectId + ":" + datasetName
	log.Tracef("Looking for dataset in datasetsInCache('%s')", key)
	rowCache := datasetsInCache.Get(key)
	if rowCache == nil {
		log.Tracef("Key not found, will load related dataset.")
		rowCache = (&common.UnsafeCache{}).Init()
		if err := loadRelatedDataset(projectId, datasetName, pkColumn, rowCache.(*common.UnsafeCache), ctx); err != nil {
			return nil, err
		}
		datasetsInCache.Set(key, rowCache)
	}
	return rowCache.(*common.UnsafeCache), nil
}

func loadRelatedDataset(projectId, datasetName, pkColumn string, rowCache *common.UnsafeCache, ctx *req.RequestContext) *errors.Error {
	log.Tracef("loadRelatedDataset: will load %s", datasetName)

	namespace := namespaceOf(datasetName)

	dataset, err := storage.FindDatasetByName(namespace, datasetName, projectId, ctx)
	if err != nil {
		log.Errorf("loadRelatedDataset1: err=%s", err)
		return err
	}

	log.Tracef("loadRelatedDataset2: dataset=%s", common.ToJson(dataset))
	datasetName = flattenNamespace(dataset.NamespaceName) + "_" + datasetName
	columnsList := dataset.ColumnsList()
	primaryKey := dataset.PrimaryKey
	sqlstr := fmt.Sprintf("select %s from pr_%s.%s all inner join (select max(__created) as __created, %s from pr_%s.%s group by %s) using __created, %s",
		strings.Join(columnsList, ","), projectId, datasetName, primaryKey, projectId, datasetName, primaryKey, primaryKey)
	log.Tracef("loadRelatedDataset3: sql=%s", sqlstr)
	rows, err := ctx.ClickHouseTransaction.Query(sqlstr, nil)
	defer rows.Close()
	if err != nil {
		log.Errorf("loadRelatedDataset2: sql=%s, err=%s", ctx.ClickHouseTransaction.Executor().GetExecutedSql(), err)
		return err
	}
	indexOfPrimaryKey := dataset.Columns.IndexOf(pkColumn)
	for rows.Next() {
		cols := make([]interface{}, 0)
		for _, col := range dataset.Columns {
			cols = append(cols, columnTypeMoveMe(col.DataType))
		}
		err := rows.Scan(cols)
		if err != nil {
			log.Errorf("loadRelatedDataset4: err=%s", err)
			return err
		}
		pkValue := cols[indexOfPrimaryKey]

		key := toString(pkValue)
		object := make(map[string]interface{})
		for i, col := range columnsList {
			object[col] = dereference(cols[i])
		}
		log.Tracef("Adding to cache1: %s: %s", key, common.ToJson(object))
		rowCache.Set(key, object)

	}
	return nil
}

func addColumnsIfNecessary(dataset *domain.Dataset, event interface{}, ctx *req.RequestContext) bool {
	var didAdd bool
	ev, ok := event.(map[string]interface{})
	if !ok {
		return false
	}
	if ev["__skiprows"] != nil {
		return false
	}
	//log.Tracef("addColumnsIfNecessary: existing columns: %s", common.ToJson(dataset.Columns))
	for col, value := range ev {
		typ := guessType(value)
		if typ != "unknown" {
			column := &domain.Column{Name: col, DataType: typ, IsNew: true}

			if !dataset.HasColumn(col) {
				dataset.AddColumn(column)
				log.Tracef("Added column %s", column.Name)
				didAdd = true
			}
		} else {
			log.Tracef("Deleting unknown type %T,%s", value, value)
			delete(ev, col)
		}
	}

	return didAdd

}

func insertRows(dataset *domain.Dataset, events messaging.EventArray, context *req.RequestContext) *errors.Error {
	rows := make(clickhouse.Rows, 0)
	errorRows := make(clickhouse.Rows, 0)

	errorLogDataset, err := storage.FindDatasetByName("/", "__ingestion_log", dataset.ProjectId, context)
	if err != nil {
		return err
	}
	log.Tracef("errorLogDataset: %s", common.ToJson(errorLogDataset))
	includeCreated := false
	ev, ok := events[0].(map[string]interface{})
	if ok && ev["__created"] != nil {
		includeCreated = true
	}
	log.Tracef("includeCreated: %t (%s)", includeCreated, dataset.Name)

	columns := columnsList(dataset, includeCreated)
	skipRow := false
	for _, event := range events {
		event, ok := event.(map[string]interface{})
		if !ok {
			continue
		}

		if event["__skiprows"] != nil {
			ev := event["__skiprows"].([]map[string]interface{})
			for _, e := range ev {
				toDimension := e["toDimension"]
				colName := e["toColumn"]
				fromValue := e["fromValue"]
				delete(event, "__skiprows")
				msg := fmt.Sprintf("Dataset: %s, Level: error, Type: fromvaluenotfound, event: %v, toDimension: %s, toColumn: %s, fromValue: %v)",
					dataset.Name, event, toDimension, colName, fromValue)
				errorRows = append(errorRows, clickhouse.Row([]interface{}{msg}))
			}
			continue

		} else {
			skipRow = false
			row := make([]interface{}, 0)
			var colName string
			for _, column := range dataset.Columns {
				colName = column.Name

				if colName == dataset.Name+"_pk" || (!includeCreated && colName == "__created") {
					continue
				}
				if event[colName] == nil {
					row = append(row, defaultValue(column))
				} else {
					if isTypeCompatible(guessType(event[colName]), column.DataType) {
						row = append(row, event[colName])
					} else {
						msg := fmt.Sprintf("Dataset: %s, Level: error, Type: typemismatch, event: %v, column: %s, offending value: %v, actual type: %s, expected type: %s)", dataset.Name, event, colName, event[colName], guessType(event[colName]), column.DataType)
						errorRows = append(errorRows, clickhouse.Row([]interface{}{msg}))
						skipRow = true
						break
					}
				}
			}
			if !skipRow {
				rows = append(rows, row)
			}
		}

	}

	log.Tracef("Will insert %d rows into ClickHouse and PipelineDb", len(rows))

	datasetName := clickhouseifyDatasetPath(dataset.NamespaceName, dataset.Name)
	var attempts int
	for {
		if err := insertRowsIntoClickHouse(dataset, rows, columns, context); err != nil && attempts < 2 {
			if strings.Contains(err.Details, "DB::Exception: No such dictionary: ") && attempts < 3 {
				attempts++
				time.Sleep(6 * time.Second)
				continue
			} else if strings.Contains(err.Details, fmt.Sprintf("DB::Exception: Table pr_%s.%s doesn't exist.", dataset.ProjectId, datasetName)) && attempts < 2 {
				if err := storage.EnsureDatasetInClickHouse(dataset, context); err != nil {
					log.Errorf("insertRows: createDatasetInClickHouse failed: %s", err)
				}
				attempts++
				continue
			}
		}
		break
	}

	if dataset.Type == "dimension" {
		updateDatasetCache(dataset, columns, rows, context)
		recreateViewForCurrentValues(dataset, context)

		// TODO: fix does nothing if dimension is not a dictionary
		touchDictionaryConfig(dataset, context)
	}
	if len(errorRows) > 0 {
		if err := insertRowsIntoClickHouse(errorLogDataset, errorRows, []string{"message"}, context); err != nil {
			return err
		}
	}
	/*if err := insertRowsIntoPipelinedb(dataset, rows, columns); err != nil {
		return err
	}*/
	return nil
}

func updateDatasetCache(dataset *domain.Dataset, columns clickhouse.Columns, rows clickhouse.Rows, ctx *req.RequestContext) *errors.Error {
	projectId := dataset.ProjectId
	datasetName := dataset.Name
	pkColumn := dataset.PrimaryKey
	rowCache, err := loadDatasetIfNeeded(projectId, datasetName, pkColumn, ctx)
	if err != nil {
		return err
	}
	indexOfPrimaryKey := dataset.Columns.IndexOf(pkColumn)

	for _, row := range rows {
		log.Tracef("updateDatasetCache: %d.%v.%s", indexOfPrimaryKey, row, pkColumn)
		pkValue := row[indexOfPrimaryKey]
		key := toString(pkValue)

		object := make(map[string]interface{})
		for i, col := range columns {
			object[col] = row[i]
		}
		log.Tracef("Updating cache: %s: %s", key, common.ToJson(object))
		rowCache.Set(key, object)
	}
	return nil
}

func recreateViewForCurrentValues(dataset *domain.Dataset, context *req.RequestContext) *errors.Error {
	if err := dropViewForCurrentValues(dataset, context); err != nil {
		return err
	}
	if err := createViewForCurrentValues(dataset, context); err != nil {
		return err
	}
	return nil
}

func dropViewForCurrentValues(dataset *domain.Dataset, context *req.RequestContext) *errors.Error {
	viewname := flattenNamespace(dataset.NamespaceName) + "_" + dataset.Name + "_current"
	sqlstr := fmt.Sprintf("drop table if exists pr_%s.%s", dataset.ProjectId, viewname)

	err := context.ClickHouseTransaction.Execute("dropCurrentView", sqlstr)
	log.Tracef("dropViewForCurrentValues: sql=%s, err=%s", sqlstr, err)
	return err
}

func createViewForCurrentValues(dataset *domain.Dataset, context *req.RequestContext) *errors.Error {
	viewname := "pr_" + dataset.ProjectId + "." + flattenNamespace(dataset.NamespaceName) + "_" + dataset.Name + "_current"
	columnsList := dataset.ColumnsList()
	primaryKey := dataset.PrimaryKey
	underlying := "pr_" + dataset.ProjectId + "." + flattenNamespace(dataset.NamespaceName) + "_" + dataset.Name
	sqlstr := "create view %s as select %s from %s all inner join (select max(__created) as __created, %s from %s group by %s) using __created, %s"
	sqlstr = fmt.Sprintf(sqlstr, viewname, strings.Join(columnsList, ","), underlying, primaryKey, underlying, primaryKey, primaryKey)

	err := context.ClickHouseTransaction.Execute("createCurrentView", sqlstr)
	log.Tracef("createViewForCurrentValues: sql=%s, err=%s", sqlstr, err)
	return err
}

func touchDictionaryConfig(dataset *domain.Dataset, context *req.RequestContext) {
	//go func() {
	//	time.Sleep(10 * time.Second)
	filename := "/opt/clickhouse/data/clickhouse/dictionaries/pr_" + dataset.ProjectId + "/" + dataset.Name + "_current.xml"
	currentTime := time.Now().Local()
	goerr := context.FileSystem.Chtimes("touchDictionaryConfig", filename, currentTime, currentTime)
	log.Tracef("touchDictionaryConfig: %s, err=%s", filename, goerr)
	//}()
}

func insertRowsIntoClickHouse(dataset *domain.Dataset, rows clickhouse.Rows, columns []string, context *req.RequestContext) *errors.Error {
	if len(rows) == 0 {
		return nil
	}
	log.Tracef("Columns: %s %d, %v", columns, len(columns), rows[0])
	for i, c := range rows[0] {
		log.Tracef("Row 0: colName: %s value=(%T:%v)", columns[i], c, c)
	}
	log.Tracef("Dataset: %s", common.ToJson(dataset))
	table := "pr_" + dataset.ProjectId + "." + flattenNamespace(dataset.NamespaceName) + "_" + dataset.Name
	transaction := context.ClickHouseTransaction.(*tx.ClickHouseTransaction)
	err := transaction.InsertMulti("insertRowsClickHouse", table, columns, rows)
	executed := transaction.Executor().GetExecutedSql()
	log.Tracef("Inserted %d rows into ClickHouse table %s in %6.3f milliseconds. (err=%s)", len(rows), table, float64(executed[0].Elapsed)/1000000., err)
	if err != nil {
		log.Errorf("Insert Error from sql: %s", table)
		if len(rows) >= 10 {
			log.Errorf("Values: %v", rows[0:10])
		} else {
			log.Errorf("Values: %v", rows)
		}
		log.Errorf("SQL: %v", executed)
		return err
	}
	return nil
}

func insertRowsIntoPipelinedb(dataset *domain.Dataset, rows clickhouse.Rows, columns []string, context *req.RequestContext) *errors.Error {
	if len(rows) == 0 {
		return nil
	}
	start := time.Now()
	table := "pr_" + dataset.ProjectId + "." + flattenNamespace(dataset.Namespace.Name) + "_" + dataset.Name
	//transaction2 := &tx.PostgresTransaction{tx.Transaction{Engine: sql.NewPostgresSqlEngine(common.Configuration.PipelineDB.URL)}}
	transaction2 := context.PostgresTransaction.(*tx.PostgresTransaction)
	err := transaction2.InsertMulti("insertRowsPipeline", table, columns, rows)
	//executed := transaction2.Executor().GetExecutedSql()
	elapsed := time.Since(start)
	log.Tracef("Inserted %d rows into PipelineDb in %6.3f milliseconds. (err=%s)", len(rows), float64(elapsed)/1000000., err)
	if err != nil {
		log.Errorf("Insert Error from sql: %s", table)
		return err

	}
	return nil
}

func updateDatasetColumns(dataset *domain.Dataset, context *req.RequestContext) *errors.Error {
	if err := storage.UpdateDatasetColumns(dataset, context); err != nil {
		log.Errorf("updateupdateDatasetColumns: %s", err)

		return err
	}

	return nil
}

func isTypeCompatible(left, right string) bool {
	if left == right {
		return true
	}
	if (left == "number" && right == "integer") || (right == "number" && left == "integer") {
		return true
	}

	if (left == "date" && right == "datetime") || (right == "date" && left == "datetime") {
		return true
	}
	return false
}

func guessType(value interface{}) string {

	switch value := value.(type) {
	case string:
		_, err := time.Parse("2006-01-02", value)
		if err == nil {
			return "date"
		}
		_, err = time.Parse("2006-01-02 15:04:05", value)
		if err == nil {
			return "datetime"
		}

		return "string"
	case []byte:
		return "bytes"
	case float64:
		a := value
		if a == float64(int64(a)) {
			return "integer"
		}
		return "number"
	case int16, int32, int64:
		return "integer"
	case bool:
		return "bool"
	case time.Time:
		return "datetime"
	case *[]string:
		cntDate := 0
		cntDatetime := 0
		for _, r := range *value {
			a := guessType(r)
			switch a {
			case "date":
				cntDate++
			case "datetime":
				cntDatetime++
			}
		}
		if cntDate > 0 {
			if cntDatetime > 0 {
				return "datetimeArray"
			}
			return "dateArray"
		}
		return "stringArray"
	case *[]int64:
		return "integerArray"
		/*for _, r := range *value {
			a := r
			if a != float64(int64(a)) {
				return "numberArray"
			}

		}
		return "integerArray"*/
	case *[]float64:
		for _, r := range *value {
			a := r
			if a != float64(int64(a)) {
				return "numberArray"
			}

		}
		return "integerArray"
	case []interface{}:
		switch value[0].(type) {
		case string:
			cntDate := 0
			cntDatetime := 0
			for _, r := range value {
				a := guessType(r)
				switch a {
				case "date":
					cntDate++
				case "datetime":
					cntDatetime++
				}
			}
			if cntDate > 0 {
				if cntDatetime > 0 {
					return "datetimeArray"
				}
				return "dateArray"
			}
			return "stringArray"
		case int64, float64:
			for _, r := range value {
				a := r.(float64)
				if a != float64(int64(a)) {
					return "numberArray"
				}

			}
			return "integerArray"
		default:
			return "unknown"
		}
	default:
		return "unknown"
	}

}

func defaultValue(column *domain.Column) interface{} {
	switch column.DataType {
	case "date":
		return time.Time{}.Format("2006-01-02")
	case "datetime":
		return time.Time{}
	case "string":
		return ""
	case "number":
		return 0.0
	case "integer":
		return 0
	case "bool":
		return 0
	case "stringArray":
		return make([]string, 0)
	case "integerArray":
		return make([]int64, 0)
	case "numberArray":
		return make([]float64, 0)
	case "boolArray":
		return make([]bool, 0)
	default:
		panic("unknown DataType " + column.DataType + " for column " + column.Name)
	}
}

func columnsList(dataset *domain.Dataset, includeCreated bool) []string {
	res := make([]string, 0)
	for _, column := range dataset.Columns {
		if column.Name == dataset.Name+"_pk" {
			continue
		}
		if !includeCreated && column.Name == "__created" {
			continue
		}
		res = append(res, column.Name)
	}
	return res
}

func dereference(val interface{}) interface{} {
	switch value := val.(type) {
	case *string:
		return *value
	case *float64:
		return *value
	case *int64:
		return *value
	case *int16:
		return *value
	case *int:
		return *value
	case *time.Time:
		return *value
	case *bool:
		return *value
	case *[]string, *[]int64, *[]float64, *[]bool:
		return val
	default:
		panic(fmt.Sprintf("unknwn type: %T, %s", val, val))
	}
}

func columnTypeMoveMe(col string) interface{} {
	var number int64
	var float float64
	var str string
	var b bool
	var t time.Time
	switch col {
	case "bool":
		return &b
	case "number":
		return &float
	case "integer":
		return &number
	case "string":
		return &str
	case "date":
		return &str
	case "datetime":
		return &t
	case "stringArray":
		a := make([]string, 0)
		return &a
	case "integerArray":
		a := make([]int64, 0)
		return &a
	case "numberArray":
		a := make([]float64, 0)
		return &a
	case "boolArray":
		a := make([]bool, 0)
		return &a
	default:
		panic(fmt.Sprintf("columnTypeMoveMe: unknown type %s", col))
	}
	return nil
}

func toString(value interface{}) string {
	switch value := value.(type) {
	case *string:
		return *value
	case *int64:
		//(*(value.(*int64))))
		return strconv.FormatInt(*(value), 10)
	case *int16:
		//(*(value.(*int64))))
		return strconv.FormatInt(int64(*(value)), 10)
	case *int:
		//(*(value.(*int64))))
		return strconv.FormatInt(int64(*(value)), 10)
	case *float64:
		return strconv.Itoa(int(*value))
	default:
		return fmt.Sprintf("%v", value)
	}
}

func flattenNamespace(path string) string {
	return strings.Replace(path, "/", "_", -1)
}


text:
package org.happysoft.zxsprite.export;

import java.util.List;
import org.happysoft.zxsprite.SpriteModel;

/**
 *
 * @author Chris Francis (c_francis1@yahoo.com)
 */
public interface ExportFormat {

  public String export(List<SpriteModel> model);

}


text:
'use strict';

var Colors           = require ('./colors.js');
var Spacing          = require ('./spacing.js');
var ColorManipulator = require ('./color-manipulator.js');
var Transitions      = require ('./transitions.js');

var Theme = {
  spacing: Spacing,
  contentFontFamily: 'Roboto, sans-serif',
  shapes: {
    defaultBorderRadius: '2px'
  },
  palette: {
      primary1Color: Colors.lightBlue500,
      primary2Color: Colors.lightBlue700,
      primary3Color: Colors.lightBlue100,
      accent1Color:  Colors.pinkA200,
      accent2Color:  Colors.pinkA400,
      accent3Color:  Colors.pinkA100,
      textColor:     Colors.darkBlack,
      subTextColor:  ColorManipulator.fade(Colors.darkBlack, 0.54),
      canvasColor:   Colors.white,
      paperColor:    Colors.white,
      borderColor:   Colors.grey300,
      disabledColor: ColorManipulator.fade(Colors.darkBlack, 0.3)
  },
  colors: Colors,
  transitions: Transitions
};

module.exports = Theme;


text:
# FileSystems.HFSPlus.BTree.DataRecord.RECORD_FLAGS

## Fields

### kHFSFileLockedBit

### kHFSFileLockedMask

### kHFSThreadExistsBit

### kHFSThreadExistsMask


text:
Music Achievement Council Resources

Resource Title Here

The brief description of what this resource is and who it is intended for should go right here.

Download the PDF

A Practical Guide for Recruitment and Retention

The brief description of what this resource is and who it is intended for should go right here.

Download the PDF

Educator Tips for Success

Tips for Success will help answer a range of questions, from how to prepare an instrument replacement plan to how to expand the learning power of music. These tips are complemented by short videos and will enhance the user's experience.


text:
#pragma once

#include <D3D11.h>
#include "com_ptr.h"

class RasterizerStateManager
{
private:
	RasterizerStateManager(com_ptr<ID3D11Device>& dev);

	static RasterizerStateManager* inst;

	com_ptr<ID3D11Device> mDev;

	com_ptr<ID3D11RasterizerState> mDefaultSolid;
	com_ptr<ID3D11RasterizerState> mDefaultWireframe;

public:

	enum DefaultStates { SOLID, WIREFRAME };

	static RasterizerStateManager* getInstance() { return inst; }

	static void init(com_ptr<ID3D11Device>& dev)
	{
		if(inst == nullptr)
		{
			inst = new RasterizerStateManager(dev);
		}
	}

	static void release()
	{
		if(inst != nullptr)
			delete inst;
	}

	/**
	Set one of the default rasterizer states.
	**/
	void setDefault(com_ptr<ID3D11DeviceContext>& devcon, DefaultStates state);

};