text:
<?php

namespace Application\Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20150116042216 extends AbstractMigration
{
    public function up(Schema $schema)
    {
        // this up() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE connecteduser ADD user_id INT DEFAULT NULL');
        $this->addSql('ALTER TABLE connecteduser ADD CONSTRAINT FK_F0A0BFE7A76ED395 FOREIGN KEY (user_id) REFERENCES User (id)');
        $this->addSql('CREATE INDEX IDX_F0A0BFE7A76ED395 ON connecteduser (user_id)');
    }

    public function down(Schema $schema)
    {
        // this down() migration is auto-generated, please modify it to your needs
        $this->abortIf($this->connection->getDatabasePlatform()->getName() != 'mysql', 'Migration can only be executed safely on \'mysql\'.');

        $this->addSql('ALTER TABLE ConnectedUser DROP FOREIGN KEY FK_F0A0BFE7A76ED395');
        $this->addSql('DROP INDEX IDX_F0A0BFE7A76ED395 ON ConnectedUser');
        $this->addSql('ALTER TABLE ConnectedUser DROP user_id');
    }
}


text:
title: Entwicklung der Gesamteinnahmen
weight: 1
data: path/to/data.csv
---

redpajama_set_name: RedPajamaGithub


text:
import React, { Component } from 'react';

import {
	AtomicBlockUtils,
	Editor,
	EditorState,
	RichUtils,
	Entity
} from 'draft-js';

import { stateToHTML } from 'draft-js-export-html';

import EditorSceneMediaInput from './EditorSceneMediaInput';
import EditorSceneButtons from './EditorSceneButtons';

/* ----- DRAFT.JS EDITOR UTILS ----- */

const style = {
	blackText: {
		color: 'black',
	}
};

const Image = (props) => {
	return ;
};

const Media = (props) => {
	const entity = props.contentState.getEntity(
		props.block.getEntityAt(0)
	);
	const { src } = entity.getData()
		, type = entity.getType();
	return type === 'img' ? <Image src={src} /> : null;
};

const mediaBlockRenderer = (block) => {
	return block.getType() === 'atomic' ?
		{ component: Media, editable: false }
		: null;
};

let stateToHTMLOptions = {
	blockRenderers: {
		atomic: (block) => {
			const mediaKey = block.getEntityAt(0)
				, mediaEntityInstance = Entity.get(mediaKey)
				, mediaEntityInstanceData = mediaEntityInstance.getData()
				, mediaEntityInstanceType = mediaEntityInstance.getType();
			return `<div><${mediaEntityInstanceType} src="${mediaEntityInstanceData.src}" /></div>`;
		},
	},
};

/* ----- COMPONENT ----- */

class EditorScene extends Component {
	constructor(props) {
		super(props);
		this.state = {
			showURLInput: false,
			urlValue: '',
			urlType: '',
			displayModule: false
		};
		this.onChange = this.onChange.bind(this);
		this.focus = () => this.refs.editor.focus();

		this.handleKeyCommand = this._handleKeyCommand.bind(this);
		this.onBold = this._onBold.bind(this);
		this.onItalic = this._onItalic.bind(this);
		this.onBlockQuote = this._onBlockQuote.bind(this);
		this.onUnorderedList = this._onUnorderedList.bind(this);
		this.onOrderedList = this._onOrderedList.bind(this);

		this.onAddImage = this._onAddImage.bind(this);
		this.onURLChange = this._onURLChange.bind(this);
		this.onURLInputKeyDown = this._onURLInputKeyDown.bind(this);
		this.confirmMedia = this._confirmMedia.bind(this);

		this.recommendationString = this.recommendationString.bind(this);
	}

	onChange(editorState) {
		// converts text to plaintext to allow actors / wiki module to parse correctly
		let content = editorState.getCurrentContent()
			, contentPlainText = content.getPlainText()
			, contentHTML = stateToHTML(content, stateToHTMLOptions);
		this.props.onSceneTextChange(contentPlainText);
		this.props.onSceneHTMLChange(contentHTML);
		this.props.onEditorStateChange(editorState);
	}

	_handleKeyCommand(command) {
		const newState = RichUtils.handleKeyCommand(this.props.editorState, command);
		if (newState) {
			this.onChange(newState);
			return 'handled';
		}
		return 'not-handled';
	}

	_onBold() {
		this.onChange(RichUtils.toggleInlineStyle(this.props.editorState, 'BOLD'));
	}

	_onItalic() {
		this.onChange(RichUtils.toggleInlineStyle(this.props.editorState, 'ITALIC'));
	}

	_onBlockQuote() {
		this.onChange(RichUtils.toggleBlockType(this.props.editorState, 'blockquote'));
	}

	_onUnorderedList() {
		this.onChange(RichUtils.toggleBlockType(this.props.editorState, 'unordered-list-item'));
	}

	_onOrderedList() {
		this.onChange(RichUtils.toggleBlockType(this.props.editorState, 'ordered-list-item'));
	}

	_onAddImage() {
		this._promptForMedia('img');
	}

	_promptForMedia(type) {
		this.setState({
			showURLInput: true,
			urlValue: '',
			urlType: type,
		}, () => {
			setTimeout(() => this.refs.url.focus(), 0);
		});
	}

	_onURLChange(event) {
		this.setState({
			urlValue: event.target.value
		});
	}

	_onURLInputKeyDown(event) {
		if (event.which === 13) {
			this._confirmMedia(event);
		}
	}

	_confirmMedia(event) {
		event.preventDefault();
		const { urlValue, urlType } = this.state
			, editorState = this.props.editorState
			, contentState = editorState.getCurrentContent()
			, contentStateWithEntity = contentState.createEntity(
				urlType,
				'IMMUTABLE',
				{ src: urlValue }
			)
			, entityKey = contentStateWithEntity.getLastCreatedEntityKey()
			, newEditorState = EditorState.set(
				editorState,
				{ currentContent: contentStateWithEntity }
			);
		this.onChange(AtomicBlockUtils.insertAtomicBlock(
			newEditorState,
			entityKey,
			' '
		));
		this.setState({
			showURLInput: false,
			urlValue: '',
		}, () => {
			setTimeout(() => this.focus(), 0);
		});
	}

	recommendationString(recArr) {
		let string = 'We noticed you have ';
		let secondHalf = ' We recommend using the ';

		recArr.forEach((rec, i) => {
			let detected = '';
			if (rec === 'actors') detected = 'characters';
			if (rec === 'maps') detected = 'locations';

			if (i === recArr.length - 1 && recArr.length > 1) {
				string += ' and ' + detected;
			} else if (i === 0) {
				string += detected;
			} else {
				string += ', ' + detected;
			}

			if (i === recArr.length - 1 && recArr.length > 1) {
				secondHalf += ' and ' + rec;
			} else if (i === 0) {
				secondHalf += rec;
			} else {
				secondHalf += ', ' + rec;
			}

		return string;
	});

	string += '!' + secondHalf;
	if (recArr.length > 1) {
		string += '  modules!';
	} else {
		string += ' module!';
	}

	return (

{string}

	);
}

componentWillReceiveProps(nextProps) {
		$(`.module-btn`).removeClass('highlighted-rec');

    if (nextProps.recommendations.length > 0) {
      nextProps.recommendations.forEach(rec => {
        $(`#${rec}.module-btn`).addClass('highlighted-rec');
      });
    }
  }

	render() {
		return (

					<input
						style={style.blackText}
						id="editor-scene-title"
						className="title-font"
						placeholder={`Title Scene ${this.props.whichScene + 1}`}
						name={this.props.whichScene}
						onChange={this.props.onSceneTitleChange}
						value={this.props.title}
					/>

					<button
						className="btn btn-default editorscene-delete-btn"
						onClick={this.props.onDeleteScene}
					>

					</button>

				<EditorSceneButtons
					onBold={this.onBold}
					onItalic={this.onItalic}
					onBlockQuote={this.onBlockQuote}
					onUnorderedList={this.onUnorderedList}
					onOrderedList={this.onOrderedList}
					onAddImage={this.onAddImage}
					whichScene={this.props.whichScene}
					whichModule={this.props.whichModule}
					recommendations={this.props.recommendations}
				/>

				{this.state.showURLInput ?
					<EditorSceneMediaInput
						onURLChange={this.onURLChange}
						onURLInputKeyDown={this.onURLInputKeyDown}
						confirmMedia={this.confirmMedia}
						urlValue={this.state.urlValue}
					/> :
					null}

				{this.props.recommendations.length > 0 ?
					this.recommendationString(this.props.recommendations)
				: null}

				{this.props.editorState ?

						<Editor
							blockRendererFn={mediaBlockRenderer}
							editorState={this.props.editorState}
							handleKeyCommand={this.handleKeyCommand}
							onChange={this.onChange}
							ref="editor"
							position={this.props.position}
						/>

 :
					null}

		);
	}
}

/* ----- CONTAINER ----- */

import { connect } from 'react-redux';
import { deleteScene, setSceneText, setSceneHTML, setSceneTitle, setEditorState, generateRecommendations } from '../../reducers/editor';

const mapStateToProps = (state) => ({
	editorState: state.editor.scenes[state.editor.whichScene].editorState,
	whichScene: state.editor.whichScene,
	title: state.editor.scenes[state.editor.whichScene].title,
	text: state.editor.scenes[state.editor.whichScene].paragraphs[0],
	whichModule: state.editor.scenes[state.editor.whichScene].whichModule,
	recommendations: state.editor.scenes[state.editor.whichScene].recommendations
});

const mapDispatchToProps = (dispatch, ownProps) => ({
	onDeleteScene(event) {
		event.preventDefault();
		let allowDelete = confirm(`Are you sure you want to delete scene ${+ownProps.whichScene + 1}?`);
		if (allowDelete) {
			dispatch(deleteScene(+ownProps.whichScene));
		}
	},
	onSceneTitleChange(event) {
		event.preventDefault();
		dispatch(setSceneTitle(event.target.value));
	},
	onSceneTextChange(content) {
		dispatch(setSceneText(content));
	},
	onSceneHTMLChange(content) {
		dispatch(setSceneHTML(content));
	},
	onEditorStateChange(editorState) {
		dispatch(setEditorState(editorState));
	},
	onRecommendation(position, event) {
		event.preventDefault();
		dispatch(generateRecommendations(position));
	}

});

export default connect(mapStateToProps, mapDispatchToProps)(EditorScene);


text:
const data = d3.range(50).map(d => ({
    x: d / 4,
    y: Math.sin(d / 4),
    z: Math.cos(d / 4) * 0.7
}));

const xExtent = fc.extentLinear().accessors([d => d.x]);
const yExtent = fc
    .extentLinear()
    .accessors([d => d.y, d => d.z])
    .pad([0.1, 0.1]);

