text:
require 'spec_helper'

describe SatutempatLocale::Server::PushHandler do
  describe '#perform!' do
    context 'accepted' do
      it 'client update is -1' do
        stub_global_marker 20

        lambda{
          SatutempatLocale::Server::PushHandler.new(-1, "spec/tar/fixtures.tar").perform!
        }.should change { SatutempatLocale::Server::Storage.count }.from(0).to(10)
      end

      it 'client update is more than server\'s' do
        stub_global_marker 10

        lambda{
          SatutempatLocale::Server::PushHandler.new(20, "spec/tar/fixtures.tar").perform!
        }.should change { SatutempatLocale::Server::Storage.count }.from(0).to(10)
      end

      it 'client update is equal with server\'s' do
        stub_global_marker 10

        lambda{
          SatutempatLocale::Server::PushHandler.new(10, "spec/tar/fixtures.tar").perform!
        }.should change { SatutempatLocale::Server::Storage.count }.from(0).to(10)
      end

      it 'create global marker' do
        Time.stub now: Time.at(10)

        lambda{
          SatutempatLocale::Server::PushHandler.new(10, "spec/tar/fixtures.tar").perform!
        }.should change { SatutempatLocale::Server::GlobalMarker.count }.from(0).to(1)
      end

      it 'update global marker but do not create new marker' do
        Time.stub now: Time.at(10)

        SatutempatLocale::Server::PushHandler.new(10, "spec/tar/fixtures.tar").perform!

        lambda{
          SatutempatLocale::Server::PushHandler.new(10, "spec/tar/fixtures.tar").perform!
        }.should_not change { SatutempatLocale::Server::GlobalMarker.count }.from(1).to(2)
      end

      it 'update global marker' do
        Time.stub now: 10
        SatutempatLocale::Server::PushHandler.new(10, "spec/tar/fixtures.tar").perform!
        SatutempatLocale::Server::GlobalMarker.first.last_update.should eql 10

        Time.stub now: 20
        SatutempatLocale::Server::PushHandler.new(10, "spec/tar/fixtures.tar").perform!
        SatutempatLocale::Server::GlobalMarker.first.reload.last_update.should eql 20
      end
    end

    context 'rejected' do
      it 'client update is less than server\'s' do
        stub_global_marker 20

        lambda{
          SatutempatLocale::Server::PushHandler.new(10, "spec/tar/fixtures.tar").perform!
        }.should raise_error PushRejectedError
      end
    end

    context 'data' do
      it 'should not introduce tar path in file_path' do
        Time.stub now: Time.at(10)

        SatutempatLocale::Server::PushHandler.new(10, "spec/tar/fixtures.tar").perform!

        SatutempatLocale::Server::Storage.first.file_path[/\A10/].should be_nil
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
// Type definitions for node-fetch based on whatwg-fetch
// Project: https://github.com/bitinn/node-fetch
// Definitions by: Torsten Werner <https://github.com/torstenwerner>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

declare module _fetch {

	class Request extends Body {
		constructor(input: string | Request, init?: RequestInit);
		method: string;
		url: string;
		headers: Headers;
		context: RequestContext;
		referrer: string;
		mode: RequestMode;
		redirect: RequestRedirect;
		credentials: RequestCredentials;
		cache: RequestCache;
	}

	interface RequestInit {
		method?: string;
		headers?: HeaderInit | { [index: string]: string };
		body?: BodyInit;
		mode?: RequestMode;
		redirect?: RequestRedirect;
		credentials?: RequestCredentials;
		cache?: RequestCache;
	}

	type RequestContext =
		"audio" | "beacon" | "cspreport" | "download" | "embed" |
		"eventsource" | "favicon" | "fetch" | "font" | "form" | "frame" |
		"hyperlink" | "iframe" | "image" | "imageset" | "import" |
		"internal" | "location" | "manifest" | "object" | "ping" | "plugin" |
		"prefetch" | "script" | "serviceworker" | "sharedworker" |
		"subresource" | "style" | "track" | "video" | "worker" |
		"xmlhttprequest" | "xslt";
	type RequestMode = "same-origin" | "no-cors" | "cors";
	type RequestRedirect = "follow" | "error" | "manual";
	type RequestCredentials = "omit" | "same-origin" | "include";
	type RequestCache =
		"default" | "no-store" | "reload" | "no-cache" |
		"force-cache" | "only-if-cached";

	class Headers {
		append(name: string, value: string): void;
		delete(name: string): void;
		get(name: string): string;
		getAll(name: string): Array<string>;
		has(name: string): boolean;
		set(name: string, value: string): void;
		forEach(callback: (value: string, name: string) => void): void;
	}

	class Body {
		bodyUsed: boolean;
		arrayBuffer(): Promise<ArrayBuffer>;
		blob(): Promise<Blob>;
		formData(): Promise<FormData>;
		json(): Promise<any>;
		json<T>(): Promise<T>;
		text(): Promise<string>;
	}
	class Response extends Body {
		constructor(body?: BodyInit, init?: ResponseInit);
		static error(): Response;
		static redirect(url: string, status: number): Response;
		type: ResponseType;
		url: string;
		status: number;
		ok: boolean;
		statusText: string;
		headers: Headers;
		clone(): Response;
	}

	type ResponseType = "basic" | "cors" | "default" | "error" | "opaque" | "opaqueredirect";

	interface ResponseInit {
		status: number;
		statusText?: string;
		headers?: HeaderInit;
	}

	type HeaderInit = Headers | Array<string>;
	type BodyInit = ArrayBuffer | ArrayBufferView | Blob | FormData | string;
	type RequestInfo = Request | string;

    function fetch(url: string | Request, init?: RequestInit): Promise<Response>;
}

declare module "node-fetch" {
	export = _fetch.fetch;
}


text:
import { makeStyles } from 'tss-react/mui';

import { Typography } from '@mui/material';

import { useLocaleDateTimeFormat } from '@centreon/ui';

const useStyles = makeStyles()({
  copyright: {
    alignItems: 'center',
    display: 'flex'
  }
});

const Copyright = (): JSX.Element => {
  const { classes } = useStyles();
  const { format } = useLocaleDateTimeFormat();

  const year = format({
    date: new Date(),
    formatString: 'YYYY'
  });

  return (
    <Typography className={classes.copyright} variant="body2">
      Copyright © 2005 - {year}
    </Typography>
  );
};

export default Copyright;


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
org.jivesoftware.openfire.forms.spi (Openfire 3.8.1 Javadoc)
</TITLE>

<META NAME="keywords" CONTENT="org.jivesoftware.openfire.forms.spi package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

org.jivesoftware.openfire.forms.spi

Classes

XDataFormImpl

XFormFieldImpl


text:
define([
    'jquery',
    'mage/translate',
    'Magento_Ui/js/modal/modal',
    'jquery/ui',
    'prototype',
], function(jQuery, $t){

window.Variables = {
    textareaElementId: null,
    variablesContent: null,
    dialogWindow: null,
    dialogWindowId: 'variables-chooser',
    overlayShowEffectOptions: null,
    overlayHideEffectOptions: null,
    insertFunction: 'Variables.insertVariable',
    init: function(textareaElementId, insertFunction) {
        if ($(textareaElementId)) {
            this.textareaElementId = textareaElementId;
        }
        if (insertFunction) {
            this.insertFunction = insertFunction;
        }
    },

    resetData: function() {
        this.variablesContent = null;
        this.dialogWindow = null;
    },

    openVariableChooser: function(variables) {
        if (this.variablesContent == null && variables) {
            this.variablesContent = '
';
            variables.each(function(variableGroup) {
                if (variableGroup.label && variableGroup.value) {
                    this.variablesContent += '
' + variableGroup.label + '
';
                    (variableGroup.value).each(function(variable){
                        if (variable.value && variable.label) {
                            this.variablesContent += '
' +
                                this.prepareVariableRow(variable.value, variable.label) + '
';
                        }
                    }.bind(this));
                }
            }.bind(this));
            this.variablesContent += '
';
        }
        if (this.variablesContent) {
            this.openDialogWindow(this.variablesContent);
        }
    },
    openDialogWindow: function (variablesContent) {
        var windowId = this.dialogWindowId;
        jQuery('
' + Variables.variablesContent + '
').modal({
            title: $t('Insert Variable...'),
            type: 'slide',
            buttons: [],
            closed: function (e, modal) {
                modal.modal.remove();
            }
        });

        jQuery('#' + windowId).modal('openModal');

        variablesContent.evalScripts.bind(variablesContent).defer();
    },
    closeDialogWindow: function() {
        jQuery('#' + this.dialogWindowId).modal('closeModal');
    },
    prepareVariableRow: function(varValue, varLabel) {
        var value = (varValue).replace(/"/g, '"').replace(/'/g, '\\'');
        var content = '' + varLabel + '';
        return content;
    },
    insertVariable: function(value) {
        var windowId = this.dialogWindowId;
        jQuery('#' + windowId).modal('closeModal');
        var textareaElm = $(this.textareaElementId);
        if (textareaElm) {
            var scrollPos = textareaElm.scrollTop;
            updateElementAtCursor(textareaElm, value);
            textareaElm.focus();
            textareaElm.scrollTop = scrollPos;
            jQuery(textareaElm).change();
            textareaElm = null;
        }
        return;
    }
};

window.MagentovariablePlugin = {
    editor: null,
    variables: null,
    textareaId: null,
    setEditor: function(editor) {
        this.editor = editor;
    },
    loadChooser: function(url, textareaId) {
        this.textareaId = textareaId;
        if (this.variables == null) {
            new Ajax.Request(url, {
                parameters: {},
                onComplete: function (transport) {
                    if (transport.responseText.isJSON()) {
                        Variables.init(null, 'MagentovariablePlugin.insertVariable');
                        this.variables = transport.responseText.evalJSON();
                        this.openChooser(this.variables);
                    }
                }.bind(this)
             });
        } else {
            this.openChooser(this.variables);
        }
        return;
    },
    openChooser: function(variables) {
        Variables.openVariableChooser(variables);
    },
    insertVariable : function (value) {
        if (this.textareaId) {
            Variables.init(this.textareaId);
            Variables.insertVariable(value);
        } else {
            Variables.closeDialogWindow();
            this.editor.execCommand('mceInsertContent', false, value);
        }
        return;
    }
};

});


text:
@implementation NSString (Helper)

- (void)drawCenteredInRect:(CGRect)rect withFont:(UIFont *)font
{
    CGSize size = [self sizeWithFont:font];

    CGRect textBounds = CGRectMake(rect.origin.x + (rect.size.width - size.width) / 2,
                                   rect.origin.y + (rect.size.height - size.height) / 2,
                                   size.width, size.height);
    [self drawInRect:textBounds withFont:font];
}

- (CGSize)heightWithFont:(UIFont*)withFont width:(float)width linebreak:(UILineBreakMode)lineBreakMode
{
	[withFont retain];
	CGSize suggestedSize = [self sizeWithFont:withFont constrainedToSize:CGSizeMake(width, FLT_MAX) lineBreakMode:lineBreakMode];
	[withFont release];

	return suggestedSize;
}

// URL 인코딩.
- (NSString *)stringByUrlEncoding
{
	return [(NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)self, NULL, CFSTR(":/?#[]@!$&'()*+,;="), kCFStringEncodingUTF8) autorelease];
}

