text:
<?php

namespace Opf\Route;

class Route implements RouteInterface
{
    protected $route;
    protected $regex;
    protected $matches;
    protected $values;

    protected $controller;
    protected $action;

    public function __construct($route, $controller, $action = 'main')
    {
        $this->route = $route;
        $this->regex = $route;

        $this->setController($controller);
        $this->setAction($action);
    }

    public function setController($controller)
    {
        $this->controller = $controller;
    }

    public function getController()
    {
        return $this->controller;
    }

    public function setAction($action)
    {
        $this->action = $action;
    }

    public function getAction()
    {
        return $this->action;
    }

    public function __toString()
    {
        return $this->route;
    }

    public function getVar()
    {
        foreach($this->values as $key=>$match) {
            $this->values[$key] = $this->matches[$key];
       }

        return $this->values;
    }

    public function match($path)
    {
        $this->setRegex();

        return preg_match('#^' . $this->regex . '$#', $path, $this->matches);
    }

    public function setRegex()
    {
        $matches = array();
        preg_match_all('#{([a-z][a-zA-Z0-9_]*)}#', $this->regex, $matches, PREG_SET_ORDER);

        foreach ($matches as $match) {
            $name = $match[1];
            $this->values[$name] = '';
            $find = '{'.$name.'}';
            $this->regex = str_replace($find, "(?P<{$name}>[^/]+)", $this->regex);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;

namespace Twee2Z.CodeGen.Variable
{
    [DebuggerDisplay("GlobalVariableNumber = {GlobalVariableNumber}")]
    class ZGlobalVariable : ZVariable
    {
        public ZGlobalVariable(byte globalVariableNumber)
            : base(VariableKind.Global)
        {
            if (globalVariableNumber > 239)
                throw new ArgumentException("There are 240 global variables to choose from only.", "globalVariableNumber");

            _variableNumber = (byte)(globalVariableNumber + 0x10);
        }

        public byte GlobalVariableNumber
        {
            get
            {
                return (byte)(_variableNumber - 0x10);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Globalization;
using Xunit;

namespace System.Globalization.Tests
{
    public class DateTimeFormatInfoClone
    {
        // PosTest1: Call Clone method on a instance created from Ctor
        [Fact]
        public void PosTest1()
        {
            DateTimeFormatInfo expected = new DateTimeFormatInfo();

            VerificationHelper(expected, expected.Clone());
        }

        // PosTest2: Call Clone method on a instance created from several cultures
        [Fact]
        public void PosTest2()
        {
            DateTimeFormatInfo expected = new CultureInfo("en-us").DateTimeFormat;
            VerificationHelper(expected, expected.Clone());

            expected = new CultureInfo("fr-FR").DateTimeFormat;
            VerificationHelper(expected, expected.Clone());
        }

        // PosTest3: Call Clone method on a readonly instance created from several cultures
        [Fact]
        public void PosTest3()
        {
            DateTimeFormatInfo expected = CultureInfo.InvariantCulture.DateTimeFormat;
            VerificationHelper(expected, expected.Clone());
        }

        private void VerificationHelper(DateTimeFormatInfo expected, Object obj)
        {
            Assert.True(obj is DateTimeFormatInfo);
            DateTimeFormatInfo actual = obj as DateTimeFormatInfo;
            Assert.False(actual.IsReadOnly);
            IsEquals(actual.AbbreviatedDayNames, expected.AbbreviatedDayNames);
            IsEquals(actual.AbbreviatedMonthGenitiveNames, expected.AbbreviatedMonthGenitiveNames);
            IsEquals(actual.AbbreviatedMonthNames, expected.AbbreviatedMonthNames);
            IsEquals(actual.DayNames, expected.DayNames);
            IsEquals(actual.MonthGenitiveNames, expected.MonthGenitiveNames);
            IsEquals(actual.MonthNames, expected.MonthNames);
            IsEquals(actual.ShortestDayNames, expected.ShortestDayNames);
            IsEquals(actual.AMDesignator, expected.AMDesignator);
            //DateTimeFormatInfo.DateSeparator property has been removed
            IsEquals(actual.FullDateTimePattern, expected.FullDateTimePattern);
            IsEquals(actual.LongDatePattern, expected.LongDatePattern);
            IsEquals(actual.LongTimePattern, expected.LongTimePattern);
            IsEquals(actual.MonthDayPattern, expected.MonthDayPattern);
            IsEquals(actual.PMDesignator, expected.PMDesignator);
            IsEquals(actual.RFC1123Pattern, expected.RFC1123Pattern);
            IsEquals(actual.ShortDatePattern, expected.ShortDatePattern);
            IsEquals(actual.ShortTimePattern, expected.ShortTimePattern);
            IsEquals(actual.SortableDateTimePattern, expected.SortableDateTimePattern);
            //DateTimeFormatInfo.TimeSeparator property has been removed
            IsEquals(actual.UniversalSortableDateTimePattern, expected.UniversalSortableDateTimePattern);
            IsEquals(actual.YearMonthPattern, expected.YearMonthPattern);
            IsEquals(actual.CalendarWeekRule, expected.CalendarWeekRule);
            IsEquals(actual.FirstDayOfWeek, expected.FirstDayOfWeek);
        }

        private void IsEquals(string str1, string str2)
        {
            Assert.Equal(str2, str1);
        }

        private void IsEquals(DayOfWeek value1, DayOfWeek value2)
        {
            Assert.Equal(value2, value1);
        }

        private void IsEquals(CalendarWeekRule value1, CalendarWeekRule value2)
        {
            Assert.Equal(value2, value1);
        }

        private void IsEquals(string[] array1, string[] array2)
        {
            Assert.Equal(array2, array1);
        }
    }
}


text:
title: AesiContentProvider.<init> - aesi-eclipse
---

[aesi-eclipse](../../index.html) / [com.virtlink.aesi.eclipse.structureoutline](../index.html) / [AesiContentProvider](index.html) / [<init>](.)

# <init>

`AesiContentProvider(documentProvider: IDocumentProvider)`


text:
namespace SIL.Linux.Logging
{
	/// <summary>
	/// "Facility" value for syslog() calls. Use these with SyslogLogger objects.
	/// Comments below are derived from the libc source and RFC 3164.
	/// All values are bitshifted left by 3 to match the values defined in libc's sys/syslog.h.
	/// </summary>
	public enum SyslogFacility
	{
		/// <summary>
		/// Kernel messages; user code cannot use this value, and will be assigned the User facility if it attempts to do so.
		/// </summary>
		Kernel = 0 << 3,

		/// <summary>
		/// User-level messages. This is the value most programs should be using.
		/// </summary>
		User = 1 << 3,

		/// <summary>
		/// Mail system
		/// </summary>
		Mail = 2 << 3,

		/// <summary>
		/// System daemons
		/// </summary>
		Daemon = 3 << 3,

		/// <summary>
		/// Security and/or authorization messages
		/// </summary>
		SecurityOrAuth = 4 << 3,

		/// <summary>
		/// Messages generated interally by syslogd
		/// </summary>
		InternalUseOnly = 5 << 3,

		/// <summary>
		/// Line printer subsystem
		/// </summary>
		LPRSubsystem = 6 << 3,

		/// <summary>
		/// Network news subsystem
		/// </summary>
		NNTPSubsystem = 7 << 3,

		/// <summary>
		/// UUCP subsystem
		/// </summary>
		UUCPSubsystem = 8 << 3,

		/// <summary>
		/// Clock daemon (cron, at, etc). Per RFC 3164, there are two facility values in use for clock daemons.
		/// </summary>
		ClockDaemon1 = 9 << 3,

		/// <summary>
		/// Security and/or authorization messages (private)
		/// </summary>
		SecurityOrAuthPrivate = 10 << 3,

		/// <summary>
		/// FTP subsystem
		/// </summary>
		FTPSubsystem = 11 << 3,

		/// <summary>
		/// NTP subsystem
		/// </summary>
		NTPSubsystem = 12 << 3,

		/// <summary>
		/// Log audit messages
		/// </summary>
		LogAudit = 13 << 3,

		/// <summary>
		/// Log alert messages
		/// </summary>
		LogAlert = 14 << 3,

		/// <summary>
		/// Clock daemon (cron, at, etc). Per RFC 3164, there are two facility values in use for clock daemons.
		/// </summary>
		ClockDaemon2 = 15 << 3,

		/// <summary>
		/// Reserved for local use
		/// </summary>
		LocalUse0 = 16 << 3,

		/// <summary>
		/// Reserved for local use
		/// </summary>
		LocalUse1 = 17 << 3,

		/// <summary>
		/// Reserved for local use
		/// </summary>
		LocalUse2 = 18 << 3,

		/// <summary>
		/// Reserved for local use
		/// </summary>
		LocalUse3 = 19 << 3,

		/// <summary>
		/// Reserved for local use
		/// </summary>
		LocalUse4 = 20 << 3,

		/// <summary>
		/// Reserved for local use
		/// </summary>
		LocalUse5 = 21 << 3,

		/// <summary>
		/// Reserved for local use
		/// </summary>
		LocalUse6 = 22 << 3,

		/// <summary>
		/// Reserved for local use
		/// </summary>
		LocalUse7 = 23 << 3
	}
}


text:
/**
 * controller.js
 *
 * Singleton class for handling input
 */
/* global controller:true, canvas */

(function () {
  "use strict";

  var Controller = function (params) {
    this.currentPressedKeys = {};
    this.isMouseDown = false;
    this.mousePos = vec3.fromValues(0.0, 0.0, 0.0);
    this.keyDownCallbacks = [];
  };

  Controller.prototype.keyDown = function (event) {
    var i;

    this.currentPressedKeys[event.keyCode] = true;

    for (i = 0; i < this.keyDownCallbacks.length; i += 1) {
      this.keyDownCallbacks[i](event.keyCode);
    }
  };

  Controller.prototype.keyUp = function (event) {
    this.currentPressedKeys[event.keyCode] = false;
  };

  Controller.prototype.registerKeyDownCallback = function (callback) {
    this.keyDownCallbacks.push(callback);
  };

  Controller.prototype.keyIntersect = function (keys) {
    for (var i = 0; i < keys.length; i += 1) {
      if (!this.currentPressedKeys[keys[i]]) {
        return false;
      }
    }

    return true;
  };

  Controller.prototype.keyUnion = function (keys) {
    for (var i = 0; i < keys.length; i += 1) {
      if (this.currentPressedKeys[keys[i]]) {
        return true;
      }
    }

    return false;
  };

  Controller.prototype.mouseDown = function (event) {
    this.isMouseDown = true;
  };

  Controller.prototype.mouseUp = function (event) {
    this.isMouseDown = false;
  };

  Controller.prototype.mouseMove = function (event) {
    this.mousePos[0] = event.offsetX;
    this.mousePos[1] = event.offsetY;
  };

  Controller.prototype.getMouseCoord = function () {
    return this.mousePos;
  };

  var ctrler = new Controller();

  // Set the singleton
  controller = ctrler;

  /**
   * Register event callbacks
   */
  Controller.prototype.registerEvents = function (canvas) {
    document.onkeydown = function (event) { ctrler.keyDown(event); };
    document.onkeyup = function (event) { ctrler.keyUp(event); };

    canvas.onmousedown = function (event) { ctrler.mouseDown(event); };
    canvas.onmouseup = function (event) { ctrler.mouseUp(event); };
    canvas.onmousemove = function (event) { ctrler.mouseMove(event); };

  };
}());


text:
package org.apache.wicket.request.resource.caching.version;

import org.apache.wicket.request.resource.caching.IStaticCacheableResource;
import org.apache.wicket.util.lang.Args;

/**
 * provides a static version string for all package resources
 *
 * @author Peter Ertl
 *
 * @since 1.5
 */
public class StaticResourceVersion implements IResourceVersion
{
	private final String version;

	/**
	 * create static version provider
	 *
	 * @param version
	 *             static version string to deliver for all queries resources
	 */
	public StaticResourceVersion(String version)
	{
		this.version = Args.notNull(version, "version");
	}

	@Override
	public String getVersion(IStaticCacheableResource resource)
	{
		return version;
	}
}


text:
const React = require('react-native');

const { StyleSheet } = React;

module.exports = StyleSheet.create({
  sidebar: {
    flex: 1,
    padding: 10,
    paddingRight: 0,
    paddingTop: 30,
    backgroundColor: '#304771',
  },
});


text:
insync.js
======

Asynchronous (Lazy-Loaded) Inline Javascript

### What is it? ###

This is a very small script that rewrites `<script>` tags that have the MIME type of `text/plain` to tags that have
the MIME type `text/javascript`.

### Why would you use it? ###

This technique allows you to add script blocks to a page, but not actually evaluate them until a later point in time.

Possible use cases:

* Inline scripts that depend on asynchronously loaded external scripts.
* Simultaneous execution of multiple script blocks across template fragments without jQuery (just put `insync()` call at bottom of page)
* To be fancy...?

### How do you use it? ###

First, add the script, either by copy/pasting into your page (it's really tiny), or linking externally.

Add your script blocks with the `text/plain` MIME type, such as:

    <script type="text/plain>
      alert("Holy asynchronous Javascript, Batman!");
    </script>

Then, just call `insync()` after those inline code blocks have been processed (i.e. either put the `insync()` call in
a callback for the document loading, or at the bottom of your page).

**Note: Don't use on code blocks that contain a `document.write`**

### What browsers support it? ###

To the best of our knowledge, all of them. We've tested on current builds of Chrome, Firefox, iOS Safari, and Android,
and those all work perfectly.

While not exactly conventional, the technique seems to be standards compliant. And some sites, like LinkedIn, use a similar
technique (with a custom MIME type, which is arguably not standards compliant).

### Can you improve on it? ###

Sure! It's a pretty bare bones script, and our JavaScript skills are far from perfect. There are also some
features that might improve it (though we don't plan to add in ourselves):

* Optionally pass in a class name (`<script>` tags can have classes) that targets specific blocks for activation
* Optimize for minification

### Credits ###

We originally noticed the technique on StackOverflow by the users
[YoussefTaghlabi](http://stackoverflow.com/users/1283955/yousseftaghlabi)
and [Rocket Hazmat](http://stackoverflow.com/users/206403/rocket-hazmat) on
[this question](http://stackoverflow.com/questions/8946715/lazy-loading-javascript-and-inline-javascript).


text:
using Antlr4.Runtime;
using MetaDslx.VisualStudio.Utilities;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MetaDslx.VisualStudio.Classification
{
    internal class TrackedBlock
    {
        public ITrackingSpan Block;
        public ITextVersion Version;
        public LexerState StartState;
        public LexerState EndState;
        public List<ClassificationSpan> CachedClassifications = new List<ClassificationSpan>();

        public void ClearCache()
        {
            this.CachedClassifications.Clear();
        }

        public void CacheClassification(ClassificationSpan classification)
        {
            this.CachedClassifications.Add(classification);
        }
    }

    public class LexerState : IEquatable<LexerState>
    {
        public LexerState(Lexer lexer)
        {
            this.Mode = lexer._mode;
            if (lexer._modeStack != null)
            {
                this.ModeStack = lexer._modeStack.Count > 0 ? new List<int>(lexer._modeStack) : null;
            }
        }
        public int Mode { get; private set; }
        public List<int> ModeStack { get; private set; }

        public override bool Equals(object obj)
        {
            return this.Equals(obj as LexerState);
        }

        public virtual bool Equals(LexerState other)
        {
            if (other == null)
            {
                return this.Mode == 0 && (this.ModeStack == null || this.ModeStack.Count == 0);
            }
            if (this.Mode != other.Mode) return false;
            if ((this.ModeStack == null || this.ModeStack.Count == 0) && (other.ModeStack == null || other.ModeStack.Count == 0)) return true;
            if (this.ModeStack == null || other.ModeStack == null) return false;
            if (this.ModeStack.Count != other.ModeStack.Count) return false;
            for (int i = 0; i < this.ModeStack.Count; i++)
            {
                if (this.ModeStack[i] != other.ModeStack[i]) return false;
            }
            return true;
        }

        public override int GetHashCode()
        {
            return Hash.Combine(this.Mode, this.ModeStack.GetHashCode());
        }

        public virtual void Restore(Lexer lexer)
        {
            lexer._mode = this.Mode;
            lexer._modeStack.Clear();
            if (this.ModeStack != null && this.ModeStack.Count > 0)
            {
                lexer._modeStack.AddRange(this.ModeStack);
            }
        }

    }

    public abstract class Antlr4LexerClassifier : IClassifier
    {
        private const int BlockSize = 256;
        public static readonly ICharStream EmptyCharStream = new AntlrInputStream();

        private IClassificationTypeRegistryService classificationRegistryService;
        private IStandardClassificationService standardClassificationService;

        private ITextBuffer textBuffer;
        private Lexer lexer;
        private List<TrackedBlock> trackedBlocks = new List<TrackedBlock>();
        private List<TrackedBlock> cachedBlocks = new List<TrackedBlock>();

        public Antlr4LexerClassifier(ITextBuffer textBuffer, MetaDslxMefServices mefServices, Lexer lexer)
        {
            this.textBuffer = textBuffer;
            this.lexer = lexer;
            this.classificationRegistryService = mefServices.GetService<IClassificationTypeRegistryService>();
            this.standardClassificationService = mefServices.GetService<IStandardClassificationService>();
            this.UpdateBlocks(new SnapshotSpan(this.textBuffer.CurrentSnapshot, 0, this.textBuffer.CurrentSnapshot.Length), false);
        }

        public event EventHandler<ClassificationChangedEventArgs> ClassificationChanged;
        public IClassificationTypeRegistryService ClassificationTypeRegistryService => this.classificationRegistryService;
        public IStandardClassificationService StandardClassificationService => this.standardClassificationService;

        public ITextBuffer TextBuffer => this.textBuffer;
        public Lexer Lexer => this.lexer;

        //Invoke ClassificationChanged that cause editor to re-classify specified span
        protected void Invalidate(SnapshotSpan span)
        {
            if (ClassificationChanged != null)
                ClassificationChanged(this, new ClassificationChangedEventArgs(span));
        }

        protected virtual LexerState SaveLexerState()
        {
            LexerState state = new LexerState(this.lexer);
            return state;
        }

        protected abstract IClassificationType GetClassificationType(int tokenType, int mode);

        public IList<ClassificationSpan> GetClassificationSpans(SnapshotSpan span)
        {
            List<ClassificationSpan> result = new List<ClassificationSpan>();
            this.UpdateBlocks(span, true);
            int position = span.Start.Position;
            int index = this.FindBlockIndex(span, span.Start.Position, false);
            while (index < this.trackedBlocks.Count)
            {
                TrackedBlock block = this.trackedBlocks[index];
                this.CacheBlock(span, block);
                int classificationStartPosition = block.Block.GetStartPoint(span.Snapshot);
                int classificationIndex = 0;
                while(classificationIndex < block.CachedClassifications.Count && position < span.End.Position)
                {
                    ClassificationSpan classification = block.CachedClassifications[classificationIndex];
                    int classificationEndPosition = classificationStartPosition + classification.Span.Length;
                    if (span.OverlapsWith(Span.FromBounds(classificationStartPosition, classificationEndPosition)))
                    {
                        result.Add(classification);
                    }
                    ++classificationIndex;
                    classificationStartPosition = classificationEndPosition;
                    if (classificationEndPosition >= span.End.Position) return result;
                }
                ++index;
            }
            return result;
        }

        private void UpdateBlocks(SnapshotSpan span, bool cache)
        {
            int index = this.FindBlockIndex(span, span.Start.Position, false);
            while (index < this.trackedBlocks.Count)
            {
                TrackedBlock block = this.trackedBlocks[index];
                Span blockSpan = block.Block.GetSpan(span.Snapshot);
                if (blockSpan.Length == 0)
                {
                    this.trackedBlocks.RemoveAt(index);
                }
                else
                {
                    if (blockSpan.Start >= span.End.Position)
                    {
                        return;
                    }
                    if (block.Version != span.Snapshot.Version || (cache && block.CachedClassifications.Count == 0 && blockSpan.Length > 0))
                    {
                        this.UpdateBlock(span, ref index, cache);
                    }
                    ++index;
                }
            }
            this.AddBlocksToEnd(span, cache);
        }

        private void AddBlocksToEnd(SnapshotSpan span, bool cache)
        {
            TrackedBlock prevBlock = null;
            int prevBlockEnd = 0;
            if (this.trackedBlocks.Count > 0)
            {
                prevBlock = this.trackedBlocks[this.trackedBlocks.Count - 1];
                prevBlockEnd = prevBlock.Block.GetEndPoint(span.Snapshot);
                if (prevBlockEnd >= span.End.Position)
                {
                    return;
                }
            }
            int nextBlockEnd = Math.Min(prevBlockEnd + BlockSize, span.Snapshot.Length);
            if (nextBlockEnd > prevBlockEnd)
            {
                TrackedBlock nextBlock = new TrackedBlock();
                nextBlock.Block = span.Snapshot.CreateTrackingSpan(Span.FromBounds(prevBlockEnd, nextBlockEnd), SpanTrackingMode.EdgeExclusive);
                nextBlock.StartState = prevBlock?.EndState;
                this.trackedBlocks.Add(nextBlock);
                int index = this.trackedBlocks.Count - 1;
                this.UpdateBlock(span, ref index, cache);
            }
        }

        private void UpdateBlock(SnapshotSpan span, ref int index, bool cache)
        {
            bool invalidate = false;
            TrackedBlock block = this.trackedBlocks[index];
            while (block != null)
            {
                Span blockSpan = block.Block.GetSpan(span.Snapshot);
                this.LexBlock(span, block, cache && (blockSpan.Start < span.End.Position));
                blockSpan = block.Block.GetSpan(span.Snapshot);
                if (invalidate) this.InvalidateBlock(span, block);

                TrackedBlock nextBlock = null;
                ++index;
                if (index < this.trackedBlocks.Count)
                {
                    while (index < this.trackedBlocks.Count)
                    {
                        nextBlock = this.trackedBlocks[index];
                        Span nextBlockSpan = nextBlock.Block.GetSpan(span.Snapshot);
                        if (nextBlockSpan.End <= blockSpan.End)
                        {
                            this.trackedBlocks.RemoveAt(index);
                        }
                        else if (nextBlockSpan.Start > blockSpan.End)
                        {
                            int nextBlockEnd = Math.Min(blockSpan.End + BlockSize, nextBlockSpan.Start);
                            nextBlock = new TrackedBlock();
                            nextBlock.Block = span.Snapshot.CreateTrackingSpan(Span.FromBounds(blockSpan.End, nextBlockEnd), SpanTrackingMode.EdgeExclusive);
                            nextBlock.StartState = block.EndState;
                            this.trackedBlocks.Insert(index, nextBlock);
                            break;
                        }
                        else
                        {
                            if (nextBlockSpan.Start == blockSpan.End && nextBlock.StartState.Equals(block.EndState))
                            {
                                return;
                            }
                            else
                            {
                                nextBlock.Block = span.Snapshot.CreateTrackingSpan(Span.FromBounds(blockSpan.End, nextBlockSpan.End), SpanTrackingMode.EdgeExclusive);
                                nextBlock.StartState = block.EndState;
                                break;
                            }
                        }
                    }
                }
                else if (blockSpan.End < span.End.Position)
                {
                    int nextBlockEnd = Math.Min(blockSpan.End + BlockSize, span.Snapshot.Length);
                    nextBlock = new TrackedBlock();
                    nextBlock.Block = span.Snapshot.CreateTrackingSpan(Span.FromBounds(blockSpan.End, nextBlockEnd), SpanTrackingMode.EdgeExclusive);
                    nextBlock.StartState = block.EndState;
                    this.trackedBlocks.Add(nextBlock);
                }
                block = nextBlock;
                invalidate = true;
            }
        }

        private void InvalidateBlockEdge(SnapshotSpan span, TrackedBlock block)
        {
            Span blockSpan = block.Block.GetSpan(span.Snapshot);
            if (span.Contains(blockSpan)) return;
            int startIndex = -1;
            int endIndex = -1;
            for (int i = 0; i < block.CachedClassifications.Count; i++)
            {
                Span classificationSpan = block.CachedClassifications[i].Span.Span;
                if (classificationSpan.Contains(span.Start.Position))
                {
                    startIndex = i;
                }
                if (classificationSpan.Contains(span.End.Position))
                {
                    endIndex = i;
                    break;
                }
            }
            if (startIndex >= 0)
            {
                Span classificationSpan = block.CachedClassifications[startIndex].Span.Span;
                if (classificationSpan.Start < span.Start.Position)
                {
                    this.Invalidate(this.CreateSnapshotSpan(span, classificationSpan.Start, span.Start.Position));
                }
            }
            if (span.End.Position > blockSpan.Start && span.End.Position < blockSpan.End)
            {
                this.Invalidate(this.CreateSnapshotSpan(span, span.End.Position, blockSpan.End));
            }
        }

        private void InvalidateBlock(SnapshotSpan span, TrackedBlock block)
        {
            Span blockSpan = block.Block.GetSpan(span.Snapshot);
            if (span.Contains(blockSpan)) return;
            if (span.Start.Position > blockSpan.Start && span.Start.Position < blockSpan.End)
            {
                this.Invalidate(this.CreateSnapshotSpan(span, blockSpan.Start, span.Start.Position));
            }
            if (span.End.Position > blockSpan.Start && span.End.Position < blockSpan.End)
            {
                this.Invalidate(this.CreateSnapshotSpan(span, span.End.Position, blockSpan.End));
            }
            if (span.Start.Position >= blockSpan.End || span.End.Position <= blockSpan.Start)
            {
                this.Invalidate(this.CreateSnapshotSpan(span, blockSpan.Start, blockSpan.End));
            }
        }

        private void CacheBlock(SnapshotSpan span, TrackedBlock block)
        {
            if (block.CachedClassifications.Count == 0)
            {
                this.LexBlock(span, block, true);
            }
        }

        private void LexBlock(SnapshotSpan span, TrackedBlock block, bool cache)
        {
            this.InvalidateBlockEdge(span, block);
            block.ClearCache();
            block.Version = span.Snapshot.Version;

            Span textSpan = block.Block.GetSpan(span.Snapshot);
            string text = span.Snapshot.GetText(textSpan);
            this.lexer.Reset();
            this.lexer.SetInputStream(new AntlrInputStream(text));
            if (block.StartState == null)
            {
                block.StartState = this.SaveLexerState();
            }
            else
            {
                block.StartState.Restore(this.lexer);
            }

            IToken token = null;
            int tokenType = -1;
            int startPosition = textSpan.Start;
            int endPosition = startPosition;
            int blockEnd = startPosition + BlockSize;
            do
            {
                LexerState state = this.SaveLexerState();
                token = lexer.NextToken();

                if (lexer._hitEOF)
                {
                    tokenType = -1;
                    endPosition = textSpan.End;
                }
                else if(token != null)
                {
                    tokenType = token.Type;
                    endPosition += token.StopIndex - token.StartIndex + 1;
                }
                if (token == null || tokenType < 0)
                {
                    int textLength = endPosition - startPosition;
                    int delta = 0;
                    tokenType = -1;
                    while (tokenType < 0 && startPosition + textLength < span.Snapshot.Length)
                    {
                        delta += 1024;
                        textLength += Math.Min(span.Snapshot.Length - startPosition - textLength, delta);
                        string currentText = span.Snapshot.GetText(startPosition, textLength);
                        textLength = currentText.Length;

                        this.lexer.Reset();
                        this.lexer.SetInputStream(new AntlrInputStream(currentText));
                        state.Restore(this.lexer);

                        token = lexer.NextToken();

                        if (lexer._hitEOF)
                        {
                            endPosition = startPosition + textLength;
                        }
                        else if (token != null)
                        {
                            tokenType = token.Type;
                            endPosition = startPosition + token.StopIndex - token.StartIndex + 1;
                        }
                        else
                        {
                            endPosition = startPosition + textLength;
                        }
                    }
                }

                if (cache)
                {
                    var classification = this.GetClassificationType(tokenType, this.lexer._mode);
                    var tokenSpan = this.CreateSnapshotSpan(span, startPosition, endPosition);
                    var classificationSpan = new ClassificationSpan(tokenSpan, classification);
                    block.CacheClassification(classificationSpan);
                }

                startPosition = endPosition;
            }
            while (token != null && startPosition < textSpan.End && startPosition < blockEnd);

            Span blockSpan = Span.FromBounds(textSpan.Start, endPosition);
            block.Block = span.Snapshot.CreateTrackingSpan(blockSpan, textSpan.Start == 0 ? SpanTrackingMode.EdgeInclusive : SpanTrackingMode.EdgePositive);
            block.EndState = this.SaveLexerState();
            this.InvalidateBlockEdge(span, block);
        }

        private SnapshotSpan CreateSnapshotSpan(SnapshotSpan span, int startPosition, int endPosition)
        {
            if (startPosition < 0) startPosition = 0;
            if (endPosition > span.Snapshot.Length) endPosition = span.Snapshot.Length;
            if (startPosition < endPosition)
            {
                return new SnapshotSpan(span.Snapshot, Span.FromBounds(startPosition, endPosition));
            }
            else
            {
                return new SnapshotSpan(span.Snapshot, Span.FromBounds(startPosition, startPosition));
            }
        }

        private int FindBlockIndex(SnapshotSpan span, int position, bool inside)
        {
            int firstIndex = 0;
            int lastIndex = this.trackedBlocks.Count - 1;
            while (firstIndex <= lastIndex)
            {
                int currentIndex = (firstIndex + lastIndex) / 2;
                SnapshotSpan trackedBlockSpan = this.trackedBlocks[currentIndex].Block.GetSpan(span.Snapshot);
                if (trackedBlockSpan.Contains(position))
                {
                    return currentIndex;
                }
                else if (position < trackedBlockSpan.Start)
                {
                    lastIndex = currentIndex - 1;
                }
                else if (position >= trackedBlockSpan.End)
                {
                    firstIndex = currentIndex + 1;
                }
            }
            if (inside) return -1;
            else return firstIndex;
        }

        private ValueTuple<int,int> FindBlockRange(SnapshotSpan span, Span range)
        {
            ValueTuple<int, int> result = new ValueTuple<int, int>();
            int firstIndex = this.FindBlockIndex(span, range.Start, false);
            result.Item1 = firstIndex;
            int lastIndex = this.trackedBlocks.Count - 1;
            int position = range.End;
            while (firstIndex <= lastIndex)
            {
                int currentIndex = (firstIndex + lastIndex) / 2;
                SnapshotSpan trackedBlockSpan = this.trackedBlocks[currentIndex].Block.GetSpan(span.Snapshot);
                if (trackedBlockSpan.Contains(position))
                {
                    result.Item2 = currentIndex;
                    return result;
                }
                else if (position < trackedBlockSpan.Start)
                {
                    lastIndex = currentIndex - 1;
                }
                else if (position >= trackedBlockSpan.End)
                {
                    firstIndex = currentIndex + 1;
                }
            }
            if (firstIndex >= this.trackedBlocks.Count)
            {
                firstIndex = this.trackedBlocks.Count - 1;
            }
            result.Item2 = firstIndex;
            return result;
        }
    }
}


text:
uint8_t md_inventory_handle_system_event(struct md_writer_sqlite *mws,
                                         md_system_event_t *mse)
{
    sqlite3_stmt *stmt = mws->insert_system;
    sqlite3_clear_bindings(stmt);
    sqlite3_reset(stmt);

    if (sqlite3_bind_int(stmt, 1, mws->node_id) ||
        sqlite3_bind_int(stmt, 2, mws->session_id) ||          // BootCount
        sqlite3_bind_int(stmt, 3, mws->session_id_multip) ||   // BootMultiplier
        sqlite3_bind_int(stmt, 4, mse->tstamp) ||
        sqlite3_bind_int(stmt, 5, mse->sequence) ||
        sqlite3_bind_text(stmt, 6, mse->imei, strlen(mse->imei),
                          SQLITE_STATIC)) {
        META_PRINT_SYSLOG(mws->parent, LOG_ERR, "Failed to bind values to "
                          "INSERT query (system)\n");
        return RETVAL_FAILURE;
    }

    if (sqlite3_step(stmt) != SQLITE_DONE) {
        return RETVAL_FAILURE;
    } else {
        return RETVAL_SUCCESS;
    }
}

static uint8_t md_inventory_system_dump_db_json(struct md_writer_sqlite *mws,
        FILE *output)
{
    const char *json_str;
    sqlite3_reset(mws->dump_system);

    json_object *jarray = json_object_new_array();

    if (md_json_helpers_dump_write(mws->dump_system, jarray))
    {
        json_object_put(jarray);
        return RETVAL_FAILURE;
    }

    json_str = json_object_to_json_string_ext(jarray, JSON_C_TO_STRING_PLAIN);
    fprintf(output, "%s", json_str);

    json_object_put(jarray);
    return RETVAL_SUCCESS;
}

static uint8_t md_inventory_system_delete_db(struct md_writer_sqlite *mws)
{
    int32_t retval;

    sqlite3_reset(mws->delete_system);
    retval = sqlite3_step(mws->delete_system);

    if (retval != SQLITE_DONE) {
        META_PRINT_SYSLOG(mws->parent, LOG_ERR, "Failed to delete system %s\n",
                sqlite3_errstr(retval));
        return RETVAL_FAILURE;
    }

    return RETVAL_SUCCESS;
}

uint8_t md_inventory_system_copy_db(struct md_writer_sqlite *mws)
{
    uint8_t retval = RETVAL_SUCCESS;

    retval = md_writer_helpers_copy_db(mws->system_prefix,
            mws->system_prefix_len, md_inventory_system_dump_db_json, mws,
            md_inventory_system_delete_db);

    if (retval == RETVAL_SUCCESS)
        mws->num_system_events = 0;

    return retval;
}


text:
ACCEPTED

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

#### Published in
Monsunia 1: 28 (1900)

#### Original name
Nymanomyces aceris-laurini Henn., 1899

### Remarks
null


text:
package swarm

import (
	"fmt"
	"sync"
	"time"

	metrics "github.com/ipfs/go-ipfs/metrics"
	inet "github.com/ipfs/go-ipfs/p2p/net"
	filter "github.com/ipfs/go-ipfs/p2p/net/filter"
	addrutil "github.com/ipfs/go-ipfs/p2p/net/swarm/addr"
	peer "github.com/ipfs/go-ipfs/p2p/peer"
	eventlog "github.com/ipfs/go-ipfs/thirdparty/eventlog"

	ma "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-multiaddr"
	ps "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-peerstream"
	pst "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-peerstream/transport"
	psy "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/go-peerstream/transport/yamux"
	"github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess"
	goprocessctx "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/jbenet/goprocess/context"
	prom "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/prometheus/client_golang/prometheus"
	mafilter "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/whyrusleeping/multiaddr-filter"
	context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context"
)

var log = eventlog.Logger("swarm2")

var PSTransport pst.Transport

var peersTotal = prom.NewGaugeVec(prom.GaugeOpts{
	Namespace: "ipfs",
	Subsystem: "p2p",
	Name:      "peers_total",
	Help:      "Number of connected peers",
}, []string{"peer_id"})

func init() {
	tpt := *psy.DefaultTransport
	tpt.MaxStreamWindowSize = 512 * 1024
	PSTransport = &tpt
}

// Swarm is a connection muxer, allowing connections to other peers to
// be opened and closed, while still using the same Chan for all
// communication. The Chan sends/receives Messages, which note the
// destination or source Peer.
//
// Uses peerstream.Swarm
type Swarm struct {
	swarm *ps.Swarm
	local peer.ID
	peers peer.Peerstore
	connh ConnHandler

	dsync dialsync
	backf dialbackoff
	dialT time.Duration // mainly for tests

	notifmu sync.RWMutex
	notifs  map[inet.Notifiee]ps.Notifiee

	// filters for addresses that shouldnt be dialed
	Filters *filter.Filters

	proc goprocess.Process
	ctx  context.Context
	bwc  metrics.Reporter
}

// NewSwarm constructs a Swarm, with a Chan.
func NewSwarm(ctx context.Context, listenAddrs []ma.Multiaddr,
	local peer.ID, peers peer.Peerstore, bwc metrics.Reporter) (*Swarm, error) {

	listenAddrs, err := filterAddrs(listenAddrs)
	if err != nil {
		return nil, err
	}

	s := &Swarm{
		swarm:   ps.NewSwarm(PSTransport),
		local:   local,
		peers:   peers,
		ctx:     ctx,
		dialT:   DialTimeout,
		notifs:  make(map[inet.Notifiee]ps.Notifiee),
		bwc:     bwc,
		Filters: filter.NewFilters(),
	}

	// configure Swarm
	s.proc = goprocessctx.WithContextAndTeardown(ctx, s.teardown)
	s.SetConnHandler(nil) // make sure to setup our own conn handler.

	// setup swarm metrics
	prom.MustRegisterOrGet(peersTotal)
	s.Notify((*metricsNotifiee)(s))

	return s, s.listen(listenAddrs)
}

func (s *Swarm) teardown() error {
	return s.swarm.Close()
}

func (s *Swarm) AddAddrFilter(f string) error {
	m, err := mafilter.NewMask(f)
	if err != nil {
		return err
	}

	s.Filters.AddDialFilter(m)
	return nil
}
func filterAddrs(listenAddrs []ma.Multiaddr) ([]ma.Multiaddr, error) {
	if len(listenAddrs) > 0 {
		filtered := addrutil.FilterUsableAddrs(listenAddrs)
		if len(filtered) < 1 {
			return nil, fmt.Errorf("swarm cannot use any addr in: %s", listenAddrs)
		}
		listenAddrs = filtered
	}
	return listenAddrs, nil
}

func (s *Swarm) Listen(addrs ...ma.Multiaddr) error {
	addrs, err := filterAddrs(addrs)
	if err != nil {
		return err
	}

	return s.listen(addrs)
}

// Process returns the Process of the swarm
func (s *Swarm) Process() goprocess.Process {
	return s.proc
}

// Context returns the context of the swarm
func (s *Swarm) Context() context.Context {
	return s.ctx
}

// Close stops the Swarm.
func (s *Swarm) Close() error {
	return s.proc.Close()
}

// StreamSwarm returns the underlying peerstream.Swarm
func (s *Swarm) StreamSwarm() *ps.Swarm {
	return s.swarm
}

// SetConnHandler assigns the handler for new connections.
// See peerstream. You will rarely use this. See SetStreamHandler
func (s *Swarm) SetConnHandler(handler ConnHandler) {

	// handler is nil if user wants to clear the old handler.
	if handler == nil {
		s.swarm.SetConnHandler(func(psconn *ps.Conn) {
			s.connHandler(psconn)
		})
		return
	}

	s.swarm.SetConnHandler(func(psconn *ps.Conn) {
		// sc is nil if closed in our handler.
		if sc := s.connHandler(psconn); sc != nil {
			// call the user's handler. in a goroutine for sync safety.
			go handler(sc)
		}
	})
}

// SetStreamHandler assigns the handler for new streams.
// See peerstream.
func (s *Swarm) SetStreamHandler(handler inet.StreamHandler) {
	s.swarm.SetStreamHandler(func(s *ps.Stream) {
		handler(wrapStream(s))
	})
}

// NewStreamWithPeer creates a new stream on any available connection to p
func (s *Swarm) NewStreamWithPeer(p peer.ID) (*Stream, error) {
	// if we have no connections, try connecting.
	if len(s.ConnectionsToPeer(p)) == 0 {
		log.Debug("Swarm: NewStreamWithPeer no connections. Attempting to connect...")
		if _, err := s.Dial(context.Background(), p); err != nil {
			return nil, err
		}
	}
	log.Debug("Swarm: NewStreamWithPeer...")

	st, err := s.swarm.NewStreamWithGroup(p)
	return wrapStream(st), err
}

// StreamsWithPeer returns all the live Streams to p
func (s *Swarm) StreamsWithPeer(p peer.ID) []*Stream {
	return wrapStreams(ps.StreamsWithGroup(p, s.swarm.Streams()))
}

// ConnectionsToPeer returns all the live connections to p
func (s *Swarm) ConnectionsToPeer(p peer.ID) []*Conn {
	return wrapConns(ps.ConnsWithGroup(p, s.swarm.Conns()))
}

// Connections returns a slice of all connections.
func (s *Swarm) Connections() []*Conn {
	return wrapConns(s.swarm.Conns())
}

// CloseConnection removes a given peer from swarm + closes the connection
func (s *Swarm) CloseConnection(p peer.ID) error {
	conns := s.swarm.ConnsWithGroup(p) // boom.
	for _, c := range conns {
		c.Close()
	}
	return nil
}

// Peers returns a copy of the set of peers swarm is connected to.
func (s *Swarm) Peers() []peer.ID {
	conns := s.Connections()

	seen := make(map[peer.ID]struct{})
	peers := make([]peer.ID, 0, len(conns))
	for _, c := range conns {
		p := c.RemotePeer()
		if _, found := seen[p]; found {
			continue
		}

		seen[p] = struct{}{}
		peers = append(peers, p)
	}
	return peers
}

// LocalPeer returns the local peer swarm is associated to.
func (s *Swarm) LocalPeer() peer.ID {
	return s.local
}

// notifyAll sends a signal to all Notifiees
func (s *Swarm) notifyAll(notify func(inet.Notifiee)) {
	s.notifmu.RLock()
	for f := range s.notifs {
		go notify(f)
	}
	s.notifmu.RUnlock()
}

// Notify signs up Notifiee to receive signals when events happen
func (s *Swarm) Notify(f inet.Notifiee) {
	// wrap with our notifiee, to translate function calls
	n := &ps2netNotifee{net: (*Network)(s), not: f}

	s.notifmu.Lock()
	s.notifs[f] = n
	s.notifmu.Unlock()

	// register for notifications in the peer swarm.
	s.swarm.Notify(n)
}

// StopNotify unregisters Notifiee fromr receiving signals
func (s *Swarm) StopNotify(f inet.Notifiee) {
	s.notifmu.Lock()
	n, found := s.notifs[f]
	if found {
		delete(s.notifs, f)
	}
	s.notifmu.Unlock()

	if found {
		s.swarm.StopNotify(n)
	}
}

type ps2netNotifee struct {
	net *Network
	not inet.Notifiee
}

func (n *ps2netNotifee) Connected(c *ps.Conn) {
	n.not.Connected(n.net, inet.Conn((*Conn)(c)))
}

func (n *ps2netNotifee) Disconnected(c *ps.Conn) {
	n.not.Disconnected(n.net, inet.Conn((*Conn)(c)))
}

func (n *ps2netNotifee) OpenedStream(s *ps.Stream) {
	n.not.OpenedStream(n.net, inet.Stream((*Stream)(s)))
}

func (n *ps2netNotifee) ClosedStream(s *ps.Stream) {
	n.not.ClosedStream(n.net, inet.Stream((*Stream)(s)))
}

type metricsNotifiee Swarm

func (nn *metricsNotifiee) Connected(n inet.Network, v inet.Conn) {
	peersTotalGauge(n.LocalPeer()).Set(float64(len(n.Conns())))
}

func (nn *metricsNotifiee) Disconnected(n inet.Network, v inet.Conn) {
	peersTotalGauge(n.LocalPeer()).Set(float64(len(n.Conns())))
}

func (nn *metricsNotifiee) OpenedStream(n inet.Network, v inet.Stream) {}
func (nn *metricsNotifiee) ClosedStream(n inet.Network, v inet.Stream) {}
func (nn *metricsNotifiee) Listen(n inet.Network, a ma.Multiaddr)      {}
func (nn *metricsNotifiee) ListenClose(n inet.Network, a ma.Multiaddr) {}

func peersTotalGauge(id peer.ID) prom.Gauge {
	return peersTotal.With(prom.Labels{"peer_id": id.Pretty()})
}


text:
module.exports = {
  "plugins": {
    // to edit target browsers: use "browserslist" field in package.json
    "postcss-import": {},
    "autoprefixer": {}
  }
}


text:
"use strict";

import debug from 'debug';

exports.log = debug('emma:log');
exports.error = debug('emma:error');


text:
module Byebug
  #
  # Reopens the +info+ command to define the +args+ subcommand
  #
  class InfoCommand < Command
    #
    # Information about arguments of the current method/block
    #
    class ProgramCommand < Command
      self.allow_in_post_mortem = true

      def self.regexp
        /^\s* p(?:rogram)? \s*$/x
      end

      def self.description
        <<-DESCRIPTION
          inf[o] p[rogram]

          #{short_description}
        DESCRIPTION
      end

      def self.short_description
        "Information about the current status of the debugged program."
      end

      def execute
        puts "Program stopped. "
        format_stop_reason context.stop_reason
      end

      private

      def format_stop_reason(stop_reason)
        case stop_reason
        when :step
          puts "It stopped after stepping, next'ing or initial start."
        when :breakpoint
          puts "It stopped at a breakpoint."
        when :catchpoint
          puts "It stopped at a catchpoint."
        end
      end
    end
  end
end


text:
<resources>
    <string name="app_name">The Advanced Page Indicator</string>
</resources>


text:
{% extends 'base.html' %}
{% load i18n %}
{% block title %}{% trans "Data Source Table Details" %}{% endblock %}

{% block page_header %}
   {% include "horizon/common/_page_header.html" with title=_("Data Source Table Details: ")|add:table_name %}
{% endblock page_header %}

{% block main %}
  {% include "admin/datasources/_detail_overview.html" %}
  <div id="datasource_table_rows">
    {{ datasource_rows_table.render }}
  </div>
{% endblock %}


text:
// ==========================================================================
//                 SeqAn - The Library for Sequence Analysis
// ==========================================================================
// Copyright (c) 2006-2010, Knut Reinert, FU Berlin
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of Knut Reinert or the FU Berlin nor the names of
//       its contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ==========================================================================

#ifndef SEQAN_HEADER_FIND_MOTIF_BASE_H
#define SEQAN_HEADER_FIND_MOTIF_BASE_H

namespace SEQAN_NAMESPACE_MAIN
{

///////////////////////////////////////////////////////////////////////////////////////////////////

/**
.Class.MotifFinder:
..cat:Motif Search
..summary:Holds the algorithm parameter values and the motif instance(s) found by the appropriate
          motif discovery algorithm.
..cat:Motif Search
..signature:MotifFinder<TValue, TSpec, TRng>
..param.TValue:The type of sequences to be analyzed.
...metafunction:Metafunction.Value
...type:Spec.Dna
...type:Spec.AminoAcid
..param.TSpec:The motif finding algorithm to search with.
...type:Spec.Projection
...type:Spec.EPatternBranching
...type:Spec.Pms1
...type:Spec.Pmsp
..param.TRng:The @Class.Rng@ specialization to use for random number generation.
...default:$GetDefaultRng<MotifFinderClass>::Type$
..include:seqan/find_motif.h
*/

struct MotifFinderClass_;
typedef Tag<MotifFinderClass_> MotifFinderClass;

template <typename TValue, typename TSpec, typename TRng = typename GetDefaultRng<MotifFinderClass>::Type>
class MotifFinder;

//////////////////////////////////////////////////////////////////////////////
//Metafunctions
//////////////////////////////////////////////////////////////////////////////

///.Metafunction.Value.param.T.type:Class.MotifFinder
///.Metafunction.Value.class:Class.MotifFinder

template<typename TValue, typename TSpec, typename TRng>
struct Value< MotifFinder<TValue, TSpec, TRng> >
{
	typedef TValue Type;
};
template<typename TValue, typename TSpec, typename TRng>
struct Value< MotifFinder<TValue, TSpec, TRng> const>
{
	typedef TValue const Type;
};

//////////////////////////////////////////////////////////////////////////////
// Functions
//////////////////////////////////////////////////////////////////////////////

/**
.Function.findMotif
..class:Class.MotifFinder
..summary:Represents the main function which is used to start the search for noticeable motif patterns.
..cat:Motif Search
..signature:findMotif(finder,dataset,seq_model)
..param.finder:The @Class.MotifFinder@ object.
...type:Class.MotifFinder
..param.dataset:The dataset object representing the input sequences.
...type:Class.StringSet
..param.seq_model:The seq_model object.
...type:Tag.Oops
...type:Tag.Omops
...type:Tag.Zoops
...type:Tag.Tcm
...remarks:The sequence models rely on different assumptions about the distribution of motif occurrences
           across the sample sequences.
..remarks:The PROJECTION algorithm is able to run in @Tag.Oops@, @Tag.Zoops@ and @Tag.Tcm@ mode.
..remarks:The ePatternBranching algorithm is able to run in @Tag.Oops@ and @Tag.Omops@ mode.
..remarks:The Pms1 and Pmsp algorithm is able to run in  @Tag.Oops@,  @Tag.Omops@,  @Tag.Zoops@ and
          @Tag.Tcm@ mode.
..include:seqan/find_motif.h
*/

/**
.Function.factorial:
..summary:Calculates the factorial value of any integer number.
..cat:Motif Search
..signature:factorial(value)
..param.value:The value object.
...remarks:$value$ must be a positive integer.
..remarks:The factorial of a non-negative integer $value$ is
          the product of all positive integers less than or equal to $value$.
..include:seqan/find_motif.h
*/

template<typename TType>
TType factorial(TType n)
{
    SEQAN_CHECKPOINT;

	TType result = 0;

	if(n==0)
	{
		result = 1;
	}
	else
	{
		result = n*factorial(n-1);
	}

	return result;
}

//////////////////////////////////////////////////////////////////////////////

/**
.Function.binomialCoefficient:
..summary:Calculates the binomial coefficient C(n,k).
..cat:Motif Search
..signature:binomialCoefficient(n,k)
..param.n:The first parameter object.
...remarks:$n$ must be a positive integer.
..param.k:The second parameter object.
...remarks:$k$ must be a positive integer.
..remarks:The binomial coefficient of $n$ and $k$ is equal to zero
          if $k$ is greater than $n$.
..include:seqan/find_motif.h
*/

template<typename TType>
TType binomialCoefficient(TType n, TType k)
{
    SEQAN_CHECKPOINT;

	//SEQAN_ASSERT(!(n<0) & !(k<0));
	TType result = 1;
	for(TType i=(n-k+1); i<=n; ++i)
	{
		result*=i;
	}
	result = result/factorial(k);

	return result;
}

//////////////////////////////////////////////////////////////////////////////

/**
.Function.hammingDistance:
..summary:Determines the Hamming distance between two sequences.
..cat:Motif Search
..signature:hammingDistance<TType>(begin1,end1,begin2)
..param.TType:Distance type.
..param.begin1:An iterator pointing to the beginning of the first sequence which is either
              a @Shortcut.DnaString@ or a @Shortcut.Peptide@.
...type:Concept.RandomAccessIteratorConcept
...type:Shortcut.DnaIterator
...type:Shortcut.PeptideIterator
..param.end1:An iterator pointing to the end of the first sequence which is either
            a @Shortcut.DnaString@ or a @Shortcut.Peptide@.
...type:Concept.RandomAccessIteratorConcept
...type:Shortcut.DnaIterator
...type:Shortcut.PeptideIterator
..param.begin2:An iterator pointing to the beginning of the second sequence which is either
              a @Shortcut.DnaString@ or a @Shortcut.Peptide@.
...type:Concept.RandomAccessIteratorConcept
...type:Shortcut.DnaIterator
...type:Shortcut.PeptideIterator
..include:seqan/find_motif.h
*/

template<typename TType, typename TStringIterator>
TType hammingDistance(TStringIterator start1, TStringIterator end1, TStringIterator start2)
{
    SEQAN_CHECKPOINT;

	TType num_of_mismatches = 0;
	while(start1!=end1)
	{
		if(*start1!=*start2)
		{
			++num_of_mismatches;
		}
		++start1;
		++start2;
	}

	return num_of_mismatches;
}

//////////////////////////////////////////////////////////////////////////////

/**
.Function.inverseHash:
..summary:Determines the corresponding sequence pattern given the hash value.
..cat:Motif Search
..signature:inverseHash<TValue>(hash_value,alphabet_size,seq_size)
..param.hash_value:The hash_value object.
..param.alphabet_size:The alphabet_size object.
...remarks:$alphabet_size$ is four for nucleotide sequences and twenty for amino acid sequences.
..param.seq_size:The seq_size object representing the size of the corresponding sequence.
..include:seqan/find_motif.h
*/

template<typename TValue, typename TType>
String<TValue>
inverseHash(TType const & hash_value,
			typename Size<TValue>::Type const & alp_size,
			typename Size< String<TValue> >::Type const & seq_size)
{
    SEQAN_CHECKPOINT;

	typedef String<TValue> TString;
	TString seq;
	resize(seq, seq_size);

	TType hash_val = hash_value;
	typedef typename Position<TString>::Type TPos;
	for(TPos i=0; i<seq_size; ++i)
	{
		int letter = hash_val%alp_size;
		seq[i] = (TValue)letter;
		hash_val = (hash_val-letter)/alp_size;
	}

	std::reverse(begin(seq), end(seq));
	return seq;
}

//////////////////////////////////////////////////////////////////////////////

/**
.Function.displayResult:
..class:Class.MotifFinder
..summary:Displays all found motif candidates. In the case of the Projection Motif Finder
          the function displays the consensus pattern of the found motif candidate.
..cat:Motif Search
..signature:displayResult(motif_finder)
..param.motif_finder:The @Class.MotifFinder@ object.
...type:Class.MotifFinder
..include:seqan/find_motif.h
*/

template<typename TValue, typename TAlgorithm, typename TRng>
void
displayResult(MotifFinder<TValue, TAlgorithm, TRng> & finder)
{
    SEQAN_CHECKPOINT;

	typedef String<TValue> TString;
	typedef String<TString> TStrings;

	if(length(finder.set_of_motifs)!=0)
	{
		unsigned int counter = 0;
		typename Iterator<TStrings>::Type iter = begin(finder.set_of_motifs);
		for(; !atEnd(iter, finder.set_of_motifs); goNext(iter))
		{
			std::cout << "[" << counter << "]: " << *iter << "\n";
			++counter;
		}
		std::cout << "\n";
	}
	else
	{
		std::cout << "NO MOTIF HAS BEEN FOUND!!!\n";
	}
}

/////////////////////////////////////////////////////////////////////////
/**
.Metafunction.Motif:
..cat:Motif Search
..summary:The string type of the finder.
..signature:Motif<T>::Type
..param.T:Finder for which the string type is determined.
...type:Class.String
..returns.param.Type:Underlying sequence type of finder $T$.
..include:seqan/find_motif.h
 */
template <typename T>
struct Motif;

template <typename TValue, typename TSpec, typename TRng>
struct Motif< MotifFinder<TValue, TSpec, TRng> >
{
	typedef String<TValue> Type;
};

/////////////////////////////////////////////////////////////////////////
/**
.Function.getMotif:
..class:Class.MotifFinder
..summary:Gets the motif out of a @Class.MotifFinder@.  If pos is given, the pos-th motif is returned, otherwise the first motif is returned.
..cat:Motif Search
..signature:getMotif(motifFinder, pos)
..param.motifFinder:
...type:Class.MotifFinder
..param.pos:Position
..include:seqan/find_motif.h
*/

template <typename TValue, typename TSpec, typename TPosition, typename TRng>
inline typename Motif<MotifFinder<TValue, TSpec, TRng> >::Type &
getMotif(MotifFinder<TValue, TSpec, TRng> & me,
		 TPosition pos)
{
    SEQAN_CHECKPOINT;
	return me.set_of_motifs[pos];
}

///.Function.getMotif.signature:getMotif(motifFinder)
template <typename TValue, typename TSpec, typename TRng>
inline typename Motif<MotifFinder<TValue, TSpec, TRng> >::Type &
getMotif(MotifFinder<TValue, TSpec, TRng> & me)
{
    SEQAN_CHECKPOINT;
	return me.set_of_motifs[0];
}

/////////////////////////////////////////////////////////////////////////
/**
.Function.motifCount:
..class:Class.MotifFinder
..summary:Gets number of motifs in the @Class.MotifFinder@.
..cat:Motif Search
..signature:motifCount(motifFinder)
..param.motifFinder:
...type:Class.MotifFinder
..include:seqan/find_motif.h
*/

template <typename TValue, typename TSpec, typename TRng>
inline size_t
motifCount(MotifFinder<TValue, TSpec, TRng> const & me)
{
    SEQAN_CHECKPOINT;
	return length(me.set_of_motifs);
}

/////////////////////////////////////////////////////////////////////////

}// namespace SEQAN_NAMESPACE_MAIN

#endif //#ifndef SEQAN_HEADER_...


text:
#include "tensorflow/cc/framework/cc_op_gen.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/op_def.pb.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/platform/init_main.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {
namespace {

void PrintAllCCOps(const std::string& dot_h, const std::string& dot_cc,
                   const std::string& overrides_fnames, bool include_internal) {
  OpList ops;
  OpRegistry::Global()->Export(include_internal, &ops);
  WriteCCOps(ops, dot_h, dot_cc, overrides_fnames);
}

}  // namespace
}  // namespace tensorflow

int main(int argc, char* argv[]) {
  tensorflow::port::InitMain(argv[0], &argc, &argv);
  if (argc != 5) {
    for (int i = 1; i < argc; ++i) {
      fprintf(stderr, "Arg %d = %s\n", i, argv[i]);
    }
    fprintf(stderr,
            "Usage: %s out.h out.cc overrides1.pbtxt,2.pbtxt include_internal\n"
            "  include_internal: 1 means include internal ops\n",
            argv[0]);
    exit(1);
  }

  bool include_internal = tensorflow::StringPiece("1") == argv[4];
  tensorflow::PrintAllCCOps(argv[1], argv[2], argv[3], include_internal);
  return 0;
}


text:
namespace EntityFramework.Repository.Tests.DatabaseFirst
{
    public partial class TestDbEntities : ITestDbContext
    {
    }
}


text:
BestBoy.setup do |config|
  # Define base Controller (default ApplicationController)
  #config.base_controller = "ApplicationController"

  # Define before_filter for using before_filters (default = nil)
  #config.before_filter = nil

  # Define skip_before_filter for skipping before_filters (default = nil)
  #config.skip_before_filter = nil

  # Define skip_after_filter for skipping after_filters (default = nil)
  #config.skip_after_filter = nil

  # Define custom redirect path as string p.e. "/admin" (default = nil)
  #config.custom_redirect = nil
end


text:
package org.springframework.boot.autoconfigure.web.reactive.error;

import javax.validation.Valid;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import reactor.core.publisher.Mono;

import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration;
import org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration;
import org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration;
import org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration;
import org.springframework.boot.test.context.assertj.AssertableReactiveWebApplicationContext;
import org.springframework.boot.test.context.runner.ReactiveWebApplicationContextRunner;
import org.springframework.boot.test.extension.OutputCapture;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;

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

/**
 * Integration tests for {@link DefaultErrorWebExceptionHandler}
 *
 * @author Brian Clozel
 */
public class DefaultErrorWebExceptionHandlerIntegrationTests {

	private final LogIdFilter logIdFilter = new LogIdFilter();

	@RegisterExtension
	public OutputCapture output = new OutputCapture();

	private ReactiveWebApplicationContextRunner contextRunner = new ReactiveWebApplicationContextRunner()
			.withConfiguration(AutoConfigurations.of(
					ReactiveWebServerFactoryAutoConfiguration.class,
					HttpHandlerAutoConfiguration.class, WebFluxAutoConfiguration.class,
					ErrorWebFluxAutoConfiguration.class,
					PropertyPlaceholderAutoConfiguration.class,
					MustacheAutoConfiguration.class))
			.withPropertyValues("spring.main.web-application-type=reactive",
					"server.port=0")
			.withUserConfiguration(Application.class);

	@Test
	public void jsonError() {
		this.contextRunner.run((context) -> {
			WebTestClient client = getWebClient(context);
			client.get().uri("/").exchange().expectStatus()
					.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody()
					.jsonPath("status").isEqualTo("500").jsonPath("error")
					.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
					.jsonPath("path").isEqualTo(("/")).jsonPath("message")
					.isEqualTo("Expected!").jsonPath("exception").doesNotExist()
					.jsonPath("trace").doesNotExist().jsonPath("requestId")
					.isEqualTo(this.logIdFilter.getLogId());
			assertThat(this.output).contains("500 Server Error for HTTP GET \"/\"")
					.contains("java.lang.IllegalStateException: Expected!");
		});
	}

	@Test
	public void notFound() {
		this.contextRunner.run((context) -> {
			WebTestClient client = getWebClient(context);
			client.get().uri("/notFound").exchange().expectStatus().isNotFound()
					.expectBody().jsonPath("status").isEqualTo("404").jsonPath("error")
					.isEqualTo(HttpStatus.NOT_FOUND.getReasonPhrase()).jsonPath("path")
					.isEqualTo(("/notFound")).jsonPath("exception").doesNotExist()
					.jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId());
		});
	}

	@Test
	public void htmlError() {
		this.contextRunner.run((context) -> {
			WebTestClient client = getWebClient(context);
			String body = client.get().uri("/").accept(MediaType.TEXT_HTML).exchange()
					.expectStatus().isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR)
					.expectHeader().contentType(MediaType.TEXT_HTML)
					.expectBody(String.class).returnResult().getResponseBody();
			assertThat(body).contains("status: 500").contains("message: Expected!");
		});
	}

	@Test
	public void bindingResultError() {
		this.contextRunner.run((context) -> {
			WebTestClient client = getWebClient(context);
			client.post().uri("/bind").contentType(MediaType.APPLICATION_JSON)
					.syncBody("{}").exchange().expectStatus().isBadRequest().expectBody()
					.jsonPath("status").isEqualTo("400").jsonPath("error")
					.isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase()).jsonPath("path")
					.isEqualTo(("/bind")).jsonPath("exception").doesNotExist()
					.jsonPath("errors").isArray().jsonPath("message").isNotEmpty()
					.jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId());
		});
	}

	@Test
	public void includeStackTraceOnParam() {
		this.contextRunner
				.withPropertyValues("server.error.include-exception=true",
						"server.error.include-stacktrace=on-trace-param")
				.run((context) -> {
					WebTestClient client = getWebClient(context);
					client.get().uri("/?trace=true").exchange().expectStatus()
							.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody()
							.jsonPath("status").isEqualTo("500").jsonPath("error")
							.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
							.jsonPath("exception")
							.isEqualTo(IllegalStateException.class.getName())
							.jsonPath("trace").exists().jsonPath("requestId")
							.isEqualTo(this.logIdFilter.getLogId());
				});
	}

	@Test
	public void alwaysIncludeStackTrace() {
		this.contextRunner.withPropertyValues("server.error.include-exception=true",
				"server.error.include-stacktrace=always").run((context) -> {
					WebTestClient client = getWebClient(context);
					client.get().uri("/?trace=false").exchange().expectStatus()
							.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody()
							.jsonPath("status").isEqualTo("500").jsonPath("error")
							.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
							.jsonPath("exception")
							.isEqualTo(IllegalStateException.class.getName())
							.jsonPath("trace").exists().jsonPath("requestId")
							.isEqualTo(this.logIdFilter.getLogId());
				});
	}

	@Test
	public void neverIncludeStackTrace() {
		this.contextRunner.withPropertyValues("server.error.include-exception=true",
				"server.error.include-stacktrace=never").run((context) -> {
					WebTestClient client = getWebClient(context);
					client.get().uri("/?trace=true").exchange().expectStatus()
							.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectBody()
							.jsonPath("status").isEqualTo("500").jsonPath("error")
							.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase())
							.jsonPath("exception")
							.isEqualTo(IllegalStateException.class.getName())
							.jsonPath("trace").doesNotExist().jsonPath("requestId")
							.isEqualTo(this.logIdFilter.getLogId());
				});
	}

	@Test
	public void statusException() {
		this.contextRunner.withPropertyValues("server.error.include-exception=true")
				.run((context) -> {
					WebTestClient client = getWebClient(context);
					client.get().uri("/badRequest").exchange().expectStatus()
							.isBadRequest().expectBody().jsonPath("status")
							.isEqualTo("400").jsonPath("error")
							.isEqualTo(HttpStatus.BAD_REQUEST.getReasonPhrase())
							.jsonPath("exception")
							.isEqualTo(ResponseStatusException.class.getName())
							.jsonPath("requestId").isEqualTo(this.logIdFilter.getLogId());
				});
	}

	@Test
	public void defaultErrorView() {
		this.contextRunner
				.withPropertyValues("spring.mustache.prefix=classpath:/unknown/",
						"server.error.include-stacktrace=always")
				.run((context) -> {
					WebTestClient client = getWebClient(context);
					String body = client.get().uri("/").accept(MediaType.TEXT_HTML)
							.exchange().expectStatus()
							.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader()
							.contentType(MediaType.TEXT_HTML).expectBody(String.class)
							.returnResult().getResponseBody();
					assertThat(body).contains("Whitelabel Error Page")
							.contains(this.logIdFilter.getLogId())
							.contains("
Expected!
").contains(
									"
java.lang.IllegalStateException");
				});
	}

	@Test
	public void escapeHtmlInDefaultErrorView() {
		this.contextRunner
				.withPropertyValues("spring.mustache.prefix=classpath:/unknown/")
				.run((context) -> {
					WebTestClient client = getWebClient(context);
					String body = client.get().uri("/html").accept(MediaType.TEXT_HTML)
							.exchange().expectStatus()
							.isEqualTo(HttpStatus.INTERNAL_SERVER_ERROR).expectHeader()
							.contentType(MediaType.TEXT_HTML).expectBody(String.class)
							.returnResult().getResponseBody();
					assertThat(body).contains("Whitelabel Error Page")
							.contains(this.logIdFilter.getLogId())
							.doesNotContain("


text:
jQuery.sap.declare("sap.workshop.mailingList.Component");

sap.ui.core.UIComponent.extend("sap.workshop.mailingList.Component", {
	init: function(){
		jQuery.sap.require("sap.m.MessageBox");
		jQuery.sap.require("sap.m.MessageToast");

        var model = new sap.ui.model.json.JSONModel({});
        sap.ui.getCore().setModel(model);
	    var oConfig = new sap.ui.model.json.JSONModel({});
        sap.ui.getCore().setModel(oConfig, "config");

        var oModel = new sap.ui.model.odata.ODataModel("/workshop/admin/services/mailingList.xsodata/", true);
        sap.ui.getCore().setModel(oModel, "mailing");

        this.getSessionInfo();

		sap.ui.core.UIComponent.prototype.init.apply(this, arguments);
	},

	createContent: function() {

		var settings = {
				ID: "App",
				title: "Workshop Mailing List",
				description: "Workshop Mailing List"
			};

		var oView = sap.ui.view({
			id: "App",
			viewName: "view.AppDisplay",
			type: "XML",
			viewData: settings
		});
		 oView.setModel(sap.ui.getCore().getModel("config"), "config");
		 oView.setModel(sap.ui.getCore().getModel());
 		 oView.setModel(sap.ui.getCore().getModel("mailing"), "mailing");
		return oView;
	},

	getSessionInfo: function(){
		var aUrl = '/workshop/admin/services/exercisesMaster.xsjs?cmd=getSessionInfo';
	    this.onLoadSession(
	    		JSON.parse(jQuery.ajax({
	    		       url: aUrl,
	    		       method: 'GET',
	    		       dataType: 'json',
	    		       async: false}).responseText));

	},

	onLoadSession: function(myJSON){
		for( var i = 0; i<myJSON.session.length; i++)
	     {
		   var config =  sap.ui.getCore().getModel("config");
		   config.setProperty("/UserName",myJSON.session[i].UserName);
	     }
	}
});


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Chapter 1. Introduction</title>
    <link rel="stylesheet" href="gettingStarted.css" type="text/css" />
    <meta name="generator" content="DocBook XSL Stylesheets V1.62.4" />
    <link rel="home" href="index.html" title="Getting Started with Replicated Berkeley DB Applications" />
    <link rel="up" href="index.html" title="Getting Started with Replicated Berkeley DB Applications" />
    <link rel="previous" href="preface.html" title="Preface" />
    <link rel="next" href="repadvantage.html" title="Replication Benefits" />

          Chapter 1. Introduction

          Prev

           Next

Chapter 1. Introduction

          Table of Contents

              Overview

                  Replication Environments

                  Replication Databases

                  Communications Layer

                  Selecting a Master

              Replication Benefits

              The Replication APIs

                  Replication Framework Overview

                  Replication API Overview

              Holding Elections

                  Influencing Elections

                  Winning Elections

                  Switching Masters

              Permanent Message Handling

                  When Not to Manage
                            Permanent Messages

                  Managing Permanent Messages

                  Implementing Permanent
                    Message Handling

    This book provides a thorough introduction and discussion on
    replication as used with Berkeley DB (DB). It begins by offering a
    general overview to replication and the benefits it provides. It also
    describes the APIs that you use to implement replication, and it
    describes architecturally the things that you need to do to your
    application code in order to use the replication APIs. Finally, it
    discusses the differences in backup and restore strategies that you
    might pursue when using replication, especially where it comes to log
    file removal.

    You should understand the concepts from the

                Berkeley DB Getting Started with Transaction Processing

     guide before reading this book.

Overview

            The DB replication APIs allow you to distribute your database
            write operations (performed on a read-write master) to one or
            more read-only replicas.
            For this reason, DB's replication implementation is said to be a
            single master, multiple replica replication strategy.

            Note that your database write operations can occur only on the
            master; any attempt to write to a replica results in an error
            being
                returned to

            the DB API used to perform the write.

            A single replication master and all of its replicas are referred
            to as a replication group.  While all
            members of the replication group can reside on the same
            machine, usually each replication participant is placed on a
            separate physical machine somewhere on the network.

            Note that all replication applications must first be
            transactional applications. The data that the master transmits
            its replicas are log records that are generated as records are
            updated. Upon transactional commit, the master transmits a
            transaction record which tells the replicas to commit the
            records they previously received from the master. In order for
            all of this to work, your replicated application must also be a
            transactional application. For this reason, it is
            recommended that you write and debug your DB application as
            a stand-alone transactional application before introducing the
            replication layer to your code.

            Finally, be aware that all machines participating in the
            replication group must share identical
            endianess.  Endianess is the byte-order
            strategy used by the computing platform to store multibyte
            numbers. Berkeley DB is sensitive to byte order and so your
            replication infrastructure must be consistent in this area.
            We expect to remove this requirement in some future
            release of the product.

Replication Environments

                The most important requirement for a replication
                participant is that it must use a unique Berkeley DB database
                environment independent of all other replication
                participants. So while multiple replication participants
                can reside on the same physical machine, no two such participants
                can share the same environment home directory.

                For this reason, technically replication occurs between
                unique database environments. So in the strictest sense,
                a replication group consists of a master
                        environment and
                one or more replica environments. However, the reality
                is that for production code, each such environment will
                usually be located on its own unique machine. Consequently,
                this manual sometimes talks about replication sites, meaning the
                unique combination of environment home directory, host and port that a specific
                replication application is using.

                There is no DB-specified limit to the number of
                environments which can participate in a replication group.
                The only limitation here is one of resources —
                network bandwidth, for example.

                    (Note, however, that the replication framework does place a limit on the
                    number of environments you can use. See
                    Replication Framework Overview
                    for details.)

                Also, DB's replication implementation requires all
                participating environments to be assigned IDs that are
                locally unique to the given environment. Depending on the
                replication APIs that you choose to use, you may or may not
                need to manage this particular detail.

                    For detailed information on database environments, see
                    the Berkeley DB Getting Started with Transaction Processing
                    guide.  For more information on environment IDs, see
                    the Berkeley DB Programmer's Reference Guide.

Replication Databases

                DB's databases are managed and used in exactly the same way
                as if you were writing a non-replicated application, with
                a couple of caveats. First,  the databases maintained in a replicated environment
                must reside either in the <tt class="literal">ENV_HOME</tt>
                directory, or in the directory identified by the
                    <tt class="methodname">DB_ENV->set_data_dir()</tt>

                method. Unlike non-replication applications, you cannot place your
                databases in a subdirectory below these locations. You should
                also not use full path names for your databases or
                environments as these are likely to break as to replicated
                to other machines.

Communications Layer

                In order to transmit database writes to the replication
                replicas, DB requires a communications layer.
                DB is agnostic as to what this layer should
                look like. The only requirement is that it
                be capable of passing two opaque data objects and an
                environment ID from the master to its replicas without
                corruption.

                Because replicas are usually placed on different machines on
                the network, the communications layer is usually some kind
                of a network-aware implementation. Beyond that, its
                implementation details are largely up to you. It could use
                TCP/IP sockets, for example, or it could use
                raw sockets if they perform better for your particular
                application.

                Note that you may not have to write your own communications
                layer. DB provides a replication framework that
                includes a fully-functional TCP/IP-based communications layer.
                See The Replication APIs
                for more information.

                    See the Berkeley DB Programmer's Reference Guide
                    for a description of how to
                write your own custom replication communications layer.

Selecting a Master

                    Every replication group is allowed one and only one
                    master environment. Almost always, masters are selected by
                    holding an election.  All such
                    elections are performed by the underlying Berkeley DB
                    replication code so you have to do very little to
                    implement them.

                    When holding an election, replicas "vote" on who should
                    be the master. Among replicas participating in the
                    election, the one with the most up-to-date set of log
                    records will win the election. Note that it's possible
                    for there to be a tie. When this occurs, priorities are
                    used to select the master. See
                    Holding Elections
                    for details.

                    For more information on holding and managing elections,
                    see Holding Elections.

          Prev

            Up

           Next

          Preface

            Home

           Replication Benefits


text:
#ifndef BOOST_COMPUTE_INTEROP_OPENGL_HPP
#define BOOST_COMPUTE_INTEROP_OPENGL_HPP

/// \file
///
/// Meta-header to include all Boost.Compute OpenGL interop headers.

#include <boost/compute/interop/opengl/acquire.hpp>
#include <boost/compute/interop/opengl/context.hpp>
#include <boost/compute/interop/opengl/opengl_buffer.hpp>
#include <boost/compute/interop/opengl/opengl_renderbuffer.hpp>
#include <boost/compute/interop/opengl/opengl_texture.hpp>

#endif // BOOST_COMPUTE_INTEROP_OPENGL_HPP


text:
import "../node-tests";
import * as util from "util";

//////////////////////////////////////////////////////////
/// Global Tests : https://nodejs.org/api/global.html  ///
//////////////////////////////////////////////////////////
{
    {
        const hrtimeBigint: bigint = process.hrtime.bigint();
    }
}

//////////////////////////////////////////////////////////
/// Util Tests                                         ///
//////////////////////////////////////////////////////////
{
    {
        const value: BigInt64Array | BigUint64Array | number = [] as any;
        if (util.types.isBigInt64Array(value)) {
            // $ExpectType BigInt64Array
            const b = value;
        } else if (util.types.isBigUint64Array(value)) {
            // $ExpectType BigUint64Array
            const b = value;
        } else {
            // $ExpectType number
            const b = value;
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CoffeeParser;

namespace CoffeeParserTest {
	class Program {
		static void Main(string[] args) {

			var t = Parser.Parse("i = 0").ToArray();

			Console.WriteLine("*** DONE ***");

		}
	}
}