const gridlines = fc.annotationSvgGridline();
const line = fc.seriesCanvasLine();
const area = fc.seriesCanvasArea().mainValue(d => d.z);

const multi = fc.seriesCanvasMulti().series([area, line]);

const chart = fc
    .chartCartesian(d3.scaleLinear(), d3.scaleLinear())
    .xLabel('Value')
    .yLabel('Sine / Cosine')
    .yOrient('left')
    .yDomain(yExtent(data))
    .xDomain(xExtent(data))
    .svgPlotArea(gridlines)
    .canvasPlotArea(multi);

// create a scale for the second axis
const zScale = d3.scaleLinear().domain([-1000, 1000]);
// create an axis for the scale
const zAxis = d3.axisRight(zScale);

chart.decorate(selection => {
    // when the chart is added to the DOM
    selection
        .enter()
        // additionally add a d3fc-svg element for the axis
        .append('d3fc-svg')
        // move the element into the right-axis cell
        .style('grid-column', 4)
        .style('grid-row', 3)
        // and give the axis a width
        .style('width', '3em')
        // when there's a measure event (namespaced to avoid removing existing handlers)
        .on('measure.z-axis', event => {
            // set the range on the scale to the elements height
            zScale.range([event.detail.height, 0]);
        })
        .on('draw.z-axis', (event, d) => {
            // draw the axis into the svg within the d3fc-svg element
            d3.select(event.currentTarget)
                .select('svg')
                .call(zAxis);
        });
});

d3.select('#chart')
    .datum(data)
    .call(chart);


text:
using ::base::SharedMemory;

namespace gpu {

namespace {

class MemoryBufferBacking : public BufferBacking {
 public:
  explicit MemoryBufferBacking(size_t size)
      : memory_(new char[size]), size_(size) {}
  ~MemoryBufferBacking() override {}
  void* GetMemory() const override { return memory_.get(); }
  size_t GetSize() const override { return size_; }

 private:
  std::unique_ptr<char[]> memory_;
  size_t size_;
  DISALLOW_COPY_AND_ASSIGN(MemoryBufferBacking);
};

}  // anonymous namespace

CommandBufferService::CommandBufferService(
    TransferBufferManagerInterface* transfer_buffer_manager)
    : ring_buffer_id_(-1),
      shared_state_(NULL),
      num_entries_(0),
      get_offset_(0),
      put_offset_(0),
      transfer_buffer_manager_(transfer_buffer_manager),
      token_(0),
      generation_(0),
      error_(error::kNoError),
      context_lost_reason_(error::kUnknown) {
}

CommandBufferService::~CommandBufferService() {
}

CommandBufferService::State CommandBufferService::GetLastState() {
  State state;
  state.get_offset = get_offset_;
  state.token = token_;
  state.error = error_;
  state.context_lost_reason = context_lost_reason_;
  state.generation = ++generation_;

  return state;
}

int32_t CommandBufferService::GetLastToken() {
  return GetLastState().token;
}

void CommandBufferService::UpdateState() {
  if (shared_state_) {
    CommandBufferService::State state = GetLastState();
    shared_state_->Write(state);
  }
}

void CommandBufferService::WaitForTokenInRange(int32_t start, int32_t end) {
  DCHECK(error_ != error::kNoError || InRange(start, end, token_));
}

void CommandBufferService::WaitForGetOffsetInRange(int32_t start, int32_t end) {
  DCHECK(error_ != error::kNoError || InRange(start, end, get_offset_));
}

void CommandBufferService::Flush(int32_t put_offset) {
  if (put_offset < 0 || put_offset > num_entries_) {
    error_ = gpu::error::kOutOfBounds;
    return;
  }

  put_offset_ = put_offset;

  if (!put_offset_change_callback_.is_null())
    put_offset_change_callback_.Run();
}

void CommandBufferService::OrderingBarrier(int32_t put_offset) {
  Flush(put_offset);
}

void CommandBufferService::SetGetBuffer(int32_t transfer_buffer_id) {
  DCHECK_EQ(-1, ring_buffer_id_);
  DCHECK_EQ(put_offset_, get_offset_);  // Only if it's empty.
  // If the buffer is invalid we handle it gracefully.
  // This means ring_buffer_ can be NULL.
  ring_buffer_ = GetTransferBuffer(transfer_buffer_id);
  ring_buffer_id_ = transfer_buffer_id;
  int32_t size = ring_buffer_.get() ? ring_buffer_->size() : 0;
  num_entries_ = size / sizeof(CommandBufferEntry);
  put_offset_ = 0;
  SetGetOffset(0);
  if (!get_buffer_change_callback_.is_null()) {
    get_buffer_change_callback_.Run(ring_buffer_id_);
  }

  UpdateState();
}

void CommandBufferService::SetSharedStateBuffer(
    std::unique_ptr<BufferBacking> shared_state_buffer) {
  shared_state_buffer_ = std::move(shared_state_buffer);
  DCHECK(shared_state_buffer_->GetSize() >= sizeof(*shared_state_));

  shared_state_ =
      static_cast<CommandBufferSharedState*>(shared_state_buffer_->GetMemory());

  UpdateState();
}

void CommandBufferService::SetGetOffset(int32_t get_offset) {
  DCHECK(get_offset >= 0 && get_offset < num_entries_);
  get_offset_ = get_offset;
}

scoped_refptr<Buffer> CommandBufferService::CreateTransferBuffer(size_t size,
                                                                 int32_t* id) {
  static int32_t next_id = 1;
  *id = next_id++;
  auto result = CreateTransferBufferWithId(size, *id);
  if (!result)
    *id = -1;
  return result;
}

void CommandBufferService::DestroyTransferBuffer(int32_t id) {
  transfer_buffer_manager_->DestroyTransferBuffer(id);
  if (id == ring_buffer_id_) {
    ring_buffer_id_ = -1;
    ring_buffer_ = NULL;
    num_entries_ = 0;
    get_offset_ = 0;
    put_offset_ = 0;
  }
}

scoped_refptr<Buffer> CommandBufferService::GetTransferBuffer(int32_t id) {
  return transfer_buffer_manager_->GetTransferBuffer(id);
}

bool CommandBufferService::RegisterTransferBuffer(
    int32_t id,
    std::unique_ptr<BufferBacking> buffer) {
  return transfer_buffer_manager_->RegisterTransferBuffer(id,
                                                          std::move(buffer));
}

scoped_refptr<Buffer> CommandBufferService::CreateTransferBufferWithId(
    size_t size,
    int32_t id) {
  if (!RegisterTransferBuffer(id,
                              base::MakeUnique<MemoryBufferBacking>(size))) {
    if (error_ == error::kNoError)
      error_ = gpu::error::kOutOfBounds;
    return NULL;
  }

  return GetTransferBuffer(id);
}

void CommandBufferService::SetToken(int32_t token) {
  token_ = token;
  UpdateState();
}

void CommandBufferService::SetParseError(error::Error error) {
  if (error_ == error::kNoError) {
    error_ = error;
    if (!parse_error_callback_.is_null())
      parse_error_callback_.Run();
  }
}

void CommandBufferService::SetContextLostReason(
    error::ContextLostReason reason) {
  context_lost_reason_ = reason;
}

int32_t CommandBufferService::GetPutOffset() {
  return put_offset_;
}

void CommandBufferService::SetPutOffsetChangeCallback(
    const base::Closure& callback) {
  put_offset_change_callback_ = callback;
}

void CommandBufferService::SetGetBufferChangeCallback(
    const GetBufferChangedCallback& callback) {
  get_buffer_change_callback_ = callback;
}

void CommandBufferService::SetParseErrorCallback(
    const base::Closure& callback) {
  parse_error_callback_ = callback;
}

}  // namespace gpu


text:
package com.intellij.projectImport;

import com.intellij.ide.DataManager;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.util.projectWizard.ProjectBuilder;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.module.ModifiableModuleModel;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ui.configuration.ModulesProvider;
import com.intellij.packaging.artifacts.ModifiableArtifactModel;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.List;

/**
 * @author Vladislav.Kaznacheev
 */
public abstract class ProjectImportBuilder<T> extends ProjectBuilder {
  public static final ExtensionPointName<ProjectImportBuilder> EXTENSIONS_POINT_NAME = ExtensionPointName.create("com.intellij.projectImportBuilder");

  private boolean myUpdate;
  private String myFileToImport;

  @NotNull
  public abstract String getName();

  public abstract Icon getIcon();

  public abstract List<T> getList();

  public abstract boolean isMarked(final T element);

  public abstract void setList(List<T> list) throws ConfigurationException;

  public abstract void setOpenProjectSettingsAfter(boolean on);

  @Override
  public List<Module> commit(@NotNull Project project, ModifiableModuleModel model, ModulesProvider modulesProvider) {
    return commit(project, model, modulesProvider, null);
  }

  @Nullable
  public abstract List<Module> commit(Project project, ModifiableModuleModel model, ModulesProvider modulesProvider, ModifiableArtifactModel artifactModel);

  public void setFileToImport(String path) {
    myFileToImport = path;
  }

  public String getFileToImport() {
    return myFileToImport;
  }

  @Nullable
  public static Project getCurrentProject() {
    return CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext());
  }

  protected String getTitle() {
    return IdeBundle.message("project.import.wizard.title", getName());
  }

  @Override
  public boolean isUpdate() {
    return myUpdate;
  }

  public void setUpdate(final boolean update) {
    myUpdate = update;
  }
}


text:
using System;
using Syncfusion.SfChart.XForms;

namespace Sensus.Probes.Network
{
    /// <summary>
    /// Probes information about WLAN access points.
    /// </summary>
    public abstract class PollingWlanProbe : PollingProbe
    {
        public sealed override string DisplayName
        {
            get { return "Wireless LAN Binding"; }
        }

        public sealed override Type DatumType
        {
            get { return typeof(WlanDatum); }
        }

        public sealed override int DefaultPollingSleepDurationMS
        {
            get
            {
                return 60000 * 15; // every 15 minutes
            }
        }

        protected override ChartSeries GetChartSeries()
        {
            return null;
        }

        protected override ChartDataPoint GetChartDataPointFromDatum(Datum datum)
        {
            return null;
        }

        protected override ChartAxis GetChartPrimaryAxis()
        {
            throw new NotImplementedException();
        }

        protected override RangeAxisBase GetChartSecondaryAxis()
        {
            throw new NotImplementedException();
        }
    }
}


text:
package org.gridkit.jvmtool;

import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;

import org.junit.Test;

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

public class MBeanHelperTest {

    private ObjectName memoryMXBean() throws MalformedObjectNameException {
        return new ObjectName(ManagementFactory.MEMORY_MXBEAN_NAME);
    }

    private ObjectName osMXBean() throws MalformedObjectNameException {
        return new ObjectName(ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME);
    }