// URL 디코딩.
- (NSString *)stringByUrlDecoding
{
	return [self stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

// 서브스트링.
- (NSString *)substringFrom:(NSInteger)a to:(NSInteger)b
{
	NSRange r;
	r.location = a;
	r.length = b - a;
	return [self substringWithRange:r];
}

- (NSInteger)indexOf:(NSString *)substring from:(NSInteger)starts
{
	NSRange r;
	r.location = starts;
	r.length = [self length] - r.location;

	NSRange index = [self rangeOfString:substring options:NSLiteralSearch range:r];
	if (index.location == NSNotFound)
    {
		return -1;
	}
	return index.location + index.length;
}

// 트림.
- (NSString *)trim
{
	return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}

// 시작 여부.
- (BOOL)startsWith:(NSString *)s
{
	if([self length] < [s length]) return NO;
	return [s isEqualToString:[self substringFrom:0 to:[s length]]];
}

// 포함 여부.
- (BOOL)containsString:(NSString *)aString
{
	NSRange range = [[self lowercaseString] rangeOfString:[aString lowercaseString]];
	return range.location != NSNotFound;
}

// SHA1.
- (NSString *)sha1
{
	NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
	uint8_t digest[CC_SHA1_DIGEST_LENGTH] = {0};
	CC_SHA1(data.bytes, data.length, digest);
	NSData *d = [NSData dataWithBytes:digest length:CC_SHA1_DIGEST_LENGTH];
	return [d hexString];
}

// 숫자 포맷팅(콤마).
- (NSString *)formatNumber
{
    NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
	[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
	NSString *formattedOutput = [formatter stringFromNumber:[NSNumber numberWithLongLong:[self longLongValue]]];

    return formattedOutput;
}

// 실수형 포맷팅(콤마).
- (NSString *)formatDoubleNumber
{
    NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
	[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
	NSString *formattedOutput = [formatter stringFromNumber:[NSNumber numberWithDouble:[self doubleValue]]];

    return formattedOutput;
}

// 퍼센트 포맷(콤마 처리됨).
- (NSString *)formatPercent
{
    NSNumberFormatter *formatter = [[[NSNumberFormatter alloc] init] autorelease];
	[formatter setNumberStyle:NSNumberFormatterPercentStyle];
	NSString *formattedOutput = [formatter stringFromNumber:[NSNumber numberWithLongLong:[self longLongValue]]];

    return formattedOutput;
}

// 소숫점 포맷 유지(스트링 데이터, 예: 00000017.34 > 17.34).
- (NSString *)formatFloatNumber
{
    return [NSString stringWithFormat:@"%.2f", [self floatValue]];
}

// 소숫점 포맷 유지(스트링 데이터, 예: 00000017.34 > 17.34%).
- (NSString *)formatFloatNumberWithPercent
{
    return [NSString stringWithFormat:@"%.2f%%", [self floatValue]];
}

// 빈 문자열 여부.
- (BOOL)isEmpty
{
    if ((NSNull *)self == [NSNull null])
    {
        return YES;
    }
    else if (self == nil)
    {
        return YES;
    }
    else if ([self length] == 0)
    {
        return YES;
    }
    else
    {
        self = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        if ([self length] == 0)
        {
            return YES;
        }
    }

    return NO;
}

// 입력된 문자열 중 오직 숫자만 반환.
- (NSString *)remainOnlyNumber
{
    return [[self componentsSeparatedByCharactersInSet:
             [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
            componentsJoinedByString:@""];
}

// strToChar.
unsigned char strToChar (char a, char b)
{
    char encoder[3] = {'\0','\0','\0'};
    encoder[0] = a;
    encoder[1] = b;
    return (char) strtol(encoder,NULL,16);
}

// cahr > NSData.
- (NSData *)decodeFromHexidecimal;
{
    const char *bytes = [self cStringUsingEncoding: NSUTF8StringEncoding];
    NSUInteger length = strlen(bytes);
    unsigned char *r = (unsigned char *) malloc(length / 2 + 1);
    unsigned char *index = r;

    while ((*bytes) && (*(bytes +1)))
    {
        *index = strToChar(*bytes, *(bytes +1));
        index++;
        bytes+=2;
    }
    *index = '\0';

    NSData *result = [NSData dataWithBytes:r length:length / 2];
    free(r);

    return result;
}

// 기본 localizedCaseInsensitiveCompare는 숫자, 영문(대소무시), 한글 순 정렬
// 한글 > 영문(대소구분 없음) > 숫자 > $
// 그외 특수문자는 전부 무시한채 인덱싱
// $는 예외
// self 가 @"ㄱ" 보다 작고 (한글이 아니고) , compare 가 @"ㄱ"보다 같거나 클때 - 무조건 크다
// 비교하면 -1 0 1 이 작다, 같다, 크다 순이므로 +1 을 하면 한글일때 YES 아니면 NO 가 된다.
// self 가 한글이고 compare 가 한글이 아닐때 무조건 작다인 조건과
// self 가 글자(한/영)이 아니고 compare가 글자(한/영)일떄 무조건 크다인 조건을 반영다.
- (NSComparisonResult)localizedCaseInsensitiveKoreanCompare:(NSString *)compare
{
	NSString *left = [NSString stringWithFormat:@"%@%@",
                      [self localizedCaseInsensitiveCompare:@"ㄱ"]+1 ? @"0" :
					  !([self localizedCaseInsensitiveCompare:@"a"]+1) ? @"2" :
					  @"1", self];
	NSString *right = [NSString stringWithFormat:@"%@%@",
					   [compare localizedCaseInsensitiveCompare:@"ㄱ"]+1 ? @"0" :
					   !([compare localizedCaseInsensitiveCompare:@"a"]+1) ? @"2" :
					   @"1", compare];

	return [left localizedCaseInsensitiveCompare:right];
}

// IP 검증.
- (BOOL)isValidIPAddress
{
    const char *utf8 = [self UTF8String];
    int success;

    struct in_addr dst;
    success = inet_pton(AF_INET, utf8, &dst);
    if (success != 1)
    {
        struct in6_addr dst6;
        success = inet_pton(AF_INET6, utf8, &dst6);
    }

    return (success == 1 ? TRUE : FALSE);
}

@end


text:
Reference.BindingHandlers = [
    {
        name: 'publish',
        description: 'Publishes the specified message and data when the bound element is clicked.',
        bindings: [
            { Binding: 'publish', Type: 'String', Description: 'The message topic to publish.' },
            { Binding: 'data', Type: 'Any', Description: 'The data to publish.' }
        ],
        example: '<button data-bind="publish: \'messageTopic\', data: model.property">Click Me</button>'
    },
    {
        name: 'navigate',
        description: 'Navigates to the specified pane with the specified data when the bound element is clicked.',
        bindings: [
            { Binding: 'navigate', Type: 'String | Object', Description: 'The pane path or options to navigate to.' },
            { Binding: 'data', Type: 'Any', Description: 'The data to pass the target pane.' },
        ],
        example: '<button data-bind="navigate: \'/target/pane\', data: model.property">Click Me</button>'
    }
];


text:
Changelog of Kovenant. Complying to [Semantic Versioning](http://semver.org).
Please refer to [roadmap](roadmap.md) for upcoming releases.

##v3.3.0

**general**

* Update to Kotlin 1.0.3
* [KOV-80](http://issues.komponents.nl/youtrack/issue/KOV-80) enhance/correct the documentation

**core**

* [KOV-87](http://issues.komponents.nl/youtrack/issue/KOV-87) Cancelable deferred

##v3.2.2

**general**

* Update to Kotlin 1.0.1-2

##v3.2.1

**general**

* Update to Kotlin 1.0.1-1

**core**

* [KOV-78](http://issues.komponents.nl/youtrack/issue/KOV-78) Support android with api level set to 15

##v3.2.0

**core**

* [KOV-74](http://issues.komponents.nl/youtrack/issue/KOV-74) Move `unwrap` to core library
* [KOV-75](http://issues.komponents.nl/youtrack/issue/KOV-75) Move `withContext` to core library
* [KOV-76](http://issues.komponents.nl/youtrack/issue/KOV-76) rename `thenUse` to `thenApply`

**general**

* [KOV-77](http://issues.komponents.nl/youtrack/issue/KOV-77) Kotlin 1.0.1

##v3.1.0

**rx**

* [KOV-68](http://issues.komponents.nl/youtrack/issue/KOV-68) Add conversion from rx::Observable to kovenant::Promise
* [KOV-69](http://issues.komponents.nl/youtrack/issue/KOV-69) Add conversion from kovenant::Promise to rx::Observable

**core**

* [KOV-70](http://issues.komponents.nl/youtrack/issue/KOV-70) Leverage sun.misc.Unsafe, fallback to AtomicFieldUpdaters

##v3.0.0

**general**

* Kotlin 1.0

##v3.0.0-rc.1036.1

**core**

* [KOV-67](http://issues.komponents.nl/youtrack/issue/KOV-67) Duplicate execution of task on shutdown boundary

##v3.0.0-rc.1036

**core**

* [KOV-66](http://issues.komponents.nl/youtrack/issue/KOV-66) Make LazyPromise implement kotlin Lazy

##v3.0.0-beta.4

**core**

* [KOV-63](http://issues.komponents.nl/youtrack/issue/KOV-63) rename `async` to `task`

##v3.0.0-beta.3

**general**

* [KOV-27](http://issues.komponents.nl/youtrack/issue/KOV-27) Remove deprecated API

**android**

* [KOV-62](http://issues.komponents.nl/youtrack/issue/KOV-62) Background threads on android should have lower priority

##v2.9.0

**general**

* [KOV-59](http://issues.komponents.nl/youtrack/issue/KOV-59) Kotlin version 1.0.0-beta-1038

**core**

* [KOV-57](http://issues.komponents.nl/youtrack/issue/KOV-57) Allow for daemon threads

##v2.8.0

**jvm**

* [KOV-15](http://issues.komponents.nl/youtrack/issue/KOV-15) Throttle max current processes

##v2.7.0

**general**

* [KOV-56](http://issues.komponents.nl/youtrack/issue/KOV-56) Kotlin M14

##v2.6.0

**general**

* [KOV-53](http://issues.komponents.nl/youtrack/issue/KOV-53) Allow `null` values

**core**

* [KOV-49](http://issues.komponents.nl/youtrack/issue/KOV-49) Better `void`/`Unit` support
* [KOV-54](http://issues.komponents.nl/youtrack/issue/KOV-54) Covariant promise API
* [KOV-55](http://issues.komponents.nl/youtrack/issue/KOV-55) `then` optimizations

##v2.5.0

Updated Kovenant to Kotlin M13.

**general**

* [KOV-50](http://issues.komponents.nl/youtrack/issue/KOV-50) Kotlin M13

**core**

* [KOV-51](http://issues.komponents.nl/youtrack/issue/KOV-51) public interfaces
* [KOV-52](http://issues.komponents.nl/youtrack/issue/KOV-52) default getError bug

##v2.4.0

**general**

This release has generified UI callback support and introduced JavaFX support based on the new UI callback support.
For more information see the [Kovenant document site](http://kovenant.komponents.nl) about the
[Ui Project](http://kovenant.komponents.nl/addons/ui/).

* [KOV-44](http://issues.komponents.nl/youtrack/issue/KOV-44) UI Callback project
* [KOV-35](http://issues.komponents.nl/youtrack/issue/KOV-35) JFX Dispatcher

##v2.3.3

**progress**

* [KOV-45](http://issues.komponents.nl/youtrack/issue/KOV-45) Updated progress

##v2.3.2

**general**

* Updated kotlin version to 0.12.1230
* Improved testing of get()

##v2.3.1

**core**

* [KOV-43](http://issues.komponents.nl/youtrack/issue/KOV-43) Fix for broken get()

##v2.3.0

**core**

* [KOV-36](http://issues.komponents.nl/youtrack/issue/KOV-36) Ability to control JVM thread factory

**kovenant-functional**

* [KOV-37](http://issues.komponents.nl/youtrack/issue/KOV-37) [Unwrap](http://kovenant.komponents.nl/api/functional_usage/#unwrap) method
* [KOV-38](http://issues.komponents.nl/youtrack/issue/KOV-38) Functional constructs. [map](http://kovenant.komponents.nl/api/functional_usage/#map)  / [bind](http://kovenant.komponents.nl/api/functional_usage/#bind)  / [apply](http://kovenant.komponents.nl/api/functional_usage/#apply)  / [withContext](http://kovenant.komponents.nl/api/functional_usage/#withcontext)

##v2.2.1

**general**

* Updated kotlin version to 0.12.1218

##v2.2.0

**kovenant-android**

* [KOV-13](http://issues.komponents.nl/youtrack/issue/KOV-13) Improve performance successUI, failUI, alwaysUI callbacks

**kovenant-core**

* [KOV-12](http://issues.komponents.nl/youtrack/issue/KOV-12) Blocking get functionality
* [KOV-31](http://issues.komponents.nl/youtrack/issue/KOV-31) Allow wait strategies to be properly interrupted

##v2.1.1

**kovenant-disruptor**

* [KOV-33](http://issues.komponents.nl/youtrack/issue/KOV-33) Disruptor project lacks a description

**kovenant-core**

* [KOV-32](http://issues.komponents.nl/youtrack/issue/KOV-32) Empty collections with bulk operations are not properly handled

##v2.1.0

**kovenant-core**

* [KOV-28](http://issues.komponents.nl/youtrack/issue/KOV-28) Instant resolved Promises
* [KOV-26](http://issues.komponents.nl/youtrack/issue/KOV-26) Smoother configuration
* [KOV-25](http://issues.komponents.nl/youtrack/issue/KOV-25) Allow for custom context implementations
* [KOV-29](http://issues.komponents.nl/youtrack/issue/KOV-29) Better backwards compatibility

**kovenant-progress**

* [KOV-8](http://issues.komponents.nl/youtrack/issue/KOV-8) Progress tracking support

**kovenant-disruptor**

* [KOV-7](http://issues.komponents.nl/youtrack/issue/KOV-7) LMAX Disruptor queues

##v2.0.0
[KOV-21](http://issues.komponents.nl/youtrack/issue/KOV-21) Kovenant has a new home which is [komponents.nl](http://komponents.nl) and thus the project is now available as `nl.komponents.kovenant:kovenant:2.0.0`

**general:**

* [KOV-22](http://issues.komponents.nl/youtrack/issue/KOV-22) Kotlin M12

**kovenant-core:**

Mostly breaking API changes in this release:

* [KOV-18](http://issues.komponents.nl/youtrack/issue/KOV-18) Configurable Dispatcher per callback which allows for better integration with other platforms and libraries. _Thanks Jayson Minard_
* [KOV-20](http://issues.komponents.nl/youtrack/issue/KOV-20) Internally there is a new work queue for single consumer scenarios (default for callback dispatcher)
* [KOV-19](http://issues.komponents.nl/youtrack/issue/KOV-19) Fixed an bug where interrupted flags might not be properly cleared by the dispatcher
* [KOV-24](http://issues.komponents.nl/youtrack/issue/KOV-24) Changed the configuration structure (breaking)

##v1.1.0

**general:**

* restructured documentation, ordered by artifact

**kovenant-core:**

* added [Any](api/core_usage.md#any) functionality
* added [All](api/core_usage.md#all) functionality
* [KOV-11](http://issues.komponents.nl/youtrack/issue/KOV-11) added [cancellation](api/core_usage.md#cancel) ability to promises
* [KOV-9](http://issues.komponents.nl/youtrack/issue/KOV-9) added [lazyPromise](api/core_usage.md#lazy-promise) property delegate

**kovenant-android:**

* [KOV-10](http://issues.komponents.nl/youtrack/issue/KOV-10) added easier [Android configuration](android/config.md)

##v1.0.0
The focus of this release has been on Android support.

* KOV-1 Android Dispatcher
* KOV-2 Android extension callback methods
* KOV-4 Improve project structure
* KOV-5 Introduce a blocking WaitStrategy

##v0.1.2

* Fixed a concurrency issue in the callback queue that could lead to NPE's

##v0.1.1

* Made kotlin library an optional dependency to not interfere with peoples projects

##v0.1.0
Initial release.
Bringing Promises to Kotlin. Configuration free.


text:
using LanguageExt.Attributes;
using LanguageExt.TypeClasses;

namespace LanguageExt
{
    [Typeclass("AsyncPair*")]
    public interface AsyncPair<SyncA, AsyncA> : Typeclass
    {
        AsyncA ToAsync(SyncA sa);
    }
}


text:
title: "Lenna 192x192 image comparison"
permalink: /docs/results-192/
excerpt: "Visual comparison of 192x192 images."
---

For a 192 by 192 pixel image the original:

A precisely Gaussian-blurred version:

At least an approximated Gaussian blur version, created with a Lookup Table with 9 inputs and 128 possible entries:


text:
#ifndef _TEST_COMPLEX_H
#define _TEST_COMPLEX_H_
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestFixture.h>

class TestComplex: public CppUnit::TestFixture {
	CPPUNIT_TEST_SUITE( TestComplex );
	CPPUNIT_TEST( test_attribute );
	CPPUNIT_TEST_SUITE_END();
public:
	void test_attribute();

	virtual void setUp();
	virtual void tearDown();
};

#endif


text:
***
FAQ
***

.. currentmodule:: cairo

Pycairo FAQ - Frequently Asked Questions
========================================

Q: Can I subclass pycairo classes?

A: Cairo, the C library, is not an object oriented library, so a Python
binding can never be a truly object oriented interface to cairo.  One way to
write the Python bindings for cairo would be as a single long list of module
functions - this would be the most accurate representation of the underlying C
library. Pycairo (and most other cairo language bindings?) instead chose to
implement the bindings using Context, Surface, Pattern, etc classes.  An
advantage is that the classes organise cairo into groups of similar functions.
A disadvantage is that creates an illusion that cairo is object oriented
library, and people are then tempted to create subclasses to override cairo
methods. When in fact there are no methods to override, just cairo functions
which can't be overridden.

The cairo documentation Appendix A "Creating a language binding for cairo"
section "Memory Management" describes why deriving from a Surface creates
problems and is best avoided.

cairo.Context can be subclassed.
All other pycairo subclasses cannot be subclassed.

Q: How do I use pycairo with numpy?

A: See test/isurface_create_for_data2.py

Q: How do I use pycairo with pygame?

A: See test/pygame-test1.py
       test/pygame-test2.py


text:
package co.uk.niadel.napi.events.entity;

import co.uk.niadel.napi.events.IEvent;
import net.minecraft.entity.Entity;
import co.uk.niadel.napi.events.EventCancellable;

public class EventEntitySpawned extends EventCancellable implements IEvent
{
	Entity entity;

	public EventEntitySpawned(Entity entity)
	{
		this.entity = entity;
	}
}


text:
<?php

namespace OAuth\OAuth2\Service\Exception;

use OAuth\Common\Exception\Exception;

/**
 * Exception thrown when an invalid accessType for the Google Service is specified
 */
class InvalidAccessTypeException extends Exception
{
}


text:
title: "build"
description: "The build command description and usage"
keywords: "build, docker, image"
---

<!-- This file is maintained within the docker/docker Github
     repository at https://github.com/docker/docker/. Make all
     pull requests against that repo. If you see this file in
     another repository, consider it read-only there, as it will
     periodically be overwritten by the definitive file. Pull
     requests which include edits to this file in other repositories
     will be rejected.
-->

# build

```markdown
Usage:  docker build [OPTIONS] PATH | URL | -

Build an image from a Dockerfile

Options:
      --build-arg value         Set build-time variables (default [])
      --cache-from value        Images to consider as cache sources (default [])
      --cgroup-parent string    Optional parent cgroup for the container
      --compress                Compress the build context using gzip
      --cpu-period int          Limit the CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int           Limit the CPU CFS (Completely Fair Scheduler) quota
  -c, --cpu-shares int          CPU shares (relative weight)
      --cpuset-cpus string      CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string      MEMs in which to allow execution (0-3, 0,1)
      --disable-content-trust   Skip image verification (default true)
  -f, --file string             Name of the Dockerfile (Default is 'PATH/Dockerfile')
      --force-rm                Always remove intermediate containers
      --help                    Print usage
      --isolation string        Container isolation technology
      --label value             Set metadata for an image (default [])
  -m, --memory string           Memory limit
      --memory-swap string      Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --network string          Set the networking mode for the RUN instructions during build
                                'bridge': use default Docker bridge
                                'none': no networking
                                'container:<name|id>': reuse another container's network stack
                                'host': use the Docker host network stack
                                '<network-name>|<network-id>': connect to a user-defined network
      --no-cache                Do not use cache when building the image
      --pull                    Always attempt to pull a newer version of the image
  -q, --quiet                   Suppress the build output and print image ID on success
      --rm                      Remove intermediate containers after a successful build (default true)
      --security-opt value      Security Options (default [])
      --shm-size string         Size of /dev/shm, default value is 64MB.
                                The format is `<number><unit>`. `number` must be greater than `0`.
                                Unit is optional and can be `b` (bytes), `k` (kilobytes), `m` (megabytes),
                                or `g` (gigabytes). If you omit the unit, the system uses bytes.
      --squash                  Squash newly built layers into a single new layer (**Experimental Only**)
  -t, --tag value               Name and optionally a tag in the 'name:tag' format (default [])
      --ulimit value            Ulimit options (default [])
```

Builds Docker images from a Dockerfile and a "context". A build's context is
the files located in the specified `PATH` or `URL`. The build process can refer
to any of the files in the context. For example, your build can use an
[*ADD*](../builder.md#add) instruction to reference a file in the
context.

The `URL` parameter can refer to three kinds of resources: Git repositories,
pre-packaged tarball contexts and plain text files.

### Git repositories

When the `URL` parameter points to the location of a Git repository, the
repository acts as the build context. The system recursively clones the
repository and its submodules using a `git clone --depth 1 --recursive`
command. This command runs in a temporary directory on your local host. After
the command succeeds, the directory is sent to the Docker daemon as the
context. Local clones give you the ability to access private repositories using
local user credentials, VPN's, and so forth.

Git URLs accept context configuration in their fragment section, separated by a
colon `:`.  The first part represents the reference that Git will check out,
this can be either a branch, a tag, or a commit SHA. The second part represents
a subdirectory inside the repository that will be used as a build context.

For example, run this command to use a directory called `docker` in the branch
`container`:

```bash
$ docker build https://github.com/docker/rootfs.git#container:docker
```

The following table represents all the valid suffixes with their build
contexts:

Build Syntax Suffix             | Commit Used           | Build Context Used
--------------------------------|-----------------------|-------------------
`myrepo.git`                    | `refs/heads/master`   | `/`
`myrepo.git#mytag`              | `refs/tags/mytag`     | `/`
`myrepo.git#mybranch`           | `refs/heads/mybranch` | `/`
`myrepo.git#abcdef`             | `sha1 = abcdef`       | `/`
`myrepo.git#:myfolder`          | `refs/heads/master`   | `/myfolder`
`myrepo.git#master:myfolder`    | `refs/heads/master`   | `/myfolder`
`myrepo.git#mytag:myfolder`     | `refs/tags/mytag`     | `/myfolder`
`myrepo.git#mybranch:myfolder`  | `refs/heads/mybranch` | `/myfolder`
`myrepo.git#abcdef:myfolder`    | `sha1 = abcdef`       | `/myfolder`

### Tarball contexts

If you pass an URL to a remote tarball, the URL itself is sent to the daemon:

Instead of specifying a context, you can pass a single Dockerfile in the `URL`
or pipe the file in via `STDIN`. To pipe a Dockerfile from `STDIN`:

```bash
$ docker build http://server/context.tar.gz
```

The download operation will be performed on the host the Docker daemon is
running on, which is not necessarily the same host from which the build command
is being issued. The Docker daemon will fetch `context.tar.gz` and use it as the
build context. Tarball contexts must be tar archives conforming to the standard
`tar` UNIX format and can be compressed with any one of the 'xz', 'bzip2',
'gzip' or 'identity' (no compression) formats.

### Text files

Instead of specifying a context, you can pass a single `Dockerfile` in the
`URL` or pipe the file in via `STDIN`. To pipe a `Dockerfile` from `STDIN`:

```bash
$ docker build - < Dockerfile
```

With Powershell on Windows, you can run:

```powershell
Get-Content Dockerfile | docker build -
```

If you use `STDIN` or specify a `URL` pointing to a plain text file, the system
places the contents into a file called `Dockerfile`, and any `-f`, `--file`
option is ignored. In this scenario, there is no context.

By default the `docker build` command will look for a `Dockerfile` at the root
of the build context. The `-f`, `--file`, option lets you specify the path to
an alternative file to use instead. This is useful in cases where the same set
of files are used for multiple builds. The path must be to a file within the
build context. If a relative path is specified then it is interpreted as
relative to the root of the context.

In most cases, it's best to put each Dockerfile in an empty directory. Then,
add to that directory only the files needed for building the Dockerfile. To
increase the build's performance, you can exclude files and directories by
adding a `.dockerignore` file to that directory as well. For information on
creating one, see the [.dockerignore file](../builder.md#dockerignore-file).

If the Docker client loses connection to the daemon, the build is canceled.
This happens if you interrupt the Docker client with `CTRL-c` or if the Docker
client is killed for any reason. If the build initiated a pull which is still
running at the time the build is cancelled, the pull is cancelled as well.

## Return code

On a successful build, a return code of success `0` will be returned.  When the
build fails, a non-zero failure code will be returned.

There should be informational output of the reason for failure output to
`STDERR`:

```bash
$ docker build -t fail .

Sending build context to Docker daemon 2.048 kB
Sending build context to Docker daemon
Step 1/3 : FROM busybox
 ---> 4986bf8c1536
Step 2/3 : RUN exit 13
 ---> Running in e26670ec7a0a
INFO[0000] The command [/bin/sh -c exit 13] returned a non-zero code: 13
$ echo $?
1
```

See also:

[*Dockerfile Reference*](../builder.md).

## Examples

### Build with PATH

```bash
$ docker build .

Uploading context 10240 bytes
Step 1/3 : FROM busybox
Pulling repository busybox
 ---> e9aa60c60128MB/2.284 MB (100%) endpoint: https://cdn-registry-1.docker.io/v1/
Step 2/3 : RUN ls -lh /
 ---> Running in 9c9e81692ae9
total 24
drwxr-xr-x    2 root     root        4.0K Mar 12  2013 bin
drwxr-xr-x    5 root     root        4.0K Oct 19 00:19 dev
drwxr-xr-x    2 root     root        4.0K Oct 19 00:19 etc
drwxr-xr-x    2 root     root        4.0K Nov 15 23:34 lib
lrwxrwxrwx    1 root     root           3 Mar 12  2013 lib64 -> lib
dr-xr-xr-x  116 root     root           0 Nov 15 23:34 proc
lrwxrwxrwx    1 root     root           3 Mar 12  2013 sbin -> bin
dr-xr-xr-x   13 root     root           0 Nov 15 23:34 sys
drwxr-xr-x    2 root     root        4.0K Mar 12  2013 tmp
drwxr-xr-x    2 root     root        4.0K Nov 15 23:34 usr
 ---> b35f4035db3f
Step 3/3 : CMD echo Hello world
 ---> Running in 02071fceb21b
 ---> f52f38b7823e
Successfully built f52f38b7823e
Removing intermediate container 9c9e81692ae9
Removing intermediate container 02071fceb21b
```

This example specifies that the `PATH` is `.`, and so all the files in the
local directory get `tar`d and sent to the Docker daemon. The `PATH` specifies
where to find the files for the "context" of the build on the Docker daemon.
Remember that the daemon could be running on a remote machine and that no
parsing of the Dockerfile happens at the client side (where you're running
`docker build`). That means that *all* the files at `PATH` get sent, not just
the ones listed to [*ADD*](../builder.md#add) in the Dockerfile.

The transfer of context from the local machine to the Docker daemon is what the
`docker` client means when you see the "Sending build context" message.

If you wish to keep the intermediate containers after the build is complete,
you must use `--rm=false`. This does not affect the build cache.

### Build with URL

```bash
$ docker build github.com/creack/docker-firefox
```

This will clone the GitHub repository and use the cloned repository as context.
The Dockerfile at the root of the repository is used as Dockerfile. You can
specify an arbitrary Git repository by using the `git://` or `git@` scheme.

```bash
$ docker build -f ctx/Dockerfile http://server/ctx.tar.gz

Downloading context: http://server/ctx.tar.gz [===================>]    240 B/240 B
Step 1/3 : FROM busybox
 ---> 8c2e06607696
Step 2/3 : ADD ctx/container.cfg /
 ---> e7829950cee3
Removing intermediate container b35224abf821
Step 3/3 : CMD /bin/ls
 ---> Running in fbc63d321d73
 ---> 3286931702ad
Removing intermediate container fbc63d321d73
Successfully built 377c409b35e4
```

This sends the URL `http://server/ctx.tar.gz` to the Docker daemon, which
downloads and extracts the referenced tarball. The `-f ctx/Dockerfile`
parameter specifies a path inside `ctx.tar.gz` to the `Dockerfile` that is used
to build the image. Any `ADD` commands in that `Dockerfile` that refer to local
paths must be relative to the root of the contents inside `ctx.tar.gz`. In the
example above, the tarball contains a directory `ctx/`, so the `ADD
ctx/container.cfg /` operation works as expected.

### Build with -

```bash
$ docker build - < Dockerfile
```

This will read a Dockerfile from `STDIN` without context. Due to the lack of a
context, no contents of any local directory will be sent to the Docker daemon.
Since there is no context, a Dockerfile `ADD` only works if it refers to a
remote URL.

```bash
$ docker build - < context.tar.gz
```

This will build an image for a compressed context read from `STDIN`.  Supported
formats are: bzip2, gzip and xz.

### Usage of .dockerignore

```bash
$ docker build .

Uploading context 18.829 MB
Uploading context
Step 1/2 : FROM busybox
 ---> 769b9341d937
Step 2/2 : CMD echo Hello world
 ---> Using cache
 ---> 99cc1ad10469
Successfully built 99cc1ad10469
$ echo ".git" > .dockerignore
$ docker build .
Uploading context  6.76 MB
Uploading context
Step 1/2 : FROM busybox
 ---> 769b9341d937
Step 2/2 : CMD echo Hello world
 ---> Using cache
 ---> 99cc1ad10469
Successfully built 99cc1ad10469
```

This example shows the use of the `.dockerignore` file to exclude the `.git`
directory from the context. Its effect can be seen in the changed size of the
uploaded context. The builder reference contains detailed information on
[creating a .dockerignore file](../builder.md#dockerignore-file)

### Tag image (-t)

```bash
$ docker build -t vieux/apache:2.0 .
```

This will build like the previous example, but it will then tag the resulting
image. The repository name will be `vieux/apache` and the tag will be `2.0`.
[Read more about valid tags](tag.md).

You can apply multiple tags to an image. For example, you can apply the `latest`
tag to a newly built image and add another tag that references a specific
version.
For example, to tag an image both as `whenry/fedora-jboss:latest` and
`whenry/fedora-jboss:v2.1`, use the following:

```bash
$ docker build -t whenry/fedora-jboss:latest -t whenry/fedora-jboss:v2.1 .
```
### Specify Dockerfile (-f)

```bash
$ docker build -f Dockerfile.debug .
```

This will use a file called `Dockerfile.debug` for the build instructions
instead of `Dockerfile`.

```bash
$ docker build -f dockerfiles/Dockerfile.debug -t myapp_debug .
$ docker build -f dockerfiles/Dockerfile.prod  -t myapp_prod .
```

The above commands will build the current build context (as specified by the
`.`) twice, once using a debug version of a `Dockerfile` and once using a
production version.

```bash
$ cd /home/me/myapp/some/dir/really/deep
$ docker build -f /home/me/myapp/dockerfiles/debug /home/me/myapp
$ docker build -f ../../../../dockerfiles/debug /home/me/myapp
```

These two `docker build` commands do the exact same thing. They both use the
contents of the `debug` file instead of looking for a `Dockerfile` and will use
`/home/me/myapp` as the root of the build context. Note that `debug` is in the
directory structure of the build context, regardless of how you refer to it on
the command line.

> **Note:**
> `docker build` will return a `no such file or directory` error if the
> file or directory does not exist in the uploaded context. This may
> happen if there is no context, or if you specify a file that is
> elsewhere on the Host system. The context is limited to the current
> directory (and its children) for security reasons, and to ensure
> repeatable builds on remote Docker hosts. This is also the reason why
> `ADD ../file` will not work.

### Optional parent cgroup (--cgroup-parent)

When `docker build` is run with the `--cgroup-parent` option the containers
used in the build will be run with the [corresponding `docker run`
flag](../run.md#specifying-custom-cgroups).

### Set ulimits in container (--ulimit)

Using the `--ulimit` option with `docker build` will cause each build step's
container to be started using those [`--ulimit`
flag values](./run.md#set-ulimits-in-container-ulimit).

### Set build-time variables (--build-arg)

You can use `ENV` instructions in a Dockerfile to define variable
values. These values persist in the built image. However, often
persistence is not what you want. Users want to specify variables differently
depending on which host they build an image on.

A good example is `http_proxy` or source versions for pulling intermediate
files. The `ARG` instruction lets Dockerfile authors define values that users
can set at build-time using the  `--build-arg` flag:

```bash
$ docker build --build-arg HTTP_PROXY=http://10.20.30.2:1234 .
```

This flag allows you to pass the build-time variables that are
accessed like regular environment variables in the `RUN` instruction of the
Dockerfile. Also, these values don't persist in the intermediate or final images
like `ENV` values do.

Using this flag will not alter the output you see when the `ARG` lines from the
Dockerfile are echoed during the build process.

For detailed information on using `ARG` and `ENV` instructions, see the
[Dockerfile reference](../builder.md).

### Optional security options (--security-opt)

This flag is only supported on a daemon running on Windows, and only supports
the `credentialspec` option. The `credentialspec` must be in the format
`file://spec.txt` or `registry://keyname`.

### Specify isolation technology for container (--isolation)

This option is useful in situations where you are running Docker containers on
Windows. The `--isolation=<value>` option sets a container's isolation
technology. On Linux, the only supported is the `default` option which uses
Linux namespaces. On Microsoft Windows, you can specify these values:

| Value     | Description                                                                                |
|-----------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `default` | Use the value specified by the Docker daemon's `--exec-opt` . If the `daemon` does not specify an isolation technology, Microsoft Windows uses `process` as its default value.  |
| `process` | Namespace isolation only.                                                                                |
| `hyperv`  | Hyper-V hypervisor partition-based isolation.                                                                                |

Specifying the `--isolation` flag without a value is the same as setting `--isolation="default"`.

### Squash an image's layers (--squash) **Experimental Only**

Once the image is built, squash the new layers into a new image with a single
new layer. Squashing does not destroy any existing image, rather it creates a new
image with the content of the squshed layers. This effectively makes it look
like all `Dockerfile` commands were created with a single layer. The build
cache is preserved with this method.

**Note**: using this option means the new image will not be able to take
advantage of layer sharing with other images and may use significantly more
space.

**Note**: using this option you may see significantly more space used due to
storing two copies of the image, one for the build cache with all the cache
layers in tact, and one for the squashed version.


text:
id: 587d7db7367417b2b2512b9c
title: Find One or More Criminals in a Hunt
challengeType: 1
videoUrl: ''
localeTitle: Encontre um ou mais criminosos em uma caçada
---

## Description

 Hora de fazer uma pausa e testar suas novas habilidades de redação de regex. Um grupo de criminosos escapou da prisão e fugiu, mas você não sabe quantos. No entanto, você sabe que eles ficam juntos quando estão perto de outras pessoas. Você é responsável por encontrar todos os criminosos de uma só vez. Aqui está um exemplo para revisar como fazer isso: O regex /z+/ corresponde à letra z quando aparece uma ou mais vezes seguidas. Ele encontraria correspondências em todas as seguintes strings:
 "z"
 "zzzzzz"
 "ABCzzzz"
 "zzzzABC"
 "abczzzzzzzzzzzzzzzzzzzzzabc"
 Mas ele não encontra correspondências nas strings a seguir, pois não há caracteres da letra z :
 ""
 "ABC"
 "abcabc"

## Instructions

 Escreva um regex greedy que encontre um ou mais criminosos dentro de um grupo de outras pessoas. Um criminoso é representado pela letra maiúscula C

## Tests

```yml
tests:
  - text: Seu regex deve corresponder a <code>one</code> criminoso (" <code>C</code> ") em <code>"C"</code>
    testString: 'assert("C".match(reCriminals) && "C".match(reCriminals)[0] == "C", "Your regex should match <code>one</code> criminal ("<code>C</code>") in <code>"C"</code>");'
  - text: Seu regex deve coincidir com <code>two</code> criminosos (" <code>CC</code> ") em <code>"CC"</code>
    testString: 'assert("CC".match(reCriminals) && "CC".match(reCriminals)[0] == "CC", "Your regex should match <code>two</code> criminals ("<code>CC</code>") in <code>"CC"</code>");'
  - text: Seu regex deve corresponder a <code>three</code> criminosos (" <code>CCC</code> ") em <code>"P1P5P4CCCP2P6P3"</code>
    testString: 'assert("P1P5P4CCCP2P6P3".match(reCriminals) && "P1P5P4CCCP2P6P3".match(reCriminals)[0] == "CCC", "Your regex should match <code>three</code> criminals ("<code>CCC</code>") in <code>"P1P5P4CCCP2P6P3"</code>");'
  - text: Seu regex deve corresponder a <code>five</code> criminosos (" <code>CCCCC</code> ") em <code>"P6P2P7P4P5CCCCCP3P1"</code>
    testString: 'assert("P6P2P7P4P5CCCCCP3P1".match(reCriminals) && "P6P2P7P4P5CCCCCP3P1".match(reCriminals)[0] == "CCCCC", "Your regex should match <code>five</code> criminals ("<code>CCCCC</code>") in <code>"P6P2P7P4P5CCCCCP3P1"</code>");'
  - text: Seu regex não deve corresponder a nenhum criminoso em <code>""</code>
    testString: 'assert(!reCriminals.test(""), "Your regex should not match any criminals in <code>""</code>");'
  - text: Seu regex não deve corresponder a nenhum criminoso em <code>"P1P2P3"</code>
    testString: 'assert(!reCriminals.test("P1P2P3"), "Your regex should not match any criminals in <code>"P1P2P3"</code>");'
  - text: Seu regex deve corresponder a <code>fifty</code> criminosos (" <code>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC</code> ") em <code>"P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3"</code> .
    testString: 'assert("P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3".match(reCriminals) && "P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3".match(reCriminals)[0] == "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC", "Your regex should match <code>fifty</code> criminals ("<code>CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC</code>") in <code>"P2P1P5P4CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCP3"</code>.");'

```

## Challenge Seed

```js
// example crowd gathering
let crowd = 'P1P2P3P4P5P6CCCP7P8P9';

let reCriminals = /./; // Change this line

let matchedCriminals = crowd.match(reCriminals);
console.log(matchedCriminals);

```

## Solution

```js
// solution required
```


text:
namespace Three {
    class Parser;
    class DataType;
};

namespace Three {
    class ASTNode {
    public:
        ASTNode();
        ASTNode(const ASTNode& other) = delete;
        virtual ~ASTNode();

        bool     addChild(ASTNode* node);
        ASTNode* childAtIndex(uint32_t i) const;
        ASTNode* lastChild() const;
        uint32_t childCount() const;
        void     eachChild(std::function<void (ASTNode*, uint32_t)> func);
        void     eachChildWithLast(std::function<void (ASTNode*, bool)> func);

        bool statement() const;
        void setStatement(bool value);
        virtual bool includesParentheses() const;
        virtual DataType dataType() const;

        virtual std::string name() const = 0;
        virtual std::string nodeName() const;
        virtual std::string str() const;
        std::string recursiveStr(uint32_t depth = 0) const;

        virtual void accept(ASTVisitor& visitor);
        void acceptChildren(ASTVisitor& visitor);

    private:
        std::vector<ASTNode*> _childNodes;
        bool _statement;
    };
}


text:
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

/**
 * @module moodle-atto_table-button
 */

/**
 * Atto text editor table plugin.
 *
 * @namespace M.atto_table
 * @class Button
 * @extends M.editor_atto.EditorPlugin
 */

var COMPONENT = 'atto_table',
    EDITTEMPLATE = '' +
        '<form class="{{CSS.FORM}}">' +
            '{{get_string "caption" component}}' +
            '<input class="{{CSS.CAPTION}} fullwidth" id="{{elementid}}_atto_table_caption" required />' +
            '
' +
            '
' +
            '{{get_string "headers" component}}' +
            '<select class="{{CSS.HEADERS}}" id="{{elementid}}_atto_table_headers">' +
                '<option value="columns">{{get_string "columns" component}}' + '</option>' +
                '<option value="rows">{{get_string "rows" component}}' + '</option>' +
                '<option value="both">{{get_string "both" component}}' + '</option>' +
            '</select>' +
            '
' +
            '
' +
                '
' +
                '<button class="submit" type="submit">{{get_string "updatetable" component}}</button>' +
            '
' +
        '</form>',
    TEMPLATE = '' +
        '<form class="{{CSS.FORM}}">' +
            '{{get_string "caption" component}}' +
            '<input class="{{CSS.CAPTION}} fullwidth" id="{{elementid}}_atto_table_caption" required />' +
            '
' +
            '
' +
            '{{get_string "headers" component}}' +
            '<select class="{{CSS.HEADERS}}" id="{{elementid}}_atto_table_headers">' +
                '<option value="columns">{{get_string "columns" component}}' + '</option>' +
                '<option value="rows">{{get_string "rows" component}}' + '</option>' +
                '<option value="both">{{get_string "both" component}}' + '</option>' +
            '</select>' +
            '
' +
            '{{get_string "numberofrows" component}}' +
            '<input class="{{CSS.ROWS}}" type="number" value="3" id="{{elementid}}_atto_table_rows" size="8" min="1" max="50"/>' +
            '
' +
            '{{get_string "numberofcolumns" component}}' +
            '<input class="{{CSS.COLUMNS}}" type="number" value="3" id="{{elementid}}_atto_table_columns" ' +
                    'size="8" min="1" max="20"/>' +
            '
' +
            '
' +
                '
' +
                '<button class="{{CSS.SUBMIT}}" type="submit">{{get_string "createtable" component}}</button>' +
            '
' +
        '</form>',
    CSS = {
        CAPTION: 'caption',
        HEADERS: 'headers',
        ROWS: 'rows',
        COLUMNS: 'columns',
        SUBMIT: 'submit',
        FORM: 'atto_form'
    },
    SELECTORS = {
        CAPTION: '.' + CSS.CAPTION,
        HEADERS: '.' + CSS.HEADERS,
        ROWS: '.' + CSS.ROWS,
        COLUMNS: '.' + CSS.COLUMNS,
        SUBMIT: '.' + CSS.SUBMIT,
        FORM: '.atto_form'
    };

Y.namespace('M.atto_table').Button = Y.Base.create('button', Y.M.editor_atto.EditorPlugin, [], {

    /**
     * A reference to the current selection at the time that the dialogue
     * was opened.
     *
     * @property _currentSelection
     * @type Range
     * @private
     */
    _currentSelection: null,

    /**
     * The contextual menu that we can open.
     *
     * @property _contextMenu
     * @type M.editor_atto.Menu
     * @private
     */
    _contextMenu: null,

    /**
     * The last modified target.
     *
     * @property _lastTarget
     * @type Node
     * @private
     */
    _lastTarget: null,

    /**
     * The list of menu items.
     *
     * @property _menuOptions
     * @type Object
     * @private
     */
    _menuOptions: null,

    initializer: function() {
        this.addButton({
            icon: 'e/table',
            callback: this._displayTableEditor,
            tags: 'table'
        });

        // Disable mozilla table controls.
        if (Y.UA.gecko) {
            document.execCommand("enableInlineTableEditing", false, false);
            document.execCommand("enableObjectResizing", false, false);
        }
    },

    /**
     * Display the table tool.
     *
     * @method _displayDialogue
     * @private
     */
    _displayDialogue: function() {
        // Store the current cursor position.
        this._currentSelection = this.get('host').getSelection();

        if (this._currentSelection !== false && (!this._currentSelection.collapsed)) {
            var dialogue = this.getDialogue({
                headerContent: M.util.get_string('createtable', COMPONENT),
                focusAfterHide: true,
                focusOnShowSelector: SELECTORS.CAPTION
            });

            // Set the dialogue content, and then show the dialogue.
            dialogue.set('bodyContent', this._getDialogueContent())
                    .show();
        }
    },

    /**
     * Display the appropriate table editor.
     *
     * If the current selection includes a table, then we show the
     * contextual menu, otherwise show the table creation dialogue.
     *
     * @method _displayTableEditor
     * @param {EventFacade} e
     * @private
     */
    _displayTableEditor: function(e) {
        var cell = this._getSuitableTableCell();
        if (cell) {
            // Add the cell to the EventFacade to save duplication in when showing the menu.
            e.tableCell = cell;
            return this._showTableMenu(e);
        }
        return this._displayDialogue(e);
    },

    /**
     * Returns whether or not the parameter node exists within the editor.
     *
     * @method _stopAtContentEditableFilter
     * @param  {Node} node
     * @private
     * @return {boolean} whether or not the parameter node exists within the editor.
     */
    _stopAtContentEditableFilter: function(node) {
        this.editor.contains(node);
    },

    /**
     * Return the edit table dialogue content, attaching any required
     * events.
     *
     * @method _getEditDialogueContent
     * @private
     * @return {Node} The content to place in the dialogue.
     */
    _getEditDialogueContent: function() {
        var template = Y.Handlebars.compile(EDITTEMPLATE);
        this._content = Y.Node.create(template({
                CSS: CSS,
                elementid: this.get('host').get('elementid'),
                component: COMPONENT
            }));

        // Handle table setting.
        this._content.one('.submit').on('click', this._updateTable, this);

        return this._content;
    },

    /**
     * Return the dialogue content for the tool, attaching any required
     * events.
     *
     * @method _getDialogueContent
     * @private
     * @return {Node} The content to place in the dialogue.
     */
    _getDialogueContent: function() {
        var template = Y.Handlebars.compile(TEMPLATE);
        this._content = Y.Node.create(template({
                CSS: CSS,
                elementid: this.get('host').get('elementid'),
                component: COMPONENT
            }));

        // Handle table setting.
        this._content.one('.submit').on('click', this._setTable, this);

        return this._content;
    },

    /**
     * Given the current selection, return a table cell suitable for table editing
     * purposes, i.e. the first table cell selected, or the first cell in the table
     * that the selection exists in, or null if not within a table.
     *
     * @method _getSuitableTableCell
     * @private
     * @return {Node} suitable target cell, or null if not within a table
     */
    _getSuitableTableCell: function() {
        var targetcell = null,
            host = this.get('host');

        host.getSelectedNodes().some(function (node) {
            if (node.ancestor('td, th, caption', true, this._stopAtContentEditableFilter)) {
                targetcell = node;

                var caption = node.ancestor('caption', true, this._stopAtContentEditableFilter);
                if (caption) {
                    var table = caption.get('parentNode');
                    if (table) {
                        targetcell = table.one('td, th');
                    }
                }

                // Once we've found a cell to target, we shouldn't need to keep looking.
                return true;
            }
        });

        if (targetcell) {
            var selection = host.getSelectionFromNode(targetcell);
            host.setSelection(selection);
        }

        return targetcell;
    },

    /**
     * Change a node from one type to another, copying all attributes and children.
     *
     * @method _changeNodeType
     * @param {Y.Node} node
     * @param {String} new node type
     * @private
     * @chainable
     */
    _changeNodeType: function(node, newType) {
        var newNode = Y.Node.create('<' + newType + '></' + newType + '>');
        newNode.setAttrs(node.getAttrs());
        node.get('childNodes').each(function(child) {
            newNode.append(child.remove());
        });
        node.replace(newNode);
        return newNode;
    },

    /**
     * Handle updating an existing table.
     *
     * @method _updateTable
     * @param {EventFacade} e
     * @private
     */
    _updateTable: function(e) {
        var caption,
            headers,
            table,
            captionnode;

        e.preventDefault();
        // Hide the dialogue.
        this.getDialogue({
            focusAfterHide: null
        }).hide();

        // Add/update the caption.
        caption = e.currentTarget.ancestor(SELECTORS.FORM).one(SELECTORS.CAPTION);
        headers = e.currentTarget.ancestor(SELECTORS.FORM).one(SELECTORS.HEADERS);

        table = this._lastTarget.ancestor('table');

        captionnode = table.one('caption');
        if (!captionnode) {
            captionnode = Y.Node.create('
</caption');
            table.insert(captionnode, 0);
        }
        captionnode.setHTML(caption.get('value'));

        // Add the row headers.
        if (headers.get('value') === 'rows' || headers.get('value') === 'both') {
            table.all('tr').each(function (row) {
                var cells = row.all('th, td'),
                    firstCell = cells.shift(),
                    newCell;

                if (firstCell.get('tagName') === 'TD') {
                    // Cell is a td but should be a th - change it.
                    newCell = this._changeNodeType(firstCell, 'th');
                    newCell.setAttribute('scope', 'row');
                } else {
                    firstCell.setAttribute('scope', 'row');
                }

                // Now make sure all other cells in the row are td.
                cells.each(function (cell) {
                    if (cell.get('tagName') === 'TH') {
                        newCell = this._changeNodeType(cell, 'td');
                        newCell.removeAttribute('scope');
                    }
                }, this);

            }, this);
        }
        // Add the col headers. These may overrule the row headers in the first cell.
        if (headers.get('value') === 'columns' || headers.get('value') === 'both') {
            var rows = table.all('tr'),
                firstRow = rows.shift(),
                newCell;

            firstRow.all('td, th').each(function (cell) {
                if (cell.get('tagName') === 'TD') {
                    // Cell is a td but should be a th - change it.
                    newCell = this._changeNodeType(cell, 'th');
                    newCell.setAttribute('scope', 'col');
                } else {
                    cell.setAttribute('scope', 'col');
                }
            }, this);
            // Change all the cells in the rest of the table to tds (unless they are row headers).
            rows.each(function(row) {
                var cells = row.all('th, td');

                if (headers.get('value') === 'both') {
                    // Ignore the first cell because it's a row header.
                    cells.shift();
                }
                cells.each(function(cell) {
                    if (cell.get('tagName') === 'TH') {
                        newCell = this._changeNodeType(cell, 'td');
                        newCell.removeAttribute('scope');
                    }
                }, this);

            }, this);
        }
        // Clean the HTML.
        this.markUpdated();
    },

    /**
     * Handle creation of a new table.
     *
     * @method _setTable
     * @param {EventFacade} e
     * @private
     */
    _setTable: function(e) {
        var caption,
            rows,
            cols,
            headers,
            tablehtml,
            i, j;

        e.preventDefault();

        // Hide the dialogue.
        this.getDialogue({
            focusAfterHide: null
        }).hide();

        caption = e.currentTarget.ancestor(SELECTORS.FORM).one(SELECTORS.CAPTION);
        rows = e.currentTarget.ancestor(SELECTORS.FORM).one(SELECTORS.ROWS);
        cols = e.currentTarget.ancestor(SELECTORS.FORM).one(SELECTORS.COLUMNS);
        headers = e.currentTarget.ancestor(SELECTORS.FORM).one(SELECTORS.HEADERS);

        // Set the selection.
        this.get('host').setSelection(this._currentSelection);

        // Note there are some spaces inserted in the cells and before and after, so that users have somewhere to click.
        var nl = "\n";
        tablehtml = '
' + nl + '
' + nl;
        tablehtml += '
' + Y.Escape.html(caption.get('value')) + '
' + nl;

        i = 0;
        if (headers.get('value') === 'columns' || headers.get('value') === 'both') {
            i = 1;
            tablehtml += '
' + nl + '
' + nl;
            for (j = 0; j < parseInt(cols.get('value'), 10); j++) {
                tablehtml += '	' + nl;
            }
            tablehtml += '
' + nl + '
' + nl;
        }
        tablehtml += '
' + nl;
        for (; i < parseInt(rows.get('value'), 10); i++) {
            tablehtml += '
' + nl;
            for (j = 0; j < parseInt(cols.get('value'), 10); j++) {
                if (j === 0 && (headers.get('value') === 'rows' || headers.get('value') === 'both')) {
                    tablehtml += '	' + nl;
                } else {
                    tablehtml += '	' + nl;
                }
            }
            tablehtml += '
' + nl;
        }
        tablehtml += '
' + nl;
        tablehtml += '
' + nl + '
';

        this.get('host').insertContentAtFocusPoint(tablehtml);

        // Mark the content as updated.
        this.markUpdated();
    },

    /**
     * Search for all the cells in the current, next and previous columns.
     *
     * @method _findColumnCells
     * @private
     * @return {Object} containing current, prev and next {Y.NodeList}s
     */
    _findColumnCells: function() {
        var columnindex = this._getColumnIndex(this._lastTarget),
            rows = this._lastTarget.ancestor('table').all('tr'),
            currentcells = new Y.NodeList(),
            prevcells = new Y.NodeList(),
            nextcells = new Y.NodeList();

        rows.each(function(row) {
            var cells = row.all('td, th'),
                cell = cells.item(columnindex),
                cellprev = cells.item(columnindex-1),
                cellnext = cells.item(columnindex+1);
            currentcells.push(cell);
            if (cellprev) {
                prevcells.push(cellprev);
            }
            if (cellnext) {
                nextcells.push(cellnext);
            }
        });

        return {
            current: currentcells,
            prev: prevcells,
            next: nextcells
        };
    },

    /**
     * Hide the entries in the context menu that don't make sense with the
     * current selection.
     *
     * @method _hideInvalidEntries
     * @param {Y.Node} node - The node containing the menu.
     * @private
     */
    _hideInvalidEntries: function(node) {
        // Moving rows.
        var table = this._lastTarget.ancestor('table'),
            row = this._lastTarget.ancestor('tr'),
            rows = table.all('tr'),
            rowindex = rows.indexOf(row),
            prevrow = rows.item(rowindex - 1),
            prevrowhascells = prevrow ? prevrow.one('td') : null;

        if (!row || !prevrowhascells) {
            node.one('[data-change="moverowup"]').hide();
        } else {
            node.one('[data-change="moverowup"]').show();
        }

        var nextrow = rows.item(rowindex + 1),
            rowhascell = row ? row.one('td') : false;

        if (!row || !nextrow || !rowhascell) {
            node.one('[data-change="moverowdown"]').hide();
        } else {
            node.one('[data-change="moverowdown"]').show();
        }

        // Moving columns.
        var cells = this._findColumnCells();
        if (cells.prev.filter('td').size() > 0) {
            node.one('[data-change="movecolumnleft"]').show();
        } else {
            node.one('[data-change="movecolumnleft"]').hide();
        }

        var colhascell = cells.current.filter('td').size() > 0;
        if ((cells.next.size() > 0) && colhascell) {
            node.one('[data-change="movecolumnright"]').show();
        } else {
            node.one('[data-change="movecolumnright"]').hide();
        }

        // Delete col
        if (cells.current.filter('td').size() > 0) {
            node.one('[data-change="deletecolumn"]').show();
        } else {
            node.one('[data-change="deletecolumn"]').hide();
        }
        // Delete row
        if (!row || !row.one('td')) {
            node.one('[data-change="deleterow"]').hide();
        } else {
            node.one('[data-change="deleterow"]').show();
        }
    },

    /**
     * Display the table menu.
     *
     * @method _showTableMenu
     * @param {EventFacade} e
     * @private
     */
    _showTableMenu: function(e) {
        e.preventDefault();

        var boundingBox;

        if (!this._contextMenu) {
            this._menuOptions = [
                {
                    text: M.util.get_string("addcolumnafter", COMPONENT),
                    data: {
                        change: "addcolumnafter"
                    }
                }, {
                    text: M.util.get_string("addrowafter", COMPONENT),
                    data: {
                        change: "addrowafter"
                    }
                }, {
                    text: M.util.get_string("moverowup", COMPONENT),
                    data: {
                        change: "moverowup"
                    }
                }, {
                    text: M.util.get_string("moverowdown", COMPONENT),
                    data: {
                        change: "moverowdown"
                    }
                }, {
                    text: M.util.get_string("movecolumnleft", COMPONENT),
                    data: {
                        change: "movecolumnleft"
                    }
                }, {
                    text: M.util.get_string("movecolumnright", COMPONENT),
                    data: {
                        change: "movecolumnright"
                    }
                }, {
                    text: M.util.get_string("deleterow", COMPONENT),
                    data: {
                        change: "deleterow"
                    }
                }, {
                    text: M.util.get_string("deletecolumn", COMPONENT),
                    data: {
                        change: "deletecolumn"
                    }
                }, {
                    text: M.util.get_string("edittable", COMPONENT),
                    data: {
                        change: "edittable"
                    }
                }
            ];

            this._contextMenu = new Y.M.editor_atto.Menu({
                items: this._menuOptions
            });

            // Add event handlers for table control menus.
            boundingBox = this._contextMenu.get('boundingBox');
            boundingBox.delegate('click', this._handleTableChange, 'a', this);
        }

        boundingBox = this._contextMenu.get('boundingBox');

        // We store the cell of the last click (the control node is transient).
        this._lastTarget = e.tableCell.ancestor('.editor_atto_content td, .editor_atto_content th', true);

        this._hideInvalidEntries(boundingBox);

        // Clear the focusAfterHide for any other menus which may be open.
        Y.Array.each(this.get('host').openMenus, function(menu) {
            menu.set('focusAfterHide', null);
        });

        // Ensure that we focus on the button in the toolbar when we tab back to the menu.
        var creatorButton = this.buttons[this.name];
        this.get('host')._setTabFocus(creatorButton);

        // Show the context menu, and align to the current position.
        this._contextMenu.show();
        this._contextMenu.align(this.buttons.table, [Y.WidgetPositionAlign.TL, Y.WidgetPositionAlign.BL]);
        this._contextMenu.set('focusAfterHide', creatorButton);

        // If there are any anchors in the bounding box, focus on the first.
        if (boundingBox.one('a')) {
            boundingBox.one('a').focus();
        }

        // Add this menu to the list of open menus.
        this.get('host').openMenus = [this._contextMenu];
    },

    /**
     * Handle a selection from the table control menu.
     *
     * @method _handleTableChange
     * @param {EventFacade} e
     * @private
     */
    _handleTableChange: function(e) {
        e.preventDefault();

        this._contextMenu.set('focusAfterHide', this.get('host').editor);
        // Hide the context menu.
        this._contextMenu.hide(e);

        // Make our changes.
        switch (e.target.getData('change')) {
            case 'addcolumnafter':
                this._addColumnAfter();
                break;
            case 'addrowafter':
                this._addRowAfter();
                break;
            case 'deleterow':
                this._deleteRow();
                break;
            case 'deletecolumn':
                this._deleteColumn();
                break;
            case 'edittable':
                this._editTable();
                break;
            case 'moverowdown':
                this._moveRowDown();
                break;
            case 'moverowup':
                this._moveRowUp();
                break;
            case 'movecolumnleft':
                this._moveColumnLeft();
                break;
            case 'movecolumnright':
                this._moveColumnRight();
                break;
        }
    },

    /**
     * Determine the index of a row in a table column.
     *
     * @method _getRowIndex
     * @param {Node} cell
     * @private
     */
    _getRowIndex: function(cell) {
        var tablenode = cell.ancestor('table'),
            rownode = cell.ancestor('tr');

        if (!tablenode || !rownode) {
            return;
        }

        var rows = tablenode.all('tr');

        return rows.indexOf(rownode);
    },

    /**
     * Determine the index of a column in a table row.
     *
     * @method _getColumnIndex
     * @param {Node} cellnode
     * @private
     */
    _getColumnIndex: function(cellnode) {
        var rownode = cellnode.ancestor('tr');

        if (!rownode) {
            return;
        }

        var cells = rownode.all('td, th');

        return cells.indexOf(cellnode);
    },

    /**
     * Delete the current row.
     *
     * @method _deleteRow
     * @private
     */
    _deleteRow: function() {
        var row = this._lastTarget.ancestor('tr');

        if (row && row.one('td')) {
            // Only delete rows with at least one non-header cell.
            row.remove(true);
        }

        // Clean the HTML.
        this.markUpdated();
    },

    /**
     * Move row up
     *
     * @method _moveRowUp
     * @private
     */
    _moveRowUp: function() {
        var row = this._lastTarget.ancestor('tr'),
            prevrow = row.previous('tr');
        if (!row || !prevrow) {
            return;
        }

        row.swap(prevrow);
        // Clean the HTML.
        this.markUpdated();
    },

    /**
     * Move column left
     *
     * @method _moveColumnLeft
     * @private
     */
    _moveColumnLeft: function() {
        var cells = this._findColumnCells();

        if (cells.current.size() > 0 && cells.prev.size() > 0 && cells.current.size() === cells.prev.size()) {
            var i = 0;
            for (i = 0; i < cells.current.size(); i++) {
                var cell = cells.current.item(i),
                    prevcell = cells.prev.item(i);

                cell.swap(prevcell);
            }
        }
        // Cleanup.
        this.markUpdated();
    },

    /**
     * Add a caption to the table if it doesn't have one.
     *
     * @method _addCaption
     * @private
     */
    _addCaption: function() {
        var table = this._lastTarget.ancestor('table'),
            caption = table.one('caption');

        if (!caption) {
            table.insert(Y.Node.create('

'), 1);
        }
    },

    /**
     * Remove a caption from the table if has one.
     *
     * @method _removeCaption
     * @private
     */
    _removeCaption: function() {
        var table = this._lastTarget.ancestor('table'),
            caption = table.one('caption');

        if (caption) {
            caption.remove(true);
        }
    },

    /**
     * Move column right.
     *
     * @method _moveColumnRight
     * @private
     */
    _moveColumnRight: function() {
        var cells = this._findColumnCells();

        // Check we have some tds in this column, and one exists to the right.
        if ( (cells.next.size() > 0) &&
                (cells.current.size() === cells.next.size()) &&
                (cells.current.filter('td').size() > 0)) {
            var i = 0;
            for (i = 0; i < cells.current.size(); i++) {
                var cell = cells.current.item(i),
                    nextcell = cells.next.item(i);

                cell.swap(nextcell);
            }
        }
        // Cleanup.
        this.markUpdated();
    },

    /**
     * Move row down.
     *
     * @method _moveRowDown
     * @private
     */
    _moveRowDown: function() {
        var row = this._lastTarget.ancestor('tr'),
            nextrow = row.next('tr');
        if (!row || !nextrow || !row.one('td')) {
            return;
        }

        row.swap(nextrow);
        // Clean the HTML.
        this.markUpdated();
    },

    /**
     * Edit table (show the dialogue).
     *
     * @method _editTable
     * @private
     */
    _editTable: function() {
        var dialogue = this.getDialogue({
            headerContent: M.util.get_string('edittable', COMPONENT),
            focusAfterHide: false,
            focusOnShowSelector: SELECTORS.CAPTION
        });

        // Set the dialogue content, and then show the dialogue.
        var node = this._getEditDialogueContent(),
            captioninput = node.one(SELECTORS.CAPTION),
            headersinput = node.one(SELECTORS.HEADERS),
            table = this._lastTarget.ancestor('table'),
            captionnode = table.one('caption');

        if (captionnode) {
            captioninput.set('value', captionnode.getHTML());
        } else {
            captioninput.set('value', '');
        }

        var headersvalue = 'columns';
        if (table.one('th[scope="row"]')) {
            headersvalue = 'rows';
            if (table.one('th[scope="col"]')) {
                headersvalue = 'both';
            }
        }
        headersinput.set('value', headersvalue);
        dialogue.set('bodyContent', node).show();
    },

    /**
     * Delete the current column.
     *
     * @method _deleteColumn
     * @private
     */
    _deleteColumn: function() {
        var columnindex = this._getColumnIndex(this._lastTarget),
            table = this._lastTarget.ancestor('table'),
            rows = table.all('tr'),
            columncells = new Y.NodeList(),
            hastd = false;

        rows.each(function(row) {
            var cells = row.all('td, th');
            var cell = cells.item(columnindex);
            if (cell.get('tagName') === 'TD') {
                hastd = true;
            }
            columncells.push(cell);
        });

        // Do not delete all the headers.
        if (hastd) {
            columncells.remove(true);
        }

        // Clean the HTML.
        this.markUpdated();
    },

    /**
     * Add a row after the current row.
     *
     * @method _addRowAfter
     * @private
     */
    _addRowAfter: function() {
        var rowindex = this._getRowIndex(this._lastTarget);

        var tablebody = this._lastTarget.ancestor('table').one('tbody');
        if (!tablebody) {
            // Not all tables have tbody.
            tablebody = this._lastTarget.ancestor('table');
            rowindex += 1;
        }

        var firstrow = tablebody.one('tr');
        if (!firstrow) {
            firstrow = this._lastTarget.ancestor('table').one('tr');
        }
        if (!firstrow) {
            // Table has no rows. Boo.
            return;
        }
        var newrow = firstrow.cloneNode(true);
        newrow.all('th, td').each(function (tablecell) {
            if (tablecell.get('tagName') === 'TH') {
                if (tablecell.getAttribute('scope') !== 'row') {
                    var newcell = Y.Node.create('	');
                    tablecell.replace(newcell);
                    tablecell = newcell;
                }
            }
            tablecell.setHTML(' ');
        });

        tablebody.insert(newrow, rowindex);

        // Clean the HTML.
        this.markUpdated();
    },

    /**
     * Add a column after the current column.
     *
     * @method _addColumnAfter
     * @private
     */
    _addColumnAfter: function() {
        var cells = this._findColumnCells(),
            before = true,
            clonecells = cells.next;
        if (cells.next.size() <= 0) {
            before = false;
            clonecells = cells.current;
        }

        Y.each(clonecells, function(cell) {
            var newcell = cell.cloneNode();
            // Clear the content of the cell.
            newcell.setHTML(' ');

            if (before) {
                cell.get('parentNode').insert(newcell, cell);
            } else {
                cell.get('parentNode').insert(newcell, cell);
                cell.swap(newcell);
            }
        }, this);

        // Clean the HTML.
        this.markUpdated();
    }

});


text:
layout: archive
permalink: /writing/
title: "Things I've Written Down"
author_profile: false
---

{% include base_path %}
{% capture written_year %}'None'{% endcapture %}
{% for post in site.posts %}
    {% if post.categories contains 'writing' %}
        {% capture year %}{{ post.date | date: '%Y' }}{% endcapture %}
        {% if year != written_year %}

{{ year }}

        {% capture written_year %}{{ year }}{% endcapture %}
        {% endif %}
        {% include archive-single.html %}
    {% endif %}
{% endfor %}


text:
package org.apache.flink.metrics.prometheus;

import org.apache.flink.util.TestLogger;

import org.junit.Assert;
import org.junit.Test;

import java.util.Map;

/**
 * Test for {@link PrometheusPushGatewayReporter}.
 */
public class PrometheusPushGatewayReporterTest extends TestLogger {

	@Test
	public void testParseGroupingKey() {
		PrometheusPushGatewayReporter reporter = new PrometheusPushGatewayReporter();
		Map<String, String> groupingKey = reporter.parseGroupingKey("k1=v1;k2=v2");
		Assert.assertNotNull(groupingKey);
		Assert.assertEquals("v1", groupingKey.get("k1"));
		Assert.assertEquals("v2", groupingKey.get("k2"));
	}

	@Test
	public void testParseIncompleteGroupingKey() {
		PrometheusPushGatewayReporter reporter = new PrometheusPushGatewayReporter();
		Map<String, String> groupingKey = reporter.parseGroupingKey("k1=");
		Assert.assertTrue(groupingKey.isEmpty());

		groupingKey = reporter.parseGroupingKey("=v1");
		Assert.assertTrue(groupingKey.isEmpty());

		groupingKey = reporter.parseGroupingKey("k1");
		Assert.assertTrue(groupingKey.isEmpty());
	}
}


text:
<?php

/**
 * DmSentMail
 *
 * This class has been auto-generated by the Doctrine ORM Framework
 *
 * @package    diem-ipsum
 * @subpackage model
 * @author     Your name here
 * @version    SVN: $Id: Builder.php 7490 2010-03-29 19:53:27Z jwage $
 */
class DmSentMail extends PluginDmSentMail
{
}


text:
package com.basho.riak.client.api.cap;

import java.util.List;

/**
 * Interface used to resolve siblings.
 *

 * When you have multiple writers there may be multiple versions of the same
 * object stored in Riak. When fetching all of these will be returned and you
 * will need to resolve the conflict.
 *

 *

 * To facilitate this, you can store an instance of the ConflictResolver
 * in the {@link com.basho.riak.client.api.cap.ConflictResolverFactory} for a class.
 * It will then be used by the {@link com.basho.riak.client.api.commands.kv.FetchValue.Response}
 * to resolve a set a of siblings to a single object.
 *

 * @author Brian Roach <roach at basho dot com>
 * @since 2.0
 * @param <T> The type of the objects to be resolved.
 */
public interface ConflictResolver<T>
{
    T resolve(List<T> objectList) throws UnresolvedConflictException;
}


text:
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!

#include "config.h"
#include "WheelEventInit.h"

namespace blink {

WheelEventInit::WheelEventInit()
{
    setDeltaMode(0u);
    setDeltaX(0);
    setDeltaY(0);
    setDeltaZ(0);
    setWheelDeltaX(0);
    setWheelDeltaY(0);
}

DEFINE_TRACE(WheelEventInit)
{
    MouseEventInit::trace(visitor);
}

} // namespace blink


text:
namespace app { namespace Fuse { namespace Triggers { struct State; } } }

namespace app {
namespace Outracks {
namespace Simulator {
namespace Runtime {

struct UxProperty__Fuse_Triggers_State;

struct UxProperty__Fuse_Triggers_State__uType : ::app::Uno::UX::Property__Fuse_Triggers_State__uType
{
};

UxProperty__Fuse_Triggers_State__uType* UxProperty__Fuse_Triggers_State__typeof();

void UxProperty__Fuse_Triggers_State___ObjInit_1(UxProperty__Fuse_Triggers_State* __this, ::uDelegate* setter, ::uDelegate* getter, ::uDelegate* adder, ::uDelegate* remover);
UxProperty__Fuse_Triggers_State* UxProperty__Fuse_Triggers_State__New_1(::uStatic* __this, ::uDelegate* setter, ::uDelegate* getter, ::uDelegate* adder, ::uDelegate* remover);
void UxProperty__Fuse_Triggers_State__OnAddListener(UxProperty__Fuse_Triggers_State* __this, ::uDelegate* listener);
::app::Fuse::Triggers::State* UxProperty__Fuse_Triggers_State__OnGet(UxProperty__Fuse_Triggers_State* __this);
void UxProperty__Fuse_Triggers_State__OnRemoveListener(UxProperty__Fuse_Triggers_State* __this, ::uDelegate* listener);
void UxProperty__Fuse_Triggers_State__OnSet(UxProperty__Fuse_Triggers_State* __this, ::app::Fuse::Triggers::State* value, ::uObject* origin);

struct UxProperty__Fuse_Triggers_State : ::app::Uno::UX::Property__Fuse_Triggers_State
{
    ::uStrong< ::uDelegate*> _setter;
    ::uStrong< ::uDelegate*> _getter;
    ::uStrong< ::uDelegate*> _adder;
    ::uStrong< ::uDelegate*> _remover;

    void _ObjInit_1(::uDelegate* setter, ::uDelegate* getter, ::uDelegate* adder, ::uDelegate* remover) { UxProperty__Fuse_Triggers_State___ObjInit_1(this, setter, getter, adder, remover); }
};

}}}}

#endif


text:
#region Copyright (c) 2017 Leoxia Ltd

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LineExtensions.cs" company="Leoxia Ltd">
//    Copyright (c) 2017 Leoxia Ltd
// </copyright>
//
// .NET Software Development
// https://www.leoxia.com
// Build. Tomorrow. Together
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//  --------------------------------------------------------------------------------------------------------------------

#endregion

#region Usings

using System;
using System.Collections.Generic;

#endregion

namespace Leoxia.Text.Extensions
{
    /// <summary>
    ///     Lines related methods
    /// </summary>
    public static class LineExtensions
    {
        /// <summary>
        ///     Splits the input in lines.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static string[] SplitInLines(this string input)
        {
            var res = input.Replace("\r\n", "\f");
            return res.Split('\f', '\n', '\r');
        }

        /// <summary>
        ///     Joins the input lines in a text where lines are separated by new line character.
        /// </summary>
        /// <param name="lines">The lines.</param>
        /// <returns></returns>
        public static string JoinLines(this IEnumerable<string> lines)
        {
            return string.Join(Environment.NewLine, lines);
        }
    }
}


text:
const breadcrumbs = require('../breadcrumbs')

describe('breadcrumbs middleware', () => {
  beforeEach(() => {
    this.nextSpy = sinon.spy()
    this.resMock = {}
  })

  describe('init()', () => {
    beforeEach(() => {
      this.init = breadcrumbs.init()
    })

    it('should attach a method to the response object', () => {
      this.init({}, this.resMock, this.nextSpy)

      expect(this.resMock).to.have.property('breadcrumb')
      expect(this.resMock.breadcrumb).to.be.a('function')
      expect(this.nextSpy.calledOnce).to.be.true
    })
  })

  describe('res.breadcrumb()', () => {
    beforeEach(() => {
      this.init({}, this.resMock, this.nextSpy)
    })

    describe('when called with no arguments', () => {
      it('should return the breadcrumb', () => {
        expect(this.resMock.breadcrumb()).to.deep.equal([])
      })
    })

    describe('when called with 1 argument', () => {
      it('should set name', () => {
        this.resMock.breadcrumb('Name')

        expect(this.resMock.breadcrumb()).to.deep.equal([
          {
            text: 'Name',
          },
        ])
      })
    })

    describe('when called with 2 arguments', () => {
      it('should set url and name', () => {
        this.resMock.breadcrumb('Name', '/sample-url')

        expect(this.resMock.breadcrumb()).to.deep.equal([
          {
            text: 'Name',
            href: '/sample-url',
          },
        ])
      })
    })

    describe('when called with an object', () => {
      it('should add the object to breadcrumb', () => {
        this.resMock.breadcrumb({
          text: 'Name',
          href: '/sample-url',
        })

        expect(this.resMock.breadcrumb()).to.deep.equal([
          {
            text: 'Name',
            href: '/sample-url',
          },
        ])
      })
    })

    describe('when called with an array of objects', () => {
      it('should add each object to breadcrumb', () => {
        this.resMock.breadcrumb([
          {
            name: 'First item',
            url: '/first-item',
          },
          {
            name: 'Second item',
            url: '/second-item',
          },
        ])

        expect(this.resMock.breadcrumb()).to.deep.equal([
          {
            name: 'First item',
            url: '/first-item',
          },
          {
            name: 'Second item',
            url: '/second-item',
          },
        ])
      })
    })
  })

  describe('res.removeBreadcrumb()', () => {
    describe('when removing last breadcrumb item', () => {
      beforeEach(() => {
        this.init({}, this.resMock, this.nextSpy)

        this.resMock.breadcrumb('Item one')
        this.resMock.breadcrumb('Item two')
        this.resMock.breadcrumb('Item three')

        this.resMock.removeBreadcrumb()
      })

      it('should only contain two items', () => {
        expect(this.resMock.breadcrumb()).to.have.length(2)
      })

      it('should only contain the correct items', () => {
        expect(this.resMock.breadcrumb()).to.deep.equal([
          { text: 'Item one' },
          { text: 'Item two' },
        ])
      })
    })

    describe('when breadcrumb middle breadcrumb items', () => {
      beforeEach(() => {
        this.init({}, this.resMock, this.nextSpy)

        this.resMock.breadcrumb('Item one')
        this.resMock.breadcrumb('Item two')
        this.resMock.breadcrumb('Item three')

        this.resMock.removeBreadcrumb()

        this.resMock.breadcrumb('Item four')
      })

      it('should only contain three items', () => {
        expect(this.resMock.breadcrumb()).to.have.length(3)
      })

      it('should only contain the correct items', () => {
        expect(this.resMock.breadcrumb()).to.deep.equal([
          { text: 'Item one' },
          { text: 'Item two' },
          { text: 'Item four' },
        ])
      })
    })
  })

  describe('setHome()', () => {
    beforeEach(() => {
      this.init = breadcrumbs.init()
      this.init({}, this.resMock, sinon.spy())

      this.setHome = breadcrumbs.setHome
    })

    describe('when called with no arguments', () => {
      beforeEach(() => {
        this.setHome()({}, this.resMock, this.nextSpy)
      })

      it('should set a default value for the home item', () => {
        expect(this.nextSpy.calledOnce).to.be.true
        expect(this.resMock.breadcrumb()).to.deep.equal([
          {
            text: 'Home',
            href: '/',
            _home: true,
          },
        ])
      })
    })

    describe('when called with an object', () => {
      beforeEach(() => {
        this.setHome({
          text: 'Root',
          href: '/root',
        })({}, this.resMock, this.nextSpy)
      })

      it('should set the object as the home item', () => {
        expect(this.nextSpy.calledOnce).to.be.true
        expect(this.resMock.breadcrumb()).to.deep.equal([
          {
            text: 'Root',
            href: '/root',
            _home: true,
          },
        ])
      })
    })

    describe('when home is already set', () => {
      beforeEach(() => {
        this.setHome()({}, this.resMock, this.nextSpy)
      })

      it('should update the home item', () => {
        this.setHome({
          text: 'Root',
          href: '/root',
        })({}, this.resMock, this.nextSpy)

        expect(this.nextSpy.calledTwice).to.be.true
        expect(this.resMock.breadcrumb()).to.deep.equal([
          {
            text: 'Root',
            href: '/root',
            _home: true,
          },
        ])
      })
    })
  })
})


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
J-Index
</TITLE>

<META NAME="date" CONTENT="2009-09-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E G H I J L M N O P R S T U V W _

J

japLang -
Variable in class gui.CalendarFrame

japLangIdx -
Variable in class gui.CalendarFrame

jButtonGroupLanguage -
Variable in class gui.CalendarFrame

jButtonRemoveContext -
Variable in class gui.CalendarPanel

jButtonStartRecognition -
Variable in class gui.CalendarPanel

jListHelp -
Variable in class gui.CalendarPanel

jMenuHelp -
Variable in class gui.CalendarFrame

jMenuItemHelpAbout -
Variable in class gui.CalendarFrame

jMenuLanguage -
Variable in class gui.CalendarFrame

jMenuView -
Variable in class gui.CalendarFrame

jPanelButtons -
Variable in class gui.CalendarPanel

jPanelResults -
Variable in class gui.CalendarPanel

jScrollPaneAnswer -
Variable in class gui.CalendarPanel

jScrollPaneDialContext -
Variable in class gui.CalendarPanel

jScrollPaneHelpSystem -
Variable in class gui.CalendarPanel

jScrollPaneRawRecRes -
Variable in class gui.CalendarPanel

jTableColumnScore -
Variable in class gui.CalendarPanel

jTableColumnTrans -
Variable in class gui.CalendarPanel

jTableColumnValue -
Variable in class gui.CalendarPanel

jTableRawRecRes -
Variable in class gui.CalendarPanel

jTextAreaDialHistory -
Variable in class gui.CalendarPanel

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E G H I J L M N O P R S T U V W _