    private ObjectName threadMXBean() throws MalformedObjectNameException {
        return new ObjectName(ManagementFactory.THREAD_MXBEAN_NAME);
    }

    private ObjectName runtimeMXBean() throws MalformedObjectNameException {
        return new ObjectName(ManagementFactory.RUNTIME_MXBEAN_NAME);
    }

    private ObjectName managementMXBean() throws MalformedObjectNameException {
        return new ObjectName("com.sun.management:type=HotSpotDiagnostic");
    }

    @Test
    public void test_thread_bean_describer() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        System.out.println(helper.describe(threadMXBean()));
    }

    @Test
    public void test_os_bean_describer() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        System.out.println(helper.describe(osMXBean()));
    }

    @Test
    public void test_memory_bean_describer() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        System.out.println(helper.describe(memoryMXBean()));
    }

    @Test
    public void test_runtime_bean_describer() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        System.out.println(helper.describe(runtimeMXBean()));
    }

    @Test
    public void test_management_bean_describer() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        System.out.println(helper.describe(managementMXBean()));
    }

    @Test
    public void test_bean_get_set() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        helper.set(threadMXBean(), "ThreadCpuTimeEnabled", "true");
        String threadAllocatedMemoryEnabled = helper.get(threadMXBean(), Collections.singletonList("ThreadAllocatedMemoryEnabled")).get("ThreadAllocatedMemoryEnabled");
        System.out.println("ThreadCpuTimeEnabled: " + threadAllocatedMemoryEnabled);
        assertThat(threadAllocatedMemoryEnabled).isEqualTo("true");

        helper.set(threadMXBean(), "ThreadCpuTimeEnabled", "FALSE");
        threadAllocatedMemoryEnabled = helper.get(threadMXBean(), Collections.singletonList("ThreadAllocatedMemoryEnabled")).get("ThreadAllocatedMemoryEnabled");
        System.out.println("ThreadCpuTimeEnabled: " + threadAllocatedMemoryEnabled);
        assertThat(threadAllocatedMemoryEnabled).isEqualTo("true");
    }

    @Test(expected=IllegalArgumentException.class)
    public void test_bean_invalid_set() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        helper.set(managementMXBean(), "ThreadCpuTimeEnabled", "true");
    }

    @Test
    public void test_get_sys_props() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        System.out.println(helper.get(runtimeMXBean(), Collections.singletonList("SystemProperties")));
    }

    @Test
    public void test_get_sys_props_wide() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        helper.setFormatingOption(MBeanHelper.FORMAT_TABLE_COLUMN_WIDTH_THRESHOLD, 200);
        System.out.println(helper.get(runtimeMXBean(), Collections.singletonList("SystemProperties")));
    }

    @Test
    public void test_get_mem_heap() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        System.out.println(helper.get(memoryMXBean(), Collections.singletonList("HeapMemoryUsage")));
    }

    @Test
    public void test_get_thread_dump() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        System.out.println(helper.invoke(threadMXBean(), "dumpAllThreads", "true", "true"));
    }

    @Test
    public void test_find_deadlocked_threads() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        System.out.println(helper.invoke(threadMXBean(), "findMonitorDeadlockedThreads"));
    }

    @Test
    public void test_get_vm_spec_infos() throws Exception {
        MBeanHelper helper = new MBeanHelper(ManagementFactory.getPlatformMBeanServer());
        Map<String, String> attrs = helper.get(runtimeMXBean(), Arrays.asList("SpecName", "SpecVendor", "SpecVersion"));
        System.out.println(attrs);
        assertThat(attrs).containsKeys("SpecName", "SpecVendor", "SpecVersion");
    }
}


text:
//Write a program that reads from the console a sequence of n integer numbers and returns the minimal, the maximal number, the sum and the average of all numbers (displayed with 2 digits after the decimal point).
//The input starts by the number n (alone in a line) followed by n lines, each holding an integer number.
//The output is like in the examples below.
using System;
class MinMaxSumAvgOfNNums
{
    static void Main()
    {
        Console.WriteLine("Enter N (Number of integers to be calculated)");
        int n = int.Parse(Console.ReadLine());

        if (n <= 0)
        {
            Console.WriteLine("Enter integer value above 0:");
            n = int.Parse(Console.ReadLine());
        }

        int[] numbers = new int[n];
        Console.WriteLine("Enter {0} integers, each alone in a line:", n);
        for (int i = 0; i < numbers.Length; i++)
        {
            numbers[i] = int.Parse(Console.ReadLine());
        }

        int min = int.MaxValue;
        for (int i = 0; i < numbers.Length; i++)
        {
            min = Math.Min(numbers[i], min);
        }
        Console.WriteLine("min = {0}", min);

        int max = 0;
        for (int i = 0; i < numbers.Length; i++)
        {
            max = Math.Max(numbers[i], max);
        }
        Console.WriteLine("max = {0}", max);

        int sum = 0;
        for (int i = 0; i < numbers.Length; i++)
        {
            sum += numbers[i];
        }
        Console.WriteLine("sum = {0}", sum);

        double avg = 0;
        for (int i = 0; i < numbers.Length; i++)
        {
            avg += numbers[i];
        }
        avg /= n;
        Console.WriteLine("avg = {0:0.00}", avg);
        Console.ReadLine();
    }
}


text:
using J2N.Text;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;

namespace Lucene.Net.Codecs.SimpleText
{

    using BinaryDocValues = Index.BinaryDocValues;
    using BufferedChecksumIndexInput = Store.BufferedChecksumIndexInput;
    using BytesRef = Util.BytesRef;
    using ChecksumIndexInput = Store.ChecksumIndexInput;
    using CorruptIndexException = Index.CorruptIndexException;
    using DocValues = Index.DocValues;
    using DocValuesType = Index.DocValuesType;
    using FieldInfo = Index.FieldInfo;
    using IBits = Util.IBits;
    using IndexFileNames = Index.IndexFileNames;
    using IndexInput = Store.IndexInput;
    using NumericDocValues = Index.NumericDocValues;
    using SegmentReadState = Index.SegmentReadState;
    using SortedDocValues = Index.SortedDocValues;
    using SortedSetDocValues = Index.SortedSetDocValues;
    using StringHelper = Util.StringHelper;

    public class SimpleTextDocValuesReader : DocValuesProducer // LUCENENET NOTE: Changed from internal to public because it is subclassed by a public class
    {
        internal class OneField
        {
            public long DataStartFilePointer { get; set; }
            public string Pattern { get; set; }
            public string OrdPattern { get; set; }
            public int MaxLength { get; set; }
            public bool FixedLength { get; set; }
            public long MinValue { get; set; }
            public long NumValues { get; set; }
        }

        private readonly int maxDoc;
        private readonly IndexInput data;
        private readonly BytesRef scratch = new BytesRef();
        private readonly IDictionary<string, OneField> fields = new Dictionary<string, OneField>();

        // LUCENENET NOTE: Changed from public to internal because the class had to be made public, but is not for public use.
        internal SimpleTextDocValuesReader(SegmentReadState state, string ext)
        {
            data = state.Directory.OpenInput(
                    IndexFileNames.SegmentFileName(state.SegmentInfo.Name, state.SegmentSuffix, ext), state.Context);
            maxDoc = state.SegmentInfo.DocCount;

            while (true)
            {
                ReadLine();
                if (scratch.Equals(SimpleTextDocValuesWriter.END))
                {
                    break;
                }
                Debug.Assert(StartsWith(SimpleTextDocValuesWriter.FIELD), scratch.Utf8ToString());
                var fieldName = StripPrefix(SimpleTextDocValuesWriter.FIELD);
                var field = new OneField();

                fields[fieldName] = field;

                ReadLine();
                Debug.Assert(StartsWith(SimpleTextDocValuesWriter.TYPE), scratch.Utf8ToString());

                var dvType =
                    (DocValuesType)
                        Enum.Parse(typeof (DocValuesType), StripPrefix(SimpleTextDocValuesWriter.TYPE));

                if (dvType == DocValuesType.NUMERIC)
                {
                    ReadLine();
                    Debug.Assert(StartsWith(SimpleTextDocValuesWriter.MINVALUE),
                        "got " + scratch.Utf8ToString() + " field=" + fieldName + " ext=" + ext);
                    field.MinValue = Convert.ToInt64(StripPrefix(SimpleTextDocValuesWriter.MINVALUE), CultureInfo.InvariantCulture);
                    ReadLine();
                    Debug.Assert(StartsWith(SimpleTextDocValuesWriter.PATTERN));
                    field.Pattern = StripPrefix(SimpleTextDocValuesWriter.PATTERN);
                    field.DataStartFilePointer = data.GetFilePointer();
                    data.Seek(data.GetFilePointer() + (1 + field.Pattern.Length + 2)*maxDoc);
                }
                else if (dvType == DocValuesType.BINARY)
                {
                    ReadLine();
                    Debug.Assert(StartsWith(SimpleTextDocValuesWriter.MAXLENGTH));
                    field.MaxLength = Convert.ToInt32(StripPrefix(SimpleTextDocValuesWriter.MAXLENGTH), CultureInfo.InvariantCulture);
                    ReadLine();
                    Debug.Assert(StartsWith(SimpleTextDocValuesWriter.PATTERN));
                    field.Pattern = StripPrefix(SimpleTextDocValuesWriter.PATTERN);
                    field.DataStartFilePointer = data.GetFilePointer();
                    data.Seek(data.GetFilePointer() + (9 + field.Pattern.Length + field.MaxLength + 2)*maxDoc);
                }
                else if (dvType == DocValuesType.SORTED || dvType == DocValuesType.SORTED_SET)
                {
                    ReadLine();
                    Debug.Assert(StartsWith(SimpleTextDocValuesWriter.NUMVALUES));
                    field.NumValues = Convert.ToInt64(StripPrefix(SimpleTextDocValuesWriter.NUMVALUES), CultureInfo.InvariantCulture);
                    ReadLine();
                    Debug.Assert(StartsWith(SimpleTextDocValuesWriter.MAXLENGTH));
                    field.MaxLength = Convert.ToInt32(StripPrefix(SimpleTextDocValuesWriter.MAXLENGTH), CultureInfo.InvariantCulture);
                    ReadLine();
                    Debug.Assert(StartsWith(SimpleTextDocValuesWriter.PATTERN));
                    field.Pattern = StripPrefix(SimpleTextDocValuesWriter.PATTERN);
                    ReadLine();
                    Debug.Assert(StartsWith(SimpleTextDocValuesWriter.ORDPATTERN));
                    field.OrdPattern = StripPrefix(SimpleTextDocValuesWriter.ORDPATTERN);
                    field.DataStartFilePointer = data.GetFilePointer();
                    data.Seek(data.GetFilePointer() + (9 + field.Pattern.Length + field.MaxLength)*field.NumValues +
                              (1 + field.OrdPattern.Length)*maxDoc);
                }
                else
                {
                    throw new ArgumentOutOfRangeException();
                }
            }

            // We should only be called from above if at least one
            // field has DVs:
            Debug.Assert(fields.Count > 0);
        }

        public override NumericDocValues GetNumeric(FieldInfo fieldInfo)
        {
            var field = fields[fieldInfo.Name];
            Debug.Assert(field != null);

            // SegmentCoreReaders already verifies this field is valid:
            Debug.Assert(field != null, "field=" + fieldInfo.Name + " fields=" + fields);

            var @in = (IndexInput)data.Clone();
            var scratch = new BytesRef();

            return new NumericDocValuesAnonymousInnerClassHelper(this, field, @in, scratch);
        }

        private class NumericDocValuesAnonymousInnerClassHelper : NumericDocValues
        {
            private readonly SimpleTextDocValuesReader _outerInstance;

            private readonly OneField _field;
            private readonly IndexInput _input;
            private readonly BytesRef _scratch;

            public NumericDocValuesAnonymousInnerClassHelper(SimpleTextDocValuesReader outerInstance,
                OneField field, IndexInput input, BytesRef scratch)
            {
                _outerInstance = outerInstance;
                _field = field;
                _input = input;
                _scratch = scratch;
            }

            public override long Get(int docId)
            {
                try
                {
                    if (docId < 0 || docId >= _outerInstance.maxDoc)
                        throw new IndexOutOfRangeException("docID must be 0 .. " + (_outerInstance.maxDoc - 1) +
                                                           "; got " + docId);

                    _input.Seek(_field.DataStartFilePointer + (1 + _field.Pattern.Length + 2) * docId);
                    SimpleTextUtil.ReadLine(_input, _scratch);

                    // LUCNENENET: .NET doesn't have a way to specify a pattern with decimal, but all of the standard ones are built in.
                    if (!decimal.TryParse(_scratch.Utf8ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out decimal bd))
                        throw new CorruptIndexException("failed to parse long value (resource=" + _input + ")");

                    SimpleTextUtil.ReadLine(_input, _scratch); // read the line telling us if its real or not
                    return (long)((decimal)_field.MinValue + bd); // LUCENENET specific - use decimal rather than BigInteger
                }
                catch (IOException ioe)
                {
                    throw new Exception(ioe.ToString(), ioe);
                }
            }
        }

        private IBits GetNumericDocsWithField(FieldInfo fieldInfo)
        {
            var field = fields[fieldInfo.Name];
            var input = (IndexInput)data.Clone();
            var scratch = new BytesRef();
            return new BitsAnonymousInnerClassHelper(this, field, input, scratch);
        }

        private class BitsAnonymousInnerClassHelper : IBits
        {
            private readonly SimpleTextDocValuesReader _outerInstance;

            private readonly OneField _field;
            private readonly IndexInput _input;
            private readonly BytesRef _scratch;

            public BitsAnonymousInnerClassHelper(SimpleTextDocValuesReader outerInstance,
                OneField field, IndexInput @in, BytesRef scratch)
            {
                _outerInstance = outerInstance;
                _field = field;
                _input = @in;
                _scratch = scratch;
            }

            public bool Get(int index)
            {
                try
                {
                    _input.Seek(_field.DataStartFilePointer + (1 + _field.Pattern.Length + 2) * index);
                    SimpleTextUtil.ReadLine(_input, _scratch); // data
                    SimpleTextUtil.ReadLine(_input, _scratch); // 'T' or 'F'
                    return _scratch.Bytes[_scratch.Offset] == (byte)'T';
                }
                catch (IOException e)
                {
                    throw new Exception(e.ToString(), e);
                }
            }

            public int Length => _outerInstance.maxDoc;
        }

        public override BinaryDocValues GetBinary(FieldInfo fieldInfo)
        {
            var field = fields[fieldInfo.Name];
            Debug.Assert(field != null);
            var input = (IndexInput)data.Clone();
            var scratch = new BytesRef();

            return new BinaryDocValuesAnonymousInnerClassHelper(this, field, input, scratch);
        }

        private class BinaryDocValuesAnonymousInnerClassHelper : BinaryDocValues
        {
            private readonly SimpleTextDocValuesReader _outerInstance;

            private readonly OneField _field;
            private readonly IndexInput _input;
            private readonly BytesRef _scratch;

            public BinaryDocValuesAnonymousInnerClassHelper(SimpleTextDocValuesReader outerInstance, OneField field,
                IndexInput input, BytesRef scratch)
            {
                _outerInstance = outerInstance;
                _field = field;
                _input = input;
                _scratch = scratch;
            }

            public override void Get(int docId, BytesRef result)
            {
                try
                {
                    if (docId < 0 || docId >= _outerInstance.maxDoc)
                        throw new IndexOutOfRangeException("docID must be 0 .. " + (_outerInstance.maxDoc - 1) +
                                                           "; got " + docId);

                    _input.Seek(_field.DataStartFilePointer + (9 + _field.Pattern.Length + _field.MaxLength + 2) * docId);
                    SimpleTextUtil.ReadLine(_input, _scratch);
                    Debug.Assert(StringHelper.StartsWith(_scratch, SimpleTextDocValuesWriter.LENGTH));
                    int len;
                    try
                    {
                        // LUCNENENET: .NET doesn't have a way to specify a pattern with integer, but all of the standard ones are built in.
                        len = int.Parse(Encoding.UTF8.GetString(_scratch.Bytes, _scratch.Offset + SimpleTextDocValuesWriter.LENGTH.Length,
                            _scratch.Length - SimpleTextDocValuesWriter.LENGTH.Length), NumberStyles.Integer, CultureInfo.InvariantCulture);
                    }
                    catch (FormatException ex)
                    {
                        throw new CorruptIndexException("failed to parse int value (resource=" + _input + ")", ex);
                    }

                    result.Bytes = new byte[len];
                    result.Offset = 0;
                    result.Length = len;
                    _input.ReadBytes(result.Bytes, 0, len);
                }
                catch (IOException ioe)
                {
                    throw new Exception(ioe.ToString(), ioe);
                }
            }
        }

        private IBits GetBinaryDocsWithField(FieldInfo fieldInfo)
        {
            var field = fields[fieldInfo.Name];
            var input = (IndexInput)data.Clone();
            var scratch = new BytesRef();

            return new BitsAnonymousInnerClassHelper2(this, field, input, scratch);
        }

        private class BitsAnonymousInnerClassHelper2 : IBits
        {
            private readonly SimpleTextDocValuesReader _outerInstance;

            private readonly OneField _field;
            private readonly IndexInput _input;
            private readonly BytesRef _scratch;

            public BitsAnonymousInnerClassHelper2(SimpleTextDocValuesReader outerInstance, OneField field,
                IndexInput input, BytesRef scratch)
            {
                _outerInstance = outerInstance;
                _field = field;
                _input = input;
                _scratch = scratch;
            }

            public bool Get(int index)
            {
                try
                {
                    _input.Seek(_field.DataStartFilePointer + (9 + _field.Pattern.Length + _field.MaxLength + 2) * index);
                    SimpleTextUtil.ReadLine(_input, _scratch);
                    Debug.Assert(StringHelper.StartsWith(_scratch, SimpleTextDocValuesWriter.LENGTH));
                    int len;
                    try
                    {
                        len = int.Parse(Encoding.UTF8.GetString(_scratch.Bytes, _scratch.Offset + SimpleTextDocValuesWriter.LENGTH.Length,
                            _scratch.Length - SimpleTextDocValuesWriter.LENGTH.Length), NumberStyles.Number, CultureInfo.InvariantCulture);
                    }
                    catch (FormatException ex)
                    {
                        throw new CorruptIndexException("failed to parse int value (resource=" + _input + ")", ex);
                    }

                    // skip past bytes
                    var bytes = new byte[len];
                    _input.ReadBytes(bytes, 0, len);
                    SimpleTextUtil.ReadLine(_input, _scratch); // newline
                    SimpleTextUtil.ReadLine(_input, _scratch); // 'T' or 'F'
                    return _scratch.Bytes[_scratch.Offset] == (byte)'T';
                }
                catch (IOException ioe)
                {
                    throw new Exception(ioe.ToString(), ioe);
                }
            }

            public int Length => _outerInstance.maxDoc;
        }

        public override SortedDocValues GetSorted(FieldInfo fieldInfo)
        {
            var field = fields[fieldInfo.Name];

            // SegmentCoreReaders already verifies this field is valid:
            Debug.Assert(field != null);
            var input = (IndexInput)data.Clone();
            var scratch = new BytesRef();

            return new SortedDocValuesAnonymousInnerClassHelper(this, field, input, scratch);
        }

        private class SortedDocValuesAnonymousInnerClassHelper : SortedDocValues
        {
            private readonly SimpleTextDocValuesReader _outerInstance;

            private readonly OneField _field;
            private readonly IndexInput _input;
            private readonly BytesRef _scratch;
            private readonly string _decoderFormat;
            private readonly string _ordDecoderFormat;

            public SortedDocValuesAnonymousInnerClassHelper(SimpleTextDocValuesReader outerInstance,
                OneField field, IndexInput input, BytesRef scratch)
            {
                _outerInstance = outerInstance;
                _field = field;
                _input = input;
                _scratch = scratch;
                _decoderFormat = field.Pattern;
                _ordDecoderFormat = field.OrdPattern;
            }

            public override int GetOrd(int docId)
            {
                if (docId < 0 || docId >= _outerInstance.maxDoc)
                {
                    throw new IndexOutOfRangeException("docID must be 0 .. " + (_outerInstance.maxDoc - 1) + "; got " +
                                                       docId);
                }

                try
                {
                    _input.Seek(_field.DataStartFilePointer + _field.NumValues * (9 + _field.Pattern.Length + _field.MaxLength) +
                             docId * (1 + _field.OrdPattern.Length));
                    SimpleTextUtil.ReadLine(_input, _scratch);
                    try
                    {
                        // LUCNENENET: .NET doesn't have a way to specify a pattern with integer, but all of the standard ones are built in.
                        return int.Parse(_scratch.Utf8ToString(), NumberStyles.Integer, CultureInfo.InvariantCulture) - 1;
                    }
                    catch (Exception pe)
                    {
                        var e = new CorruptIndexException("failed to parse ord (resource=" + _input + ")", pe);
                        throw e;
                    }
                }
                catch (IOException ioe)
                {
                    throw new Exception(ioe.ToString(), ioe);
                }
            }

            public override void LookupOrd(int ord, BytesRef result)
            {
                try
                {
                    if (ord < 0 || ord >= _field.NumValues)
                    {
                        throw new IndexOutOfRangeException("ord must be 0 .. " + (_field.NumValues - 1) + "; got " +
                                                                  ord);
                    }
                    _input.Seek(_field.DataStartFilePointer + ord * (9 + _field.Pattern.Length + _field.MaxLength));
                    SimpleTextUtil.ReadLine(_input, _scratch);
                    Debug.Assert(StringHelper.StartsWith(_scratch, SimpleTextDocValuesWriter.LENGTH),
                        "got " + _scratch.Utf8ToString() + " in=" + _input);
                    int len;
                    try
                    {
                        // LUCNENENET: .NET doesn't have a way to specify a pattern with integer, but all of the standard ones are built in.
                        len = int.Parse(Encoding.UTF8.GetString(_scratch.Bytes, _scratch.Offset + SimpleTextDocValuesWriter.LENGTH.Length,
                            _scratch.Length - SimpleTextDocValuesWriter.LENGTH.Length), NumberStyles.Integer, CultureInfo.InvariantCulture);

                    }
                    catch (Exception pe)
                    {
                        var e = new CorruptIndexException("failed to parse int length (resource=" + _input + ")", pe);
                        throw e;
                    }

                    result.Bytes = new byte[len];
                    result.Offset = 0;
                    result.Length = len;
                    _input.ReadBytes(result.Bytes, 0, len);
                }
                catch (IOException ioe)
                {
                    throw new Exception(ioe.ToString(), ioe);
                }
            }

            public override int ValueCount => (int)_field.NumValues;
        }

        public override SortedSetDocValues GetSortedSet(FieldInfo fieldInfo)
        {
            var field = fields[fieldInfo.Name];

            // SegmentCoreReaders already verifies this field is
            // valid:
            Debug.Assert(field != null);

            var input = (IndexInput) data.Clone();
            var scratch = new BytesRef();

            return new SortedSetDocValuesAnonymousInnerClassHelper(this, field, input, scratch);
        }

        private class SortedSetDocValuesAnonymousInnerClassHelper : SortedSetDocValues
        {
            private readonly SimpleTextDocValuesReader _outerInstance;

            private readonly OneField _field;
            private readonly IndexInput _input;
            private readonly BytesRef _scratch;
            private readonly string _decoderFormat;

            public SortedSetDocValuesAnonymousInnerClassHelper(SimpleTextDocValuesReader outerInstance,
                OneField field, IndexInput input, BytesRef scratch)
            {
                _outerInstance = outerInstance;
                _field = field;
                _input = input;
                _scratch = scratch;
                _decoderFormat = field.Pattern;
                _currentOrds = EMPTY_STRINGS;
                _currentIndex = 0;
            }

            // LUCENENET specific - optimized empty array creation
            private static readonly string[] EMPTY_STRINGS =
#if FEATURE_ARRAYEMPTY
                Array.Empty<string>();
#else
                new string[0];
#endif

            private string[] _currentOrds;
            private int _currentIndex;

            public override long NextOrd()
            {
                return _currentIndex == _currentOrds.Length ? NO_MORE_ORDS : Convert.ToInt64(_currentOrds[_currentIndex++], CultureInfo.InvariantCulture);
            }

            public override void SetDocument(int docID)
            {
                if (docID < 0 || docID >= _outerInstance.maxDoc)
                    throw new IndexOutOfRangeException("docID must be 0 .. " + (_outerInstance.maxDoc - 1) + "; got " +
                                                        docID);

                try
                {
                    _input.Seek(_field.DataStartFilePointer + _field.NumValues * (9 + _field.Pattern.Length + _field.MaxLength) +
                                docID * (1 + _field.OrdPattern.Length));
                    SimpleTextUtil.ReadLine(_input, _scratch);
                    var ordList = _scratch.Utf8ToString().Trim();
                    _currentOrds = ordList.Length == 0 ? EMPTY_STRINGS : ordList.Split(',').TrimEnd();
                    _currentIndex = 0;
                }
                catch (IOException ioe)
                {
                    throw new Exception(ioe.ToString(), ioe);
                }
            }

            public override void LookupOrd(long ord, BytesRef result)
            {
                try
                {
                    if (ord < 0 || ord >= _field.NumValues)
                    {
                        throw new IndexOutOfRangeException("ord must be 0 .. " + (_field.NumValues - 1) + "; got " + ord);
                    }

                    _input.Seek(_field.DataStartFilePointer + ord * (9 + _field.Pattern.Length + _field.MaxLength));
                    SimpleTextUtil.ReadLine(_input, _scratch);
                    Debug.Assert(StringHelper.StartsWith(_scratch, SimpleTextDocValuesWriter.LENGTH),
                        "got " + _scratch.Utf8ToString() + " in=" + _input);
                    int len;
                    try
                    {
                        // LUCNENENET: .NET doesn't have a way to specify a pattern with integer, but all of the standard ones are built in.
                        len = int.Parse(Encoding.UTF8.GetString(_scratch.Bytes, _scratch.Offset + SimpleTextDocValuesWriter.LENGTH.Length,
                            _scratch.Length - SimpleTextDocValuesWriter.LENGTH.Length), NumberStyles.Integer, CultureInfo.InvariantCulture);
                    }
                    catch (Exception pe)
                    {
                        var e = new CorruptIndexException("failed to parse int length (resource=" + _input + ")", pe);
                        throw e;
                    }

                    result.Bytes = new byte[len];
                    result.Offset = 0;
                    result.Length = len;
                    _input.ReadBytes(result.Bytes, 0, len);
                }
                catch (IOException ioe)
                {
                    throw new Exception(ioe.ToString(), ioe);
                }
            }

            public override long ValueCount => _field.NumValues;
        }

        public override IBits GetDocsWithField(FieldInfo field)
        {
            switch (field.DocValuesType)
            {
                case DocValuesType.SORTED_SET:
                    return DocValues.DocsWithValue(GetSortedSet(field), maxDoc);
                case DocValuesType.SORTED:
                    return DocValues.DocsWithValue(GetSorted(field), maxDoc);
                case DocValuesType.BINARY:
                    return GetBinaryDocsWithField(field);
                case DocValuesType.NUMERIC:
                    return GetNumericDocsWithField(field);
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (!disposing) return;

            data.Dispose();
        }

        /// <summary> Used only in ctor: </summary>
        private void ReadLine()
        {
            SimpleTextUtil.ReadLine(data, scratch);
        }

        /// <summary> Used only in ctor: </summary>
        private bool StartsWith(BytesRef prefix)
        {
            return StringHelper.StartsWith(scratch, prefix);
        }

        /// <summary> Used only in ctor: </summary>
        private string StripPrefix(BytesRef prefix)
        {
            return Encoding.UTF8.GetString(scratch.Bytes, scratch.Offset + prefix.Length, scratch.Length - prefix.Length);
        }

        public override long RamBytesUsed()
        {
            return 0;
        }

        public override void CheckIntegrity()
        {
            var iScratch = new BytesRef();
            var clone = (IndexInput) data.Clone();
            clone.Seek(0);
            ChecksumIndexInput input = new BufferedChecksumIndexInput(clone);
            while (true)
            {
                SimpleTextUtil.ReadLine(input, iScratch);
                if (!iScratch.Equals(SimpleTextDocValuesWriter.END)) continue;

                SimpleTextUtil.CheckFooter(input);
                break;
            }
        }
    }
}


text:
package org.openqa.selenium.remote;

import java.util.Objects;
import java.util.UUID;

public class SessionId {

  private final String opaqueKey;

  public SessionId(UUID uuid) {
    this(Objects.requireNonNull(uuid, "Session ID key has not been set.").toString());
  }

  public SessionId(String opaqueKey) {
    this.opaqueKey = Objects.requireNonNull(opaqueKey, "Session ID key has not been set.");
  }

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

  @Override
  public int hashCode() {
    return opaqueKey.hashCode();
  }

  @Override
  public boolean equals(Object obj) {
    return obj instanceof SessionId && opaqueKey.equals(((SessionId) obj).opaqueKey);
  }
}


text:
define([
	"require",
	"intern",
	"intern!object",
	"intern/chai!assert",
	"intern/dojo/node!leadfoot/keys",
	"intern/dojo/node!leadfoot/helpers/pollUntil"
], function (require, intern, registerSuite, assert, keys, pollUntil) {

	registerSuite({
		name: "activationTracker functional tests",

		setup: function () {
			return this.remote
				.get(require.toUrl("./activationTracker.html"))
				.then(pollUntil("return ready || null;", [],
					intern.config.WAIT_TIMEOUT, intern.config.POLL_INTERVAL));
		},

		beforeEach: function () {
			return this.remote.findById("clearButton")
				.click()
				.end()
				.sleep(100);	// because the clear button clears things on a setTimeout()
		},

		basic: function () {
			this.timeout = intern.config.TEST_TIMEOUT;

			var environmentType = this.remote.environmentType;

			return this.remote
				.findById("first").click().end()
				.findById("activeStack").getProperty("value").then(function (activeStack) {
					assert.strictEqual(activeStack, "form", "activeStack #1");
				}).end()
				.findById("log").getProperty("value").then(function (log) {
					assert.strictEqual(log.trim(), "form activated", "log #1");
				}).end()
				.findById("second").click().end()	// focus another simple input
				.findById("activeStack").getProperty("value").then(function (activeStack) {
					assert.strictEqual(activeStack, "form", "activeStack #2");
				}).end()
				.findById("log").getProperty("value").then(function (log) {
					// Since the deliteful/Form widget didn't leave the focus chain it
					// shouldn't have any more events besides the original.
					assert.strictEqual(log.trim(), "form activated", "log #2");
				}).end()
				.findById("combobox").click().end()	// focus combobox
				.findById("activeStack").getProperty("value").then(function (activeStack) {
					assert.strictEqual(activeStack, "form, fieldset1, combobox", "activeStack #3");
				}).end()
				.findById("log").getProperty("value").then(function (log) {
					assert.strictEqual(log.trim(), "form activated\nfieldset1 activated\ncombobox activated", "log #3");
				}).end()
				.findById("combobox").click().end()	// focus combobox again to check for duplicate notifications
				.findById("activeStackChangeNotifications").getProperty("value").then(function (changes) {
					assert.strictEqual(changes, "2", "activeStack changes #1");
				}).end()
				.findById("editor").click().end()
				.findById("activeStack").getProperty("value").then(function (activeStack) {
					assert.strictEqual(activeStack, "form, editor", "activeStack #4");
				}).end()
				.findById("log").getProperty("value").then(function (log) {
					assert.strictEqual(log.trim(), "form activated\nfieldset1 activated\ncombobox activated\n" +
						"combobox deactivated\nfieldset1 deactivated\neditor activated", "log #4");
				}).end()

				// clicking spinner buttons should activate the spinner, even
				// though there's no actual DOM focus event
				.findByCssSelector("fake-spinner .button").click().end()
				.findById("activeStack").getProperty("value").then(function (activeStack) {
					if (environmentType.browserName === "internet explorer") {
						// click() doesn't generate pointerdown event on IE10+ and neither does
						// moveMouseTo().pressMouseButton(1).releaseMouseButton(1).
						// see https://github.com/theintern/leadfoot/issues/17.
						return;
					}
					assert.strictEqual(activeStack, "form, fieldset2, spinner", "activeStack #5");
				}).end();
		},

		keyboard: function () {
			this.timeout = intern.config.TEST_TIMEOUT;

			if (this.remote.environmentType.brokenSendKeys || !this.remote.environmentType.nativeEvents) {
				return this.skip("no keyboard support");
			}

			return this.remote
				.findById("first").click().end()
				.findById("activeStack").getProperty("value").then(function (activeStack) {
					assert.strictEqual(activeStack, "form", "activeStack #1");
				}).end()
				.findById("log").getProperty("value").then(function (log) {
					assert.strictEqual(log.trim(), "form activated", "log #1");
				}).end()
				.pressKeys(keys.TAB)	// focus another simple input
				.findById("activeStack").getProperty("value").then(function (activeStack) {
					assert.strictEqual(activeStack, "form", "activeStack #2");
				}).end()
				.findById("log").getProperty("value").then(function (log) {
					// Since the deliteful/Form widget didn't leave the focus chain it
					// shouldn't have any more events besides the original.
					assert.strictEqual(log.trim(), "form activated", "log #2");
				}).end()
				.pressKeys(keys.TAB)	// focus combobox
				.findById("activeStack").getProperty("value").then(function (activeStack) {
					assert.strictEqual(activeStack, "form, fieldset1, combobox", "activeStack #3");
				}).end()
				.findById("log").getProperty("value").then(function (log) {
					assert.strictEqual(log.trim(), "form activated\nfieldset1 activated\ncombobox activated", "log #3");
				}).end()
				.findById("combobox").click().end()	// focus combobox again to check for duplicate notifications
				.findById("activeStackChangeNotifications").getProperty("value").then(function (changes) {
					assert.strictEqual(changes, "2", "activeStack changes #1");
				}).end();
		},

		dropdown: function () {
			this.timeout = intern.config.TEST_TIMEOUT;

			var environmentType = this.remote.environmentType;

			return this.remote
				.findById("dropdownButton").click().end()
				.findByCssSelector("fake-popup")
					.isDisplayed().then(function (visible) {
						assert(visible, "popup visible");
					})
					.click()
					.end()
				.findById("activeStack").getProperty("value").then(function (activeStack) {
					if (environmentType.browserName === "internet explorer") {
						// click() doesn't generate pointerdown event on IE10+ and neither does
						// moveMouseTo().pressMouseButton(1).releaseMouseButton(1).
						// see https://github.com/theintern/leadfoot/issues/17.
						return;
					}
					assert.strictEqual(activeStack, "form, dropdownButton, popup", "activeStack #1");
				}).end();
		}
	});
});


text:
license: Licensed to the Apache Software Foundation (ASF) under one
         or more contributor license agreements.  See the NOTICE file
         distributed with this work for additional information
         regarding copyright ownership.  The ASF licenses this file
         to you 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.
---

Geolocation
===========

> El objeto `geolocation` proporciona acceso al sensor GPS del dispositivo.

La API Geolocation proporciona información sobre la localización del dispositivo, como la latitud y la longitud. Los orígenes de datos sobre localización pueden ser el Global Position System (GPS) o la localización obtenida por medio de la red, como la dirección IP, RFID, dirección MAC de dispositivos WiFi/Bluetooth, y los IDs de células GSM/CDMA. No hay garantía de que la API retorne la localización actual.

Esta API esta basada en la [W3C Geo location API Specification](http://dev.w3.org/geo/api/spec-source.html). Algunos dispositivos ya incluyen una implementación de esta API. En esos dispositivos se usara la API incluida en vez de la PhoneGap. Para dispositivos que no tienen soporte de geolocalización, La implementación PhoneGap debe ser compatible con las especificaciones W3C.

Métodos
-------

- geolocation.getCurrentPosition
- geolocation.watchPosition
- geolocation.clearWatch

Argumentos
----------

- geolocationSuccess
- geolocationError
- geolocationOptions

Objetos (Solo Lectura)
----------------------

- Position
- PositionError
- Coordinates


text:
package com.lyncode.xml.matchers;

import com.lyncode.test.matchers.extractor.ExtractFunction;
import com.lyncode.test.matchers.extractor.MatcherExtractor;
import org.hamcrest.Description;
import org.hamcrest.Matcher;

import javax.xml.namespace.QName;

public class QNameMatchers {
    public static Matcher<QName> localPart(final Matcher<String> matcher) {
        return new MatcherExtractor<QName, String>(matcher, extractLocalPart());
    }

    private static ExtractFunction<QName, String> extractLocalPart() {
        return new ExtractFunction<QName, String>() {
            @Override
            public String apply(QName input) {
                return input.getLocalPart();
            }

            @Override
            public void describeTo(Description description) {
                description.appendText("local part");
            }
        };
    }
}


text:
"""jobma permission classes"""
import logging

from django.conf import settings

from rest_framework.permissions import BasePermission

log = logging.getLogger(__name__)

class JobmaWebhookPermission(BasePermission):
    """Restrict access to jobma via access token"""

    def has_permission(self, request, view):
        if not settings.JOBMA_WEBHOOK_ACCESS_TOKEN:
            log.error("JOBMA_WEBHOOK_ACCESS_TOKEN not set")
            return False
        header = request.headers.get("authorization", "")
        if header.startswith("Bearer "):
            token = header[len("Bearer ") :]

            return token == settings.JOBMA_WEBHOOK_ACCESS_TOKEN
        return False


text:
package com.intellij.codeInsight.folding.impl.actions;

import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.codeInsight.actions.BaseCodeInsightAction;
import com.intellij.codeInsight.folding.impl.CollapseSelectionHandler;
import com.intellij.openapi.project.DumbAware;

/**
 * @author ven
 */
public class CollapseSelectionAction extends BaseCodeInsightAction implements DumbAware {
  protected CodeInsightActionHandler getHandler() {
    return new CollapseSelectionHandler();
  }
}


text:
byte getEEPROMHighAddress(int memAddress){
    return (byte)((memAddress) >> 8);
}

byte getEEPROMLowAddress(int memAddress){
    return (byte)(memAddress & 0xFF);
}

byte getEEPROMDevAddress(int memAddress){
    return E_24LC16BT_addr | (getEEPROMHighAddress(memAddress) & 0x07);
}

void writeEEPROM(int memAddress, const byte data){
  Wire.beginTransmission( getEEPROMDevAddress(memAddress) );
  Wire.write( memAddress );
  Wire.write(data);
  Wire.endTransmission();
  delay(5);
}

void writeEEPROM(int memAddress, const byte* buffer, int length){
    int page_i = 0;
    uint8_t c = 0;
    while (c < length){
        Wire.beginTransmission( getEEPROMDevAddress(memAddress + c) );
        Wire.write( getEEPROMLowAddress(memAddress + c) );
        page_i = 0;
        while ((page_i < 16) && (c < length)){
            Wire.write(buffer[c]);
            page_i++;
            c++;
        }
        Wire.endTransmission();
        delay(5);
    }
}

byte readEEPROM(int memAddress){
    Wire.beginTransmission( getEEPROMDevAddress(memAddress) );
    Wire.write( memAddress );
    Wire.endTransmission();
    byte rdata = 0x00;
    Wire.requestFrom( getEEPROMDevAddress(memAddress), 1 );
    if (Wire.available())
    {
        rdata = Wire.read();
    }
    return rdata;
}

void readEEPROM(int memAddress, byte* buffer, int length){
    Wire.beginTransmission( getEEPROMDevAddress(memAddress) );
    Wire.write( getEEPROMLowAddress(memAddress) );
    Wire.endTransmission();
    Wire.requestFrom( getEEPROMDevAddress(memAddress), (byte)length );
    int c = 0;
    for ( c = 0; c < length; c++ )
      if (Wire.available()) buffer[c] = Wire.read();
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/text_presserd" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/text_presserd" />
    <item android:state_focused="true" android:drawable="@drawable/text_focused" />
    <item android:state_focused="false" android:drawable="@drawable/text_normal" />
</selector>


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>QA Demo Admin Panel | </title>

    <link href="../vendors/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="../vendors/font-awesome/css/font-awesome.min.css" rel="stylesheet">

    <link href="../vendors/nprogress/nprogress.css" rel="stylesheet">

    <link href="../vendors/dropzone/dist/min/dropzone.min.css" rel="stylesheet">

    <link href="../build/css/custom.min.css" rel="stylesheet">

               QA Demo Admin Panel

                Welcome,

User 1

General

 Home

Dashboard

Dashboard2

Dashboard3

 Forms

General Form

Advanced Components

Form Validation

Form Wizard

Form Upload

Form Buttons

 UI Elements

General Elements

Media Gallery

Typography

Icons

Glyphicons

Widgets

Invoice

Inbox

Calendar

 Tables

Tables

Table Dynamic

 Data Presentation

Chart JS

Chart JS2

Moris JS

ECharts

Other Charts

Layouts

Fixed Sidebar

Fixed Footer

Live On

 Additional Pages

E-commerce

Projects

Project Detail

Contacts

Profile

 Extras

403 Error

404 Error

500 Error

Plain Page

Login Page

Pricing Tables

 Multilevel Menu

Level One

Level One

Level Two

Level Two

Level Two

Level One

 Landing Page Coming Soon

                    User 1

 Profile

                        50%
                        Settings

Help

 Log Out

                    6

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          John Smith
                          3 mins ago

                          Film festivals used to be do-or-die moments for movie makers. They were where...

                          See All Alerts

Form Upload

                    <input type="text" class="form-control" placeholder="Search for...">

                      <button class="btn btn-default" type="button">Go!</button>

Dropzone multiple file uploader

Settings 1

Settings 2

Drag multiple files to the box below for multi upload or click to select files. This is for demonstration purposes only, the files are not uploaded to any server.

                    <form action="form_upload.html" class="dropzone"></form>

            Bootstrap Base Admin Template by ABC


text:
import os
import sys
import unittest

sys.path.insert(1, os.path.abspath(os.path.join(__file__, "../..")))
import base_test
from selenium.common import exceptions
from selenium.webdriver.support import wait

class AlertsTest(base_test.WebDriverBaseTest):
    def setUp(self):
        self.wait = wait.WebDriverWait(self.driver, 5, ignored_exceptions = [exceptions.NoAlertPresentException])
        self.driver.get(self.webserver.where_is('modal/res/alerts.html'))

    def tearDown(self):
        try:
            self.driver.switch_to_alert().dismiss()
        except exceptions.NoAlertPresentException:
            pass

    # Alerts
    def test_should_allow_user_to_accept_an_alert(self):
        self.driver.find_element_by_css_selector('#alert').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.accept()
        self.driver.current_url

    def test_should_allow_user_to_accept_an_alert_with_no_text(self):
        self.driver.find_element_by_css_selector('#empty-alert').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.accept()
        self.driver.current_url

    def test_should_allow_user_to_dismiss_an_alert(self):
        self.driver.find_element_by_css_selector('#alert').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.dismiss()
        self.driver.current_url

    def test_should_allow_user_to_get_text_of_an_alert(self):
        self.driver.find_element_by_css_selector('#alert').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        value = alert.text
        alert.accept()
        self.assertEquals('cheese', value)

    def test_setting_the_value_of_an_alert_throws(self):
        self.driver.find_element_by_css_selector('#alert').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        with self.assertRaises(exceptions.ElementNotVisibleException):
            alert.send_keys('cheese')
        alert.accept()

    def test_alert_should_not_allow_additional_commands_if_dismissed(self):
        self.driver.find_element_by_css_selector('#alert').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.accept()
        with self.assertRaises(exceptions.NoAlertPresentException):
            alert.text

    # Prompts
    def test_should_allow_user_to_accept_a_prompt(self):
        self.driver.find_element_by_css_selector('#prompt').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.accept()
        self.wait.until(lambda x: x.find_element_by_css_selector('#text').text == '')

    def test_should_allow_user_to_dismiss_a_prompt(self):
        self.driver.find_element_by_css_selector('#prompt').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.dismiss()
        self.wait.until(lambda x: x.find_element_by_css_selector('#text').text == 'null')

    def test_should_allow_user_to_set_the_value_of_a_prompt(self):
        self.driver.find_element_by_css_selector('#prompt').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.send_keys('cheese')
        alert.accept()
        self.wait.until(lambda x: x.find_element_by_css_selector('#text').text == 'cheese')

    def test_should_allow_user_to_get_text_of_a_prompt(self):
        self.driver.find_element_by_css_selector('#prompt').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        value = alert.text
        alert.accept()
        self.assertEquals('Enter something', value)

    def test_prompt_should_not_allow_additional_commands_if_dismissed(self):
        self.driver.find_element_by_css_selector('#prompt').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.accept()
        with self.assertRaises(exceptions.NoAlertPresentException):
            alert.text

    def test_prompt_should_use_default_value_if_no_keys_sent(self):
        self.driver.find_element_by_css_selector('#prompt-with-default').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.accept()
        self.wait.until(lambda x: x.find_element_by_css_selector('#text').text == 'This is a default value')

    def test_prompt_should_have_null_value_if_dismissed(self):
        self.driver.find_element_by_css_selector('#prompt-with-default').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.dismiss()
        self.wait.until(lambda x: x.find_element_by_css_selector('#text').text == 'null')

    # Confirmations
    def test_should_allow_user_to_accept_a_confirm(self):
        self.driver.find_element_by_css_selector('#confirm').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.accept()
        self.wait.until(lambda x: x.find_element_by_css_selector('#text').text == 'true')

    def test_should_allow_user_to_dismiss_a_confirm(self):
        self.driver.find_element_by_css_selector('#confirm').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.dismiss()
        self.wait.until(lambda x: x.find_element_by_css_selector('#text').text == 'false')

    def test_setting_the_value_of_a_confirm_throws(self):
        self.driver.find_element_by_css_selector('#confirm').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        with self.assertRaises(exceptions.ElementNotVisibleException):
            alert.send_keys('cheese')
        alert.accept()

    def test_should_allow_user_to_get_text_of_a_confirm(self):
        self.driver.find_element_by_css_selector('#confirm').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        value = alert.text
        alert.accept()
        self.assertEquals('cheese', value)

    def test_confirm_should_not_allow_additional_commands_if_dismissed(self):
        self.driver.find_element_by_css_selector('#confirm').click()
        alert = self.wait.until(lambda x: x.switch_to_alert())
        alert.accept()
        with self.assertRaises(exceptions.NoAlertPresentException):
            alert.text

"""
    def test_switch_to_missing_alert_fails(self):
        with self.assertRaises(exceptions.NoAlertPresentException):
            self.driver.switch_to_alert()
"""

if __name__ == '__main__':
    unittest.main()


text:
#ifndef __UM_PROCESSOR_I386_H
#define __UM_PROCESSOR_I386_H

#include "linux/string.h"
#include <sysdep/host_ldt.h>
#include "asm/segment.h"

extern int host_has_cmov;

/* include faultinfo structure */
#include "sysdep/faultinfo.h"

struct uml_tls_struct {
	struct user_desc tls;
	unsigned flushed:1;
	unsigned present:1;
};

struct arch_thread {
	struct uml_tls_struct tls_array[GDT_ENTRY_TLS_ENTRIES];
	unsigned long debugregs[8];
	int debugregs_seq;
	struct faultinfo faultinfo;
};

#define INIT_ARCH_THREAD { \
	.tls_array  		= { [ 0 ... GDT_ENTRY_TLS_ENTRIES - 1 ] = \
				    { .present = 0, .flushed = 0 } }, \
	.debugregs  		= { [ 0 ... 7 ] = 0 }, \
	.debugregs_seq		= 0, \
	.faultinfo		= { 0, 0, 0 } \
}

static inline void arch_flush_thread(struct arch_thread *thread)
{
	/* Clear any TLS still hanging */
	memset(&thread->tls_array, 0, sizeof(thread->tls_array));
}

static inline void arch_copy_thread(struct arch_thread *from,
                                    struct arch_thread *to)
{
        memcpy(&to->tls_array, &from->tls_array, sizeof(from->tls_array));
}

#include <asm/user.h>

/* REP NOP (PAUSE) is a good thing to insert into busy-wait loops. */
static inline void rep_nop(void)
{
	__asm__ __volatile__("rep;nop": : :"memory");
}

#define cpu_relax()	rep_nop()

/*
 * Default implementation of macro that returns current
 * instruction pointer ("program counter"). Stolen
 * from asm-i386/processor.h
 */
#define current_text_addr() \
	({ void *pc; __asm__("movl $1f,%0\n1:":"=g" (pc)); pc; })

#define ARCH_IS_STACKGROW(address) \
       (address + 32 >= UPT_SP(&current->thread.regs.regs))

#define KSTK_EIP(tsk) KSTK_REG(tsk, EIP)
#define KSTK_ESP(tsk) KSTK_REG(tsk, UESP)
#define KSTK_EBP(tsk) KSTK_REG(tsk, EBP)

#include "asm/processor-generic.h"

#endif


text:
<?

/**
 * @version    $Id$
 * @author     Rasmus Andersson
 * @package    ab
 * @subpackage imap
 */
class IMAPMailbox {

	protected $name = 'Untitled';
	protected $path = 'INBOX.Untitled';
	protected $encoded_path = 'INBOX.Untitled';
	protected $delimiter = '.';
	protected $flags = 0;

	/** @var IMAPConnection  The connection which created this mailbox, or null if none */
	protected $connection = null;

	// These are loaded by calling IMAPConnection->getMailboxStatus($this->getPath(true))
	/** @var int  Total number of messages */
	protected $messages = -1;

	/** @var int  Number of unread messages */
	protected $recent = -1;

	/** @var int  Number of new/unseen, unread messages */
	protected $unseen = -1;

	/**
	 * @param  string
	 * @param  string
	 * @param  IMAPConnection
	 */
	public function __construct( $encoded_path, $connection = null ) {
		$this->path = mb_convert_encoding($encoded_path, IMAPConnection::getEncoding(), 'UTF7-IMAP');
		$this->encoded_path = $encoded_path;
		$this->connection = $connection;

		$p = strrpos($this->path, $this->delimiter);
		$this->name = ($p===false) ? $this->path : substr($this->path, $p+1);
	}

	/**
	 * @return int
	 */
	public function getNumMessages() {
		if($this->messages == -1)
			$this->fetchDetails();
		return $this->messages;
	}

	/**
	 * @return int
	 */
	public function getNumUnreadMessages() {
		if($this->unseen == -1)
			$this->fetchDetails();
		return $this->unseen;
	}

	/**
	 * @return int
	 */
	public function getNumRecentMessages() {
		if($this->recent == -1)
			$this->fetchDetails();
		return $this->recent;
	}

	/**
	 * @return void
	 */
	public function fetchDetailsIfNeeded()
	{
		if($this->messages == -1)
			$this->fetchDetails();
	}

	/**
	 * @return void
	 */
	protected function fetchDetails()
	{
		# Create new connection if it's missing
		if(!$this->connection) {
			$this->connection = new IMAPConnection();
			$this->connection->open($this->getPath(true), null, null, OP_HALFOPEN);
		}

		$nfo = $this->connection->getMailboxStatus($this->getPath(true), SA_MESSAGES|SA_RECENT|SA_UNSEEN);
		if(!is_object($nfo))
			var_dump($nfo);
		$this->messages = $nfo->messages;
		$this->recent = $nfo->recent;
		$this->unseen = $nfo->unseen;
	}

	/**
	 * @param  array
	 * @param  IMAPConnection
	 * @return Mailbox[]  Multi dimensional map, keyed by imap-encoded path's
	 * @usedby ImapConnection->getMailboxes()
	 */
	public static function fromList( $list, $connection = null )
	{
		$boxes_temp = array();

		foreach($list as $i => $m)
		{
			$mb = new self(substr($m->name, strpos($m->name,'}')+1), $connection);
			$mb->delimiter = $m->delimiter;
			$mb->flags = $m->attributes;
			$boxes_temp[$mb->getPath()] = $mb;
		}

		# Sort
		$boxes = array();
		ksort($boxes_temp);
		foreach($boxes_temp as $mb)
		{
			$r = explode($m->delimiter, $mb->getPath(true));
			eval('$boxes[\'' . implode('\'][\'', $r) . '\'][\'#\'] = $mb;');
		}

		return $boxes;
	}

	/** @return string */
	public function getPath( $imapEncoded = false ) {
		if($imapEncoded)
			return $this->encoded_path;
		else
			return $this->path;
	}

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

	/**
	 * Check if this mailbox has "children" (there are mailboxes below this one)
	 *
	 * @return bool
	 */
	public function hasChilds() {
		return !(($this->flags & LATT_NOINFERIORS) == LATT_NOINFERIORS);
	}

	/**
	 * If this is a container (not a mailbox) you cannot open it.
	 *
	 * @return bool
	 */
	public function canOpen() {
		return !(($this->flags & LATT_NOSELECT) == LATT_NOSELECT);
	}

	/**
	 * @param  string
	 * @return string
	 */
	public function toXMLStartTag( $tagName = 'box' )
	{
		$this->fetchDetailsIfNeeded();
		return '<' . $tagName . ' messages="' . $this->messages
			. '" unread="' . $this->unseen
			. '" recent="' . $this->recent
			. '" name="' . Utils::xmlEscape($this->getName())
			. '" path="' . Utils::xmlEscape($this->getPath(true)) . '"';
	}
}

?>


text:
CPPARSE
=
cpparse is a small combinator/parser utility using templates and C++11, based off of Haskell's [Parsec](https://www.haskell.org/haskellwiki/Parsec) library.

BASICS
-
cpparse operates around three main classes:

- `buffer<T>`: Maintains the current position along an input value, which is only advanced upon a successful parse.
  - `buffer::buffer(const T&)`: construct a buffer containing the given input.
- `maybe<T>`: The class's value can only be accessed when it is `just`. `nothing` means no value is contained.
  - `bool is_just()`/`bool is_nothing()`: test if a value is contained. Implicit conversion to `bool` is also possible.
  - `T from_just()`/`T operator*()`: retrieve the value contained. Throws an exception if the class is `nothing`.
- `parser<R, T>`: All parser classes extend from this interface, which takes an input type `T` and an output type `R`.
  - `maybe<T> parser::parse(buffer<T>&)`: apply the parser to the given input.

### Example

    using namespace cpparse;

    auto my_parser = string("hello"); //< Create a string parser.
    buffer<std::string> buf("hello world");

    // Apply the parser to the input string.
    auto result = my_parser->parse(buf);
    if (result)
        std::cout << *result << std::endl;

will output `hello`, and the buffer will contain, from its current position, `" world"`.

PARSERS
-
cpparse includes some default common parser behaviors.

### Char & String Parsers

The basic units for parsing string input. Created with the `string` and `character` functions.

    auto ch_parser = character('c');

Applying `ch_parser` to a buffer containing `"cello"` would return a character variable with value `'c'`. Similarly, a string parser returns an `std::string` value equal to the parser's input string.

### OneOf Parsers

The `one_of` function takes an `std::vector` of values and tries to match the input to a single one of those values. This function also has a character parser override that takes an `std::string`, and tries to match one of its characters with the input.

    auto some_ch = one_of("abcd");

Applying `some_ch` to a buffer of `"develop"` would return `'d'`, while applying it to `"apple"` would return `'a'`.

For the opposite behavior of the OneOf Parser, `none_of` behaves as described above, but matches any value not specified.

### Option Parsers

The `option` function takes another parser as input, along with an optional value. It behaves the same way as the parser it was passed, but upon failure, returns the optional value instead of `maybe::nothing`.

    auto perhaps = option(string("hello"), "see ya");

When given an input of `"hello world"`, the parser returns `"hello"`, but with input such as `"goodbye world"`, the parser will return `"see ya"` instead.

An additional function, `optional`, takes no alternate value, and returns an empty type upon failure (`""` for `std::string`).

### Skip Parsers

The `skip` function allows output to be ignored upon success.

    auto ignore = skip("misc");

With the input `"misc info"`, the parser simply returns an empty type value, in this case, `""`. This is mainly useful when working with other parsers in a combinator.

### Forward Parsers

The `placeholder<R, T>` function allows an empty parser to be defined and set later (with `set_target`). Note that template arguments must be explicitly specified.

    auto recurse = placeholder<std::string, std::string>();
    recurse->set_target(string("iterate"));

When `recurse` is used, the string parser will be applied to the input. This can be used for recursive parsing when used in conjunction with combinators.

### Lift Parsers

The `lift<R>` function takes an existing parser, and transforms its result into a new type/value with a lambda or function pointer. The new return type of the parser must be specified as a template argument, and the passed lambda's parameter type must be equal to the result type of the inner parser.

    auto to_int = lift<int>(one_of("1234567890"),
        [](const std::string& s)
        {
            int i = atoi(s.c_str());
            return i;
        });

When applied to the string `"4"`, the above parser will return the integer `4`.

COMBINATORS
-
cpparse allows for parsers to be combined to create more complex behaviors.

### Many Combinators

The `many` and `many1` functions allow a parser to be applied repeatedly to the input. `many` will still succeed if no input is matched, while `many1` requires the parser is applied once to succeed.

    auto sleeping = many(character('z'));

When applied to `"zzz"`, the string `"zzz"` is returned. Note that using `many` with a character parser automatically converts the result to a string.

When `many` is applied to other input types, a template parameter `accumulator` must be specified. Available options are:

- `vector_accumulator`: returns an `std::vector` containing an entry for each parse result.
- `concat_accumulator`: tries to combine its output with the `+=` operator.

### Choice Combinators

The `|` operator attempts to apply parsers to the input, in order, until one succeeds, returning that value. If all parsers fail, `maybe::nothing` is returned.

All parsers in the choice must be the same type.

    auto greeting = string("hello") | string("hola");

The `greeting` parser will first attempt to match `"hello"` to the input, and then tries `"hola"` if that fails.

### Sequence Combinators

The `>>` operator applies multiple combinators in the order given. When all parsers are successful, the result of the last parser in the chain is returned. If one of the parsers fails, the chain stops executing, and `maybe::nothing` is returned.

Note that each element of the sequence can be a different parser type.

    auto alphabet = character('a') >> string("b") >> character('c');

When the above parser is applied to the input `"abcd"`,  `'c'` is returned. However, if it is applied to `"adc"`, the parser fails and `maybe::nothing` is returned.

### Merge Combinators

The `>>=` operator behaves similarly to the sequence combinator, but combines the output of each parser into one result. This is where the `skip` function is most useful.

Each merged parser must be of the same type.

    auto squished = string("no") >>= skip(string(" ")) >>= string("space");

When applied to the string `"no space"`, the above parser would return the string `"nospace"`.

### Block Combinators

The `block()` combinator works similarly to the sequence combinator as well, but includes a special function at the end to transform the parser results.

This combinator ended up being rather complicated trying to imitate Haskell's "do" notation. Use of the block combinator requires three steps during its creation:

- Call the `block<R, T, M>()` function: This function requires three template parameters: the final output type, the input type, and the output type of the primary parser statements.
- Specify the steps with the `->*` operator: each parser will be executed in the order given.
- Give a processing function with the `^` operator: specify, with a lambda or function pointer, how the data from the parsers should be combined/used.

To carry data between the parser sequence and the processing function, all parsers can be "tagged" with a name (using the `<<` operator and the `tag()` function). When the block combinator is running, output from each parser with a valid tag is placed in an `std::map<std::string, M>`, mapping the tag name to the result. This map is then passed to the processing function.

For maximum flexibility, the block combinator accepts parsers of all return types. However, tagged values will only be stored  if they match the `M` type specified in the `block()` statement.

    auto html_name = block<std::string, std::string, std::string>()
        ->* ( character('<')                     )
        ->* ( many(none_of(">")) << tag("inner") )
        ->* ( character('>')                     )
        ^ [](const std::map<std::string, std::string>& m)
        {
            return m.at("inner");
        };

When presented with the input `"<table>"`, the string `"table"` will be returned.

UTILITY FUNCTIONS
-
cpparse contains some pre-defined frequently used values for parsing strings and characters, and other common parser patterns.

### Strings and Characters

- `upper()`: parses any uppercase alphabetical character.
- `lower()`: parses any lowercase letter.
- `letter()`: parses a case-insensitive character of the alphabet.
- `digit()`: parses a numeric character.
- `symbol()`: parses one of a variety of non-alphanumeric characters.

### Lifting

- `lift_string()`: convert a character parser to a string parser.
- `lift_vector()`: convert to an `std::vector` of a value's type, containing a single element with the parser's result.

### Block Parsing

- `sep_by()`: parse a repeating sequence (one or more) of a parser value followed by a separator value.
- `end_by()`: behaves the same as `sep_by()`, however, the sequence must be terminated by the separator.


text:
@interface CVFloatingTableView : NSTableView
{
	NSColor *_tableBackgroundColor;
}

- (void)setTablebackgroundColor: (NSColor *)aColor;
@end


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <objectAnimator
        android:duration="700"
        android:propertyName="tableHorizontalPivotWidth"
        android:valueFrom="0"
        android:valueTo="1"
        android:valueType="floatType" />
</set>


text:
require File.dirname(__FILE__) + '/../../orawls_core'

module Puppet
  Type.newtype(:wls_jms_queue) do
    include EasyType
    include Utils::WlsAccess
    extend Utils::TitleParser

    desc 'This resource allows you to manage a Queue in a JMS Module of an WebLogic domain.'

    ensurable

    set_command(:wlst)

    to_get_raw_resources do
      Puppet.debug "index #{name}"
      environment = { 'action' => 'index', 'type' => 'wls_jms_queue' }
      wlst template('puppet:///modules/orawls/providers/wls_jms_queue/index.py.erb', binding), environment
    end

    on_create  do | command_builder |
      wlst_action = 'create'
      Puppet.info "create #{name} "
      template('puppet:///modules/orawls/providers/wls_jms_queue/create_modify.py.erb', binding)
    end

    on_modify  do | command_builder |
      wlst_action = 'modify'
      Puppet.info "modify #{name} "
      template('puppet:///modules/orawls/providers/wls_jms_queue/create_modify.py.erb', binding)
    end

    on_destroy  do | command_builder |
      Puppet.info "destroy #{name} "
      template('puppet:///modules/orawls/providers/wls_jms_queue/destroy.py.erb', binding)
    end

    parameter :domain
    parameter :name
    parameter :jmsmodule
    parameter :queue_name
    parameter :timeout
    property :distributed
    property :jndiname
    property :subdeployment
    property :balancingpolicy
    property :quota
    property :defaulttargeting
    property :errordestination
    property :expirationloggingpolicy
    property :redeliverylimit
    property :expirationpolicy
    property :redeliverydelay
    property :timetodeliver
    property :deliverymode
    property :timetolive
    property :forwarddelay
    property :templatename
    property :messagelogging
    property :destination_keys
    property :insertionpaused
    property :consumptionpaused
    property :productionpaused

    add_title_attributes(:jmsmodule, :queue_name) do
      /^((.*\/)?(.*):(.*)?)$/
    end

    autorequire(:wls_jms_template) { "#{jmsmodule}:#{templatename}" }
  end
end


text:
package com.linecorp.bot.client;

import java.util.function.Supplier;

/**
 * Special {@link Supplier} for Channel Access Token.
 *
 * You can implement it to return same channel tokens.
 * Or refresh tokens internally.
 */
@FunctionalInterface
public interface ChannelTokenSupplier extends Supplier<String> {
}