text:
#import "TimelineViewController.h"
#import "AssetMO.h"
#import "ModelAccess.h"
#import "NSArrayController_ObjectExchange.h"
#import "NSTreeController+NSMAdditions.h"
#import "StageEditorViewController.h"

@implementation TimelineViewController

@synthesize deleteButton=_deleteButton,
			treeController=_treeController,
			sceneViewController = _sceneViewController,
			assetEditor = _assetEditor,
			splitView = _splitView;

#pragma mark -
#pragma mark Initialization & Deallocation

#define MODEL_KEYPATH(base, rest) GENERIC_MODEL_KEYPATH(@"representedObject", (base), (rest))
#define MODEL_ACCESS(base, rest)  [self valueForKeyPath: MODEL_KEYPATH((base), (rest))]

- (id)init{
	if ((self = [super initWithNibName:@"TimelineView" bundle:nil])){
	}
	return self;
}

- (void)dealloc{
	[self setModelAccessObservingState: NO];
	[_sceneViewController release];
	[_treeController release];
	[_assetEditor release];
	[_splitView release];
	[super dealloc];
}

- (TimelineView*)timeline {
	return (TimelineView*)self.view;
}

#pragma mark -
#pragma mark datasource methods

- (NSUInteger)numberOfLayersInTimeline:(TimelineView *)timeline {
	NSUInteger count = 0;
	NSInteger row = 0;
	NSOutlineView *outlineView = [[self timeline] layerOutlineView];
	id rootNode = [self.treeController arrangedObjects];
	for (id node in [rootNode childNodes]) {
		BOOL expanded = [self.timeline isItemExpanded:node];
		count++;
		if (expanded) count += [[node childNodes] count];
		row = [outlineView rowForItem:node];
		count = fmax(count, row);
	}
	return fmax(0, count);
}

- (id)timeline:(TimelineView *)timeline itemForLayerAtIndex:(NSInteger)layerIndex {
	NSUInteger idx = 0;
	id rootNode = [self.treeController arrangedObjects];

	for (id node in [rootNode childNodes]) {
		if (idx==layerIndex) return [node representedObject];
		BOOL expanded = [self.timeline isItemExpanded:node];
		if (expanded == YES) {
			for (id child in [node childNodes]) {
				idx++;
				if (idx==layerIndex) return [child representedObject];
			}
		}
		idx++;
	}
	return nil;
}

- (NSUInteger)timeline:(TimelineView *)timeline firstFrameIndexInLayerWithIndex:(NSUInteger)layerIndex{
	NSRange range = [[self timeline:self.timeline itemForLayerAtIndex:layerIndex] range];
	return range.location;
}

- (NSUInteger)timeline:(TimelineView *)timeline numberOfFramesInLayerWithIndex:(NSUInteger)layerIndex{
	NSRange range = [[self timeline:timeline itemForLayerAtIndex:layerIndex] range];
	return range.length;
}

- (void)timeline:(TimelineView *)timeline setTitleOfLayer:(NSString *)newName atIndex:(NSInteger)layerIndex{
	AssetMO *asset = [self timeline:timeline itemForLayerAtIndex:layerIndex];
	asset.name = newName;
}

- (NSUInteger)timeline:(TimelineView *)timeline loopValueForLayerAtIndex:(NSInteger)layerIndex {
	AssetMO *asset = [self timeline:timeline itemForLayerAtIndex: layerIndex];
	NSUInteger loopValue = [asset.keyframeAnimation.loop unsignedIntValue];
	return loopValue;
}

- (BOOL)timeline:(TimelineView *)timeline layerAtIndexIsVisible:(NSInteger)layerIndex {
	AssetMO *asset = [self timeline:timeline itemForLayerAtIndex: layerIndex];
	NSNumber *hidden = [asset valueForKey: @"hidden"];
	BOOL isVisible = ! [hidden boolValue];
	return isVisible;
}

- (BOOL)frameAtIndexPathIsKeyframe:(NSIndexPath *)indexPath{
	AssetMO *asset = [self timeline:nil itemForLayerAtIndex:[indexPath layer]];
	NSIndexSet *keyframes = asset.keyframes;
	return [keyframes containsIndex:[indexPath frame]];
}

- (KeyframeMO *) keyframeForFrameIndex: (NSInteger) frameIndex inLayer: (NSInteger) layerIndex {
	AssetMO *asset = [self timeline:nil itemForLayerAtIndex:layerIndex];
	return [asset.keyframeAnimation keyframeForTime: [NSNumber numberWithInteger: frameIndex]];
}

- (KeyframeMO *) keyframeForIndexPath: (NSIndexPath *) indexPath {
	return [self keyframeForFrameIndex: [indexPath frame] inLayer: [indexPath layer]];
}

#pragma mark -
#pragma mark observing methods for TimelineGridView

- (void) assets: (NSArray *) assets didChange: (NSDictionary *) change {
	//NDCLog(@"assets: %ld change: %@", (long)[assets count], [change valueForKey: NSKeyValueChangeKindKey]);
	//NSLog(@"asset count: %d", [assets count]);

	SceneMO *scene = [[assets lastObject] scene];

	NSPredicate *fetchPredicate = [NSPredicate predicateWithFormat:@"(scene == %@) AND (parent == nil)", scene];
	[self.treeController setFetchPredicate:fetchPredicate];

	id gridView = [[self timeline] gridView];
	id outlineView = [[self timeline] layerOutlineView];

	[gridView performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
	[outlineView performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
}

- (NSTreeNode *)treeNodeForItem:(id)item rootNode:(id)rootNode {
	id obj = [rootNode representedObject];
	if (obj == item) return rootNode;
	for (id child in [rootNode childNodes]) {
		return [self treeNodeForItem:item rootNode:child];
	}
	return nil;
}

//- (NSPredicate*)parentAssetsOnlyFilterPredicate {
//	return [NSPredicate predicateWithFormat:@"parent == nil"];
//}

- (void) selectedAssets: (NSArray *) selectedAssets didChange: (NSDictionary *) change {
	[[NSNotificationCenter defaultCenter] removeObserver:[self timeline]
													name:NSOutlineViewSelectionDidChangeNotification object:[[self timeline] layerOutlineView]];
	//NDCLog(@"selectedAssets: %ld change: %@", (long)[selectedAssets count], [change valueForKey: NSKeyValueChangeKindKey]);
	NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
		for (id selectedAsset in selectedAssets) {
			NSIndexPath *indexPath = [self.treeController indexPathForObject:selectedAsset];
			if (indexPath) {
				[indexPaths addObject:indexPath];
			}
		}

	[self.treeController setSelectionIndexPaths:indexPaths];
	[[NSNotificationCenter defaultCenter] addObserver:[self timeline]
											 selector:@selector(layerOutlineViewSelectionDidChange:)
												 name:NSOutlineViewSelectionDidChangeNotification object:[[self timeline] layerOutlineView]];
	[[[self timeline] layerOutlineView] reloadData];
	[[[self timeline] gridView] reloadData];
	[indexPaths release];
}

- (void) assetsParent: (NSArray *) assetsParent didChange: (NSDictionary *) change {
	[[self treeController] rearrangeObjects];
	[[[self timeline] gridView] reloadData];
}

- (void) assetsHidden: (NSArray *) assetsHidden didChange: (NSDictionary *) change {
	[[[self timeline] gridView] reloadData];
}

- (void) coalescedUnionOfSceneKeyframesTimeDidChange
{
	lptrace();
	[[[self timeline] gridView] reloadData];
}

- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
	// non-magic - comes from ModelAccess.m - calls selectors like [self selectedAssets:newValue didChange: changeDict]
	if( NO == [self processModelAccessObservationForKeyPath: keyPath ofObject:object change:change context:context] ) {
		[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
	}
}

- (void)loadView {
	[super loadView];
	//[_treeController setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"viewPosition" ascending:YES]]];
}

- (void)awakeFromNib {
	[self setModelAccessObservingState: YES];
}

#pragma mark -
#pragma mark outlineView delegate methods

- (void)outlineViewItemDidExpand:(NSNotification *)notification {
	[[[self timeline] gridView] reloadData];
}

- (void)outlineViewItemDidCollapse:(NSNotification *)notification {
	[[[self timeline] gridView] reloadData];
}

#pragma mark -
#pragma mark timelineview delegate methods

- (void)timeline:(TimelineView *)timeline willDisplayCell:(NSCell *)cell inLayer:(NSUInteger)layerIndex frame:(NSUInteger)frameIndex{
	NSRange range = [[self timeline:timeline itemForLayerAtIndex:layerIndex] range];

	TimelineFrameCell *timelineCell = (TimelineFrameCell *)cell;

	if (range.length == 1){
		timelineCell.framePosition = kFramePositionSingle;
	}else{
		if (frameIndex == range.location){
			timelineCell.framePosition = kFramePositionLeft;
			timelineCell.keyframe = YES;
		}else if (frameIndex == range.location + range.length - 1){
			timelineCell.framePosition = kFramePositionRight;
			timelineCell.keyframe = YES;
		}else{
			timelineCell.framePosition = kFramePositionMiddle;
			timelineCell.keyframe = NO;
		}
	}

	if (timeline.isDraggingLayers &&
		[timeline.draggedLayers containsObject:[NSNumber numberWithInt:layerIndex]]) {
		timelineCell.enclosingLayerIsDragged = YES;
	} else {
		timelineCell.enclosingLayerIsDragged = NO;
	}

	AssetMO *asset = [self timeline:timeline itemForLayerAtIndex:layerIndex];

	[timelineCell setEnabled: [asset keyFramesEditable]];

	NSMutableIndexSet *set = [asset keyframes];
	if ([set containsIndex:frameIndex]){
		timelineCell.keyframe = YES;
	}
}

- (void)timeline:(TimelineView *)timeline didDoubleClickFrame:(NSUInteger)frameIndex inLayer:(NSUInteger)layerIndex {
	NDCLog(@"frame index: %d", frameIndex);
	AssetMO *asset = [self timeline:timeline itemForLayerAtIndex:layerIndex];
	if (![asset keyFramesEditable]) {
		NSBeep();
		return;
	}
	[asset.keyframeAnimation ensureKeyframeForTime: [NSNumber numberWithInteger: frameIndex]];
	[[[self timeline] gridView] reloadData];
}

- (void)timeline:(TimelineView *)timeline didChangeLoopValue:(NSUInteger)loopValue forLayerAtIndex:(NSUInteger)index {
	AssetMO *asset = [self timeline:timeline itemForLayerAtIndex:index];
	asset.keyframeAnimation.loop = [NSNumber numberWithUnsignedInt:loopValue];
}

- (void)timeline:(TimelineView *)timeline didSeekToFrame:(NSUInteger)frameIndex {
	NSNumber *theTime = [NSNumber numberWithInteger: frameIndex];
	[self.sceneViewController setCurrentTime: theTime];
	self.assetEditor.currentTime = theTime;
	AssetMO *asset = MODEL_ACCESS(kModelAccessAssetSelectionKeyPath, @"self");
	if( nil != asset && NO == NSIsControllerMarker(asset) ) {
		KeyframeMO *keyframe = [asset.keyframeAnimation keyframeForTime: theTime];
		NSArrayController *arrayController = MODEL_ACCESS(kModelAccessKeyframeArrayControllerKeyPath, nil);
		[arrayController setSelectedObjects: keyframe == nil ? [NSArray array] : [NSArray arrayWithObject: keyframe]];
	}
}
/*
- (BOOL) timeline:(TimelineView *)timeline layerAtIndex: (NSInteger)layerIndex shouldBecomeVisible: (BOOL) visibility {
	NSNumber *hidden = [NSNumber numberWithBool: ! visibility];
	AssetMO *asset = [self timeline:timeline itemForLayerAtIndex: layerIndex];
	[asset setValue: hidden forKey: @"hidden"];
	return YES;
}*/

- (NSArray *)timeline:(TimelineView *)timeline draggableFramesAtIndexPaths:(NSArray *)indexPaths{
	#ifdef MULTIPLE_FRAME_DRAG
	return YES;
	#endif

	__block BOOL (^isKeyFrame)(NSInteger, AssetMO *) = 	^(NSInteger frame, AssetMO *asset){
		NSRange range = [asset range];
		NSIndexSet *keyframes = [asset keyframes];
		if (frame != range.location &&
			frame != NSMaxRange(range) - 1 &&
			![keyframes containsIndex:frame]){
			return NO;
		}
		return YES;
	};

	NSMutableArray *draggableFrames = [NSMutableArray array];
	for (NSIndexPath *indexPath in indexPaths){
		AssetMO *asset = [self timeline:timeline itemForLayerAtIndex:[indexPath layer]];
		if (isKeyFrame([indexPath frame], asset)){
			[draggableFrames addObject:indexPath];
		}
	}
	return draggableFrames;
}

- (NSIndexPath *)timeline:(TimelineView *)timeline
validateFrameDropPosition:(NSIndexPath *)dropPosition
	  frameSourcePosition:(NSIndexPath *)sourcePosition{
	return [NSIndexPath indexPathForFrame:[dropPosition frame] inLayer:[sourcePosition layer]];
}

- (void)timeline:(TimelineView *)timeline performFrameDrop:(NSIndexPath *)dropPosition sourcePosition:(NSIndexPath *)sourcePosition{

	AssetMO *asset = [self timeline:timeline itemForLayerAtIndex:[dropPosition layer]];

	if (![asset keyFramesEditable]) {
		NSBeep();
		return;
	}

	NSIndexSet *keyframes = [asset keyframes];

	KeyframeMO *keyframe = [self keyframeForIndexPath: sourcePosition];
	AssetMO *layer = [self timeline:[self timeline] itemForLayerAtIndex:[dropPosition layer]];
	if (nil != keyframe) {
		// if a keyframe already exists at the drop position, replace it
		if ([keyframes containsIndex:[dropPosition frame]]){
			[[layer.keyframeAnimation mutableSetValueForKey: @"keyframes"]
			 removeObject:[layer.keyframeAnimation keyframeForTime:
						   [NSNumber numberWithInt:[dropPosition frame]]]];
		}
		keyframe.time = [NSNumber numberWithInteger: [dropPosition frame]];
	} else {
		NSLog(@"%@ ALERT !!! Hell freezing over - received drop for non-existing sourcePosition: %@", [self class], sourcePosition);
	}

	[[[self timeline] gridView] reloadData];
	[[NSNotificationCenter defaultCenter] postNotificationName:	kModelAccessPropertiesAffectedNotification object: keyframe];
}

- (BOOL)timeline:(TimelineView *)timeline performLayerDropAtIndex:(NSInteger)layerIndex
	toFrameIndex:(NSInteger)firstFrameIndex{

	AssetMO *asset = [self timeline:timeline itemForLayerAtIndex:layerIndex];

	NSRange formerRange = [asset range];
	NSInteger diff = firstFrameIndex - formerRange.location;
	NSArray *orderedKeyframes = [asset valueForKeyPath:@"keyframeAnimation.orderedKeyframes"];
	for (KeyframeMO *keyframe in orderedKeyframes){
		NSInteger formerTime = [keyframe.time integerValue];
		keyframe.time = [NSNumber numberWithInt:formerTime + diff];
	}

	// post global one (object nil)
	[[NSNotificationCenter defaultCenter] postNotificationName:kModelAccessPropertiesAffectedNotification object:nil];

	[[[self timeline] gridView] reloadData];
	return YES;
}

- (BOOL)timeline:(TimelineView *)timeline shouldDeleteLayersAtIndexes:(NSIndexSet *)layerIndexes {
	[layerIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
		AssetMO *asset = [self timeline:timeline itemForLayerAtIndex: idx];
		[MODEL_ACCESS(kModelAccessAssetArrayControllerKeyPath, nil) removeObject: asset];
	}];
	return YES;
}

- (BOOL)timeline:(TimelineView *)timeline shouldDeleteFramesWithIndexPaths:(NSArray *)indexPaths{
	NSMutableDictionary *indexesPerLayer = [NSMutableDictionary dictionary];
	BOOL shiftKeyDown = ([NSEvent modifierFlags] & NSShiftKeyMask) != 0;

	for (NSIndexPath *indexPath in indexPaths){
		NSNumber *key = [NSNumber numberWithInt:[indexPath layer]];
		NSMutableIndexSet *indexSet = [indexesPerLayer objectForKey:key];
		if (!indexSet){
			indexSet = [NSMutableIndexSet indexSet];
			[indexesPerLayer setObject:indexSet forKey:key];
		}
		[indexSet addIndex:[indexPath frame]];
	}
	for (NSNumber *key in indexesPerLayer){
		AssetMO *asset = [self timeline:timeline itemForLayerAtIndex:[key integerValue]];
		NSMutableIndexSet *keyframeIndexes = [asset keyframes];
		NSIndexSet *frames = [indexesPerLayer objectForKey:key];
		NSMutableDictionary *keyframes = [NSMutableDictionary dictionary];
		for (KeyframeMO *keyframe in asset.keyframeAnimation.keyframes){
			[keyframes setObject:keyframe forKey:keyframe.time];
		}

		// decreases position of following keyframes by one
		__block void (^deleteFrameAtIndex)(NSInteger) = ^(NSInteger frame){
			NSInteger nextKeyframe = [keyframeIndexes indexGreaterThanIndex:frame];
			while (nextKeyframe != NSNotFound){
				KeyframeMO *keyframe = [keyframes objectForKey:[NSNumber numberWithInt:nextKeyframe]];
				NSNumber *newTime = [NSNumber numberWithInt:([keyframe.time intValue] - 1)];
				keyframe.time = newTime;
				nextKeyframe = [keyframeIndexes indexGreaterThanIndex:nextKeyframe];
			}
		};

		NSInteger frame = [frames firstIndex];
		while (frame != NSNotFound){
			if ([keyframeIndexes containsIndex:frame]){ // keyframe
				KeyframeMO *keyframe = [keyframes objectForKey:[NSNumber numberWithInt:frame]];
				NSMutableSet *assetKeyframes =
					[NSMutableSet setWithSet:asset.keyframeAnimation.keyframes];
				[assetKeyframes removeObject:keyframe];
				asset.keyframeAnimation.keyframes = assetKeyframes;
				if ([assetKeyframes count] < 1){ // last keyframe was deleted
					// remove layer
					[MODEL_ACCESS(kModelAccessAssetArrayControllerKeyPath, nil) removeObject:asset];
					break;
				}else{
					if (shiftKeyDown) deleteFrameAtIndex(frame);
				}
			}else{ // non-keyframe
				if (shiftKeyDown) deleteFrameAtIndex(frame);
			}
			frame = [frames indexGreaterThanIndex:frame];
		}
	}
	[[[self timeline] gridView] reloadData];
	return YES;
}

- (BOOL)timeline:(TimelineView *)timeline insertLayersFromIndexPaths:(NSArray *)fromIndexPaths  atIndexPaths:(NSArray *)toIndexPaths{

	return NO;
// FIXME
/*	[self setModelAccessObservingState:NO];

	// for now from and toIndexPaths will only have one item - an indexpath which also only has one index
	NSInteger fromIndex = [(NSIndexPath *)[fromIndexPaths objectAtIndex:0] indexAtPosition:0];
	NSInteger toIndex = [(NSIndexPath *)[toIndexPaths objectAtIndex:0] indexAtPosition:0];

	//	AssetMO *asset = [_cachedLayers objectAtIndex:fromIndex];
	AssetMO *asset = [self timeline:timeline itemForLayerAtIndex:fromIndex];
	//	AssetMO *asset = [layerItemVO representedObject];
	NSMutableArray *layers = [_cachedLayers mutableCopy];
	[layers insertObject:layerItemVO atIndex:toIndex];
	if (toIndex < fromIndex){
		fromIndex++;
	}
	[layers removeObjectAtIndex:fromIndex];

	// in theory one could assume that only affected layers need to have their viewPosition updated
	// unfortunately after a PSD import the viewPosition is not neccessarily zero based, nor
	// have layers incremented their viewPosition by 1; thus we normalize the viewPosition here
	NSInteger i = [layers count] - 1;
	for (LayerItemVO *lyr in layers){
		[[lyr representedObject] setViewPosition: [NSNumber numberWithInt:i--]];
	}
	[layers release];

	[self _cacheModelData:YES];
	[self setModelAccessObservingState:YES];
	return YES;*/
}

- (void)timelineLayerSelectionIndexDidChange:(TimelineView *)timeline {
	NSMutableArray *selectedObjects = [NSMutableArray array];
	NSIndexSet *indexes = [[self timeline] selectedLayerListIndexes];
	NSInteger index = [indexes firstIndex];
	while (index != NSNotFound){
		id item = [self timeline:timeline itemForLayerAtIndex:index];
		if (item) {
			[selectedObjects addObject:item];
		}
		index = [indexes indexGreaterThanIndex:index];
	}
	[self setValue:selectedObjects forKeyPath:MODEL_KEYPATH(kModelAccessSelectedAssetsKeyPath, nil)];
}

#pragma mark -
#pragma mark Actions

- (IBAction)removeLayer:(id)sender{
	NSIndexSet *indexes = [[self timeline] selectedLayerListIndexes];
	if (![indexes count]){
		return;
	}
	[self timeline:[self timeline] shouldDeleteLayersAtIndexes:indexes];
}

@end


text: Demo for NSBudapest about IBDesignable and IBInspectable

redpajama_set_name: RedPajamaGithub


text:
"""Config flow for Islamic Prayer Times integration."""
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.core import callback

# pylint: disable=unused-import
from .const import CALC_METHODS, CONF_CALC_METHOD, DEFAULT_CALC_METHOD, DOMAIN, NAME

class IslamicPrayerFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle the Islamic Prayer config flow."""

    VERSION = 1
    CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL

    @staticmethod
    @callback
    def async_get_options_flow(config_entry):
        """Get the options flow for this handler."""
        return IslamicPrayerOptionsFlowHandler(config_entry)

    async def async_step_user(self, user_input=None):
        """Handle a flow initialized by the user."""
        if self._async_current_entries():
            return self.async_abort(reason="single_instance_allowed")

        if user_input is None:
            return self.async_show_form(step_id="user")

        return self.async_create_entry(title=NAME, data=user_input)

    async def async_step_import(self, import_config):
        """Import from config."""
        return await self.async_step_user(user_input=import_config)

class IslamicPrayerOptionsFlowHandler(config_entries.OptionsFlow):
    """Handle Islamic Prayer client options."""

    def __init__(self, config_entry):
        """Initialize options flow."""
        self.config_entry = config_entry

    async def async_step_init(self, user_input=None):
        """Manage options."""
        if user_input is not None:
            return self.async_create_entry(title="", data=user_input)

        options = {
            vol.Optional(
                CONF_CALC_METHOD,
                default=self.config_entry.options.get(
                    CONF_CALC_METHOD, DEFAULT_CALC_METHOD
                ),
            ): vol.In(CALC_METHODS)
        }

        return self.async_show_form(step_id="init", data_schema=vol.Schema(options))


text:
package ru.job4j.generic;

/**
 * Абстрактный класс описывающий магазин.
 * @author agavrikov
 * @since 21.07.2017
 * @version 1
 */
abstract public class SimpleStore<T extends Base> implements Store<T> {
    /**
     * Поле для хранения структуры - списка пользователей.
     */
    private SimpleArray<T> array;

    /**
     * Конструктор для инициализации.
     * @param size размер хранилища.
     */
    public SimpleStore(int size) {
        this.array = new SimpleArray<T>(size);
    }

    /**
     * геттер хранилища.
     * @return хранилище пользователей.
     */
    public SimpleArray<T> getArray() {
        return this.array;
    }

    /**
     * Метод для добавления элемента.
     *
     * @param value значение элемента
     */
    @Override
    public void add(T value) {
        this.array.add(value);
    }

    /**
     * метод для изменения элемента.
     *
     * @param elem
     * @param value элементкоторым заменяем текущий элемент.
     * @elem элемент, который нужно изменить.
     */
    @Override
    public void update(T elem, T value) {
        this.array.update(this.array.findIndexByObject(elem), value);
    }

    /**
     * Метод для удаления элемента.
     *
     * @param value элемент, который нужно удалить
     */
    @Override
    public void delete(T value) {
        this.array.delete(this.array.findIndexByObject(value));
    }
}


text:
Roo is available here and on Rubyforge. You can install the official release with 'gem install roo' or refer to the installation instructions below for the latest development gem.

## Installation

    # Run the following if you haven't done so before:
    gem sources -a http://gems.github.com/

    # Install the gem:
    sudo gem install hmcgowan-roo

## Usage:

    require 'rubygems'
    require 'roo'

    s = Openoffice.new("myspreadsheet.ods")      # creates an Openoffice Spreadsheet instance
    s = Excel.new("myspreadsheet.xls")           # creates an Excel Spreadsheet instance
    s = Google.new("myspreadsheetkey_at_google") # creates an Google Spreadsheet instance
    s = Excelx.new("myspreadsheet.xlsx")         # creates an Excel Spreadsheet instance for Excel .xlsx files

    s.default_sheet = s.sheets.first  # first sheet in the spreadsheet file will be used

    # s.sheet is an array which holds the names of the sheets within
    # a spreadsheet.
    # you can also write
    # s.default_sheet = s.sheets[3] or
    # s.default_sheet = 'Sheet 3'

    s.cell(1,1)                                 # returns the content of the first row/first cell in the sheet
    s.cell('A',1)                               # same cell
    s.cell(1,'A')                               # same cell
    s.cell(1,'A',s.sheets[0])                   # same cell

    # almost all methods have an optional argument 'sheet'.
    # If this parameter is omitted, the default_sheet will be used.

    s.info                                      # prints infos about the spreadsheet file

    s.first_row                                 # the number of the first row
    s.last_row                                  # the number of the last row
    s.first_column                              # the number of the first column
    s.last_column                               # the number of the last column

    # limited font information is available

    s.font(1,1).bold?
    s.font(1,1).italic?
    s.font(1,1).underline?

see http://roo.rubyforge.org for a more complete tutorial


text:
"""Group a list of PubMed IDs based on their relationships in Entrez.
This is a demonstration script tackling the problem of organizing a list
of journal articles into most related groups. The input is a list of pubmed IDs
and the resulting groups are printed, demonstrating the functionality.
It works by trying to group together most closely related items first and
gradually relaxing stringency until all items are placed into related groups.
Usage:
    pubmed_related_group.py <pmids>
"""
from __future__ import with_statement
import sys
import operator

from Bio import Entrez

def main(pmid_file):
    pmids = []
    with open(pmid_file) as in_handle:
        for line in in_handle:
            pmids.append(line.strip())
    entrez_grouper = EntrezRelatedGrouper(3, 10)
    all_groups = entrez_grouper.get_pmid_groups(pmids)
    print all_groups

class EntrezRelatedGrouper:
    """Group journal articles using the Entrez Elink related query.
    """
    def __init__(self, min_group_size, max_group_size):
        self._min_group = min_group_size
        self._max_group = max_group_size

        self._filter_params = [(0.08, 2), (0.10, 2), (0.11, 3),
                (0.125, 3), (0.15, 4), (0.2, 5), (0.9, 10)]

    def get_pmid_groups(self, pmids):
        """Retrieve related groups for the passed article PubMed IDs.
        This works through a set of increasingly less stringent filtering
        parameters, placing all PubMed IDs in groups based on related articles
        from Entrez.
        """
        pmid_related = self._get_elink_related_ids(pmids)
        filter_params = self._filter_params[:]
        final_groups = []
        while len(pmid_related) > 0:
            if len(filter_params) == 0:
                raise ValueError("Ran out of parameters before finding groups")
            cur_thresh, cur_related = filter_params.pop(0)
            while 1:
                filt_related = self._filter_related(pmid_related, cur_thresh,
                        cur_related)
                groups = self._groups_from_related_dict(filt_related)
                new_groups, pmid_related = self._collect_new_groups(
                        pmid_related, groups)
                final_groups.extend(new_groups)
                if len(new_groups) == 0:
                    break
            if len(pmid_related) < self._max_group:
                final_groups.append(pmid_related.keys())
                pmid_related = {}
        return final_groups

    def _collect_new_groups(self, pmid_related, groups):
        """Collect new groups within our parameters, updating the ones to find.
        """
        final_groups = []
        for group_items in groups:
            final_items = [i for i in group_items if pmid_related.has_key(i)]
            if (len(final_items) >= self._min_group and
                    len(final_items) <= self._max_group):
                final_groups.append(final_items)
                for item in final_items:
                    del pmid_related[item]
        final_related_dict = {}
        for pmid, related in pmid_related.items():
            final_related = [r for r in related if pmid_related.has_key(r)]
            final_related_dict[pmid] = final_related
        return final_groups, final_related_dict

    def _get_elink_related_ids(self, pmids):
        """Query Entrez elink for pub med ids related to the passed list.
        Returns a dictionary where the keys are input pubmed ids and the keys
        are related PubMed IDs, sorted by score.
        """
        pmid_related = {}
        for pmid in pmids:
            handle = Entrez.elink(dbform='pubmed', db='pubmed', id=pmid)
            record = Entrez.read(handle)
            cur_ids = []
            for link_dict in record[0]['LinkSetDb'][0]['Link']:
                cur_ids.append((int(link_dict.get('Score', 0)),
                    link_dict['Id']))
            cur_ids.sort()
            cur_ids.reverse()
            local_ids = [x[1] for x in cur_ids if x[1] in pmids]
            if pmid in local_ids:
                local_ids.remove(pmid)
            pmid_related[pmid] = local_ids
        return pmid_related

    def _filter_related(self, inital_dict, overrep_thresh=0.125, related_max=3):
        """Filter a dictionary of related terms to limit over-represented items.
        We may have some items represented many times in a set, which will lead
        to a non-useful huge cluster of related items. These are filtered,
        based on overrep_thresh, and the total items for any item is limited to
        related_max.
        """
        final_dict = {}
        all_vals = reduce(operator.add, inital_dict.values())
        for item_id, item_vals in inital_dict.items():
            final_vals = [val for val in item_vals if
                float(all_vals.count(val)) / len(inital_dict) <= overrep_thresh]
            final_dict[item_id] = final_vals[:related_max]
        return final_dict

    def _groups_from_related_dict(self, related_dict):
        """Create a list of unique groups from a dictionary of relations.
        """
        cur_groups = []
        all_base = related_dict.keys()
        for base_id, cur_ids in related_dict.items():
            overlap = set(cur_ids) & set(all_base)
            if len(overlap) > 0:
                new_group = set(overlap | set([base_id]))
                is_unique = True
                for exist_i, exist_group in enumerate(cur_groups):
                    if len(new_group & exist_group) > 0:
                        update_group = new_group | exist_group
                        cur_groups[exist_i] = update_group
                        is_unique = False
                        break
                if is_unique:
                    cur_groups.append(new_group)
        return [list(g) for g in cur_groups]

if __name__ == "__main__":
    if len(sys.argv) != 2:
        print __doc__
        sys.exit()
    main(sys.argv[1])


text:
"""Test the entity helper."""
# pylint: disable=protected-access
import asyncio
from unittest.mock import MagicMock
from unittest.mock import patch

import pytest

import homeassistant.helpers.entity as entity
from homeassistant.helpers.customize import set_customize
from homeassistant.const import ATTR_HIDDEN, ATTR_DEVICE_CLASS

from tests.common import get_test_home_assistant

def test_generate_entity_id_requires_hass_or_ids():
    """Ensure we require at least hass or current ids."""
    fmt = 'test.{}'
    with pytest.raises(ValueError):
        entity.generate_entity_id(fmt, 'hello world')

def test_generate_entity_id_given_keys():
    """Test generating an entity id given current ids."""
    fmt = 'test.{}'
    assert entity.generate_entity_id(
        fmt, 'overwrite hidden true', current_ids=[
            'test.overwrite_hidden_true']) == 'test.overwrite_hidden_true_2'
    assert entity.generate_entity_id(
        fmt, 'overwrite hidden true', current_ids=[
            'test.another_entity']) == 'test.overwrite_hidden_true'

def test_async_update_support(event_loop):
    """Test async update getting called."""
    sync_update = []
    async_update = []

    class AsyncEntity(entity.Entity):
        hass = MagicMock()
        entity_id = 'sensor.test'

        def update(self):
            sync_update.append([1])

    ent = AsyncEntity()
    ent.hass.loop = event_loop

    @asyncio.coroutine
    def test():
        yield from ent.async_update_ha_state(True)

    event_loop.run_until_complete(test())

    assert len(sync_update) == 1
    assert len(async_update) == 0

    @asyncio.coroutine
    def async_update_func():
        """Async update."""
        async_update.append(1)

    ent.async_update = async_update_func

    event_loop.run_until_complete(test())

    assert len(sync_update) == 1
    assert len(async_update) == 1

class TestHelpersEntity(object):
    """Test homeassistant.helpers.entity module."""

    def setup_method(self, method):
        """Setup things to be run when tests are started."""
        self.entity = entity.Entity()
        self.entity.entity_id = 'test.overwrite_hidden_true'
        self.hass = self.entity.hass = get_test_home_assistant()
        self.entity.update_ha_state()

    def teardown_method(self, method):
        """Stop everything that was started."""
        self.hass.stop()

    def test_default_hidden_not_in_attributes(self):
        """Test that the default hidden property is set to False."""
        assert ATTR_HIDDEN not in self.hass.states.get(
            self.entity.entity_id).attributes

    def test_overwriting_hidden_property_to_true(self):
        """Test we can overwrite hidden property to True."""
        set_customize(
            self.hass,
            entity.CORE_DOMAIN,
            [{'entity_id': [self.entity.entity_id], ATTR_HIDDEN: True}])
        self.entity.update_ha_state()

        state = self.hass.states.get(self.entity.entity_id)
        assert state.attributes.get(ATTR_HIDDEN)

    def test_generate_entity_id_given_hass(self):
        """Test generating an entity id given hass object."""
        fmt = 'test.{}'
        assert entity.generate_entity_id(
            fmt, 'overwrite hidden true',
            hass=self.hass) == 'test.overwrite_hidden_true_2'

    def test_update_calls_async_update_if_available(self):
        """Test async update getting called."""
        async_update = []

        class AsyncEntity(entity.Entity):
            hass = self.hass
            entity_id = 'sensor.test'

            @asyncio.coroutine
            def async_update(self):
                async_update.append([1])

        ent = AsyncEntity()
        ent.update()
        assert len(async_update) == 1

    def test_device_class(self):
        """Test device class attribute."""
        state = self.hass.states.get(self.entity.entity_id)
        assert state.attributes.get(ATTR_DEVICE_CLASS) is None
        with patch('homeassistant.helpers.entity.Entity.device_class',
                   new='test_class'):
            self.entity.update_ha_state()
        state = self.hass.states.get(self.entity.entity_id)
        assert state.attributes.get(ATTR_DEVICE_CLASS) == 'test_class'


text:
#include <iostream>
#include <limits>

#include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "absl/status/status.h"
#include "absl/strings/str_format.h"
#include "tensorflow_lite_support/cc/port/statusor.h"
#include "tensorflow_lite_support/cc/task/core/category.h"
#include "tensorflow_lite_support/cc/task/text/nlclassifier/bert_nl_classifier.h"

ABSL_FLAG(std::string,
          model_path,
          "",
          "Absolute path to the '.tflite' bert classification model.");
ABSL_FLAG(std::string, text, "", "Text to classify.");

namespace tflite {
namespace task {
namespace text {
namespace nlclassifier {

absl::Status Classify() {
  ASSIGN_OR_RETURN(
      std::unique_ptr<BertNLClassifier> classifier,
      BertNLClassifier::CreateFromFile(absl::GetFlag(FLAGS_model_path)));

  std::vector<core::Category> categories =
      classifier->Classify(absl::GetFlag(FLAGS_text));

  for (int i = 0; i < categories.size(); ++i) {
    const core::Category& category = categories[i];
    std::cout << absl::StrFormat("category[%d]: '%s' : '%.5f'\n", i,
                                 category.class_name, category.score);
  }

  return absl::OkStatus();
}

}  // namespace nlclassifier
}  // namespace text
}  // namespace task
}  // namespace tflite

int main(int argc, char** argv) {
  // Parse command line arguments and perform sanity checks.
  absl::ParseCommandLine(argc, argv);
  if (absl::GetFlag(FLAGS_model_path).empty()) {
    std::cerr << "Missing mandatory 'model_path' argument.\n";
    return 1;
  }
  if (absl::GetFlag(FLAGS_text).empty()) {
    std::cerr << "Missing mandatory 'question' argument.\n";
    return 1;
  }

  // Run classification.
  absl::Status status = tflite::task::text::nlclassifier::Classify();
  if (status.ok()) {
    return 0;
  } else {
    std::cerr << "Classification failed: " << status.message() << "\n";
    return 1;
  }
}


text:
module.exports = function (context, stepInfo) {
  context.formatOptions.progressive = true;
};


text:
ruby-aws-signed-url
===================

Ruby library for AWS signed url (S3, CloudFront)


text:
package org.elasticsearch.index.query;

import org.apache.lucene.search.Query;
import org.apache.lucene.search.spans.SpanNotQuery;
import org.apache.lucene.search.spans.SpanQuery;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;

import java.io.IOException;
import java.util.Objects;

import static org.elasticsearch.index.query.SpanQueryBuilder.SpanQueryBuilderUtil.checkNoBoost;

public class SpanNotQueryBuilder extends AbstractQueryBuilder<SpanNotQueryBuilder> implements SpanQueryBuilder {
    public static final String NAME = "span_not";

    /** the default pre parameter size */
    public static final int DEFAULT_PRE = 0;
    /** the default post parameter size */
    public static final int DEFAULT_POST = 0;

    private static final ParseField POST_FIELD = new ParseField("post");
    private static final ParseField PRE_FIELD = new ParseField("pre");
    private static final ParseField DIST_FIELD = new ParseField("dist");
    private static final ParseField EXCLUDE_FIELD = new ParseField("exclude");
    private static final ParseField INCLUDE_FIELD = new ParseField("include");

    private final SpanQueryBuilder include;

    private final SpanQueryBuilder exclude;

    private int pre = DEFAULT_PRE;

    private int post = DEFAULT_POST;

    /**
     * Construct a span query matching spans from include which
     * have no overlap with spans from exclude.
     * @param include the span query whose matches are filtered
     * @param exclude the span query whose matches must not overlap
     */
    public SpanNotQueryBuilder(SpanQueryBuilder include, SpanQueryBuilder exclude) {
        if (include == null) {
            throw new IllegalArgumentException("inner clause [include] cannot be null.");
        }
        if (exclude == null) {
            throw new IllegalArgumentException("inner clause [exclude] cannot be null.");
        }
        this.include = include;
        this.exclude = exclude;
    }

    /**
     * Read from a stream.
     */
    public SpanNotQueryBuilder(StreamInput in) throws IOException {
        super(in);
        include = (SpanQueryBuilder) in.readNamedWriteable(QueryBuilder.class);
        exclude = (SpanQueryBuilder) in.readNamedWriteable(QueryBuilder.class);
        pre = in.readVInt();
        post = in.readVInt();
    }

    @Override
    protected void doWriteTo(StreamOutput out) throws IOException {
        out.writeNamedWriteable(include);
        out.writeNamedWriteable(exclude);
        out.writeVInt(pre);
        out.writeVInt(post);
    }

    /**
     * @return the span query whose matches are filtered
     */
    public SpanQueryBuilder includeQuery() {
        return this.include;
    }

    /**
     * @return the span query whose matches must not overlap
     */
    public SpanQueryBuilder excludeQuery() {
        return this.exclude;
    }

    /**
     * @param dist the amount of tokens from within the include span can't have overlap with the exclude span.
     * Equivalent to setting both pre and post parameter.
     */
    public SpanNotQueryBuilder dist(int dist) {
        pre(dist);
        post(dist);
        return this;
    }

    /**
     * @param pre the amount of tokens before the include span that can't have overlap with the exclude span. Values
     * smaller than 0 will be ignored and 0 used instead.
     */
    public SpanNotQueryBuilder pre(int pre) {
        this.pre = (pre >= 0) ? pre : 0;
        return this;
    }

    /**
     * @return the amount of tokens before the include span that can't have overlap with the exclude span.
     * @see SpanNotQueryBuilder#pre(int)
     */
    public Integer pre() {
        return this.pre;
    }

    /**
     * @param post the amount of tokens after the include span that can't have overlap with the exclude span.
     */
    public SpanNotQueryBuilder post(int post) {
        this.post = (post >= 0) ? post : 0;
        return this;
    }

    /**
     * @return the amount of tokens after the include span that can't have overlap with the exclude span.
     * @see SpanNotQueryBuilder#post(int)
     */
    public Integer post() {
        return this.post;
    }

    @Override
    protected void doXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject(NAME);
        builder.field(INCLUDE_FIELD.getPreferredName());
        include.toXContent(builder, params);
        builder.field(EXCLUDE_FIELD.getPreferredName());
        exclude.toXContent(builder, params);
        builder.field(PRE_FIELD.getPreferredName(), pre);
        builder.field(POST_FIELD.getPreferredName(), post);
        printBoostAndQueryName(builder);
        builder.endObject();
    }

    public static SpanNotQueryBuilder fromXContent(XContentParser parser) throws IOException {
        float boost = AbstractQueryBuilder.DEFAULT_BOOST;

        SpanQueryBuilder include = null;
        SpanQueryBuilder exclude = null;

        Integer dist = null;
        Integer pre  = null;
        Integer post = null;

        String queryName = null;

        String currentFieldName = null;
        XContentParser.Token token;
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (token == XContentParser.Token.START_OBJECT) {
                if (INCLUDE_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    QueryBuilder query = parseInnerQueryBuilder(parser);
                    if (query instanceof SpanQueryBuilder == false) {
                        throw new ParsingException(parser.getTokenLocation(), "span_not [include] must be of type span query");
                    }
                    include = (SpanQueryBuilder) query;
                    checkNoBoost(NAME, currentFieldName, parser, include);
                } else if (EXCLUDE_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    QueryBuilder query = parseInnerQueryBuilder(parser);
                    if (query instanceof SpanQueryBuilder == false) {
                        throw new ParsingException(parser.getTokenLocation(), "span_not [exclude] must be of type span query");
                    }
                    exclude = (SpanQueryBuilder) query;
                    checkNoBoost(NAME, currentFieldName, parser, exclude);
                } else {
                    throw new ParsingException(parser.getTokenLocation(), "[span_not] query does not support [" + currentFieldName + "]");
                }
            } else {
                if (DIST_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    dist = parser.intValue();
                } else if (PRE_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    pre = parser.intValue();
                } else if (POST_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    post = parser.intValue();
                } else if (AbstractQueryBuilder.BOOST_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    boost = parser.floatValue();
                } else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    queryName = parser.text();
                } else {
                    throw new ParsingException(parser.getTokenLocation(), "[span_not] query does not support [" + currentFieldName + "]");
                }
            }
        }
        if (include == null) {
            throw new ParsingException(parser.getTokenLocation(), "span_not must have [include] span query clause");
        }
        if (exclude == null) {
            throw new ParsingException(parser.getTokenLocation(), "span_not must have [exclude] span query clause");
        }
        if (dist != null && (pre != null || post != null)) {
            throw new ParsingException(parser.getTokenLocation(), "span_not can either use [dist] or [pre] & [post] (or none)");
        }

        SpanNotQueryBuilder spanNotQuery = new SpanNotQueryBuilder(include, exclude);
        if (dist != null) {
            spanNotQuery.dist(dist);
        }
        if (pre != null) {
            spanNotQuery.pre(pre);
        }
        if (post != null) {
            spanNotQuery.post(post);
        }
        spanNotQuery.boost(boost);
        spanNotQuery.queryName(queryName);
        return spanNotQuery;
    }

    @Override
    protected Query doToQuery(QueryShardContext context) throws IOException {

        Query includeQuery = this.include.toQuery(context);
        assert includeQuery instanceof SpanQuery;
        Query excludeQuery = this.exclude.toQuery(context);
        assert excludeQuery instanceof SpanQuery;

        return new SpanNotQuery((SpanQuery) includeQuery, (SpanQuery) excludeQuery, pre, post);
    }

    @Override
    protected int doHashCode() {
        return Objects.hash(include, exclude, pre, post);
    }

    @Override
    protected boolean doEquals(SpanNotQueryBuilder other) {
        return Objects.equals(include, other.include) &&
               Objects.equals(exclude, other.exclude) &&
               (pre == other.pre) &&
               (post == other.post);
    }

    @Override
    public String getWriteableName() {
        return NAME;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>jfoley.waltz</groupId>
  <artifactId>waltz-flow</artifactId>
  <version>0.5-SNAPSHOT</version>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <javaVersion>1.8</javaVersion>
  </properties>

  <distributionManagement>
    <repository>
      <id>deployment</id>
      <name>Internal Releases</name>
      <url>http://scm-ciir.cs.umass.edu:8080/nexus/content/repositories/releases/</url>
    </repository>
    <snapshotRepository>
      <id>deployment</id>
      <name>Internal Releases</name>
      <url>http://scm-ciir.cs.umass.edu:8080/nexus/content/repositories/snapshots/</url>
    </snapshotRepository>
  </distributionManagement>

  <pluginRepositories>
    <pluginRepository>
      <id>edu.umass.ciir.snapshots</id>
      <name>CIIR Nexus Snapshots</name>
      <url>http://scm-ciir.cs.umass.edu:8080/nexus/content/repositories/snapshots</url>
    </pluginRepository>
    <pluginRepository>
      <id>edu.umass.ciir.releases</id>
      <name>CIIR Nexus Releases</name>
      <url>http://scm-ciir.cs.umass.edu:8080/nexus/content/repositories/releases</url>
    </pluginRepository>
  </pluginRepositories>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
      <type>jar</type>
    </dependency>

    <dependency>
      <groupId>jfoley.waltz</groupId>
      <artifactId>waltz-base</artifactId>
      <version>0.5-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>jfoley.waltz</groupId>
      <artifactId>waltz-galago-io</artifactId>
      <version>0.5-SNAPSHOT</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>

      <!-- build a jar with relative classpath -->
      <plugin>
        <artifactId>maven-jar-plugin</artifactId>
        <version>2.4</version>
        <configuration>
          <archive>
            <index>true</index>
            <manifest>
              <classpathPrefix>lib/</classpathPrefix>
              <addClasspath>true</addClasspath>
              <useUniqueVersions>false</useUniqueVersions>
            </manifest>
          </archive>
        </configuration>
      </plugin>

      <!-- this is entirely to set the java version -->
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>${javaVersion}</source>
          <target>${javaVersion}</target>
        </configuration>
      </plugin>

      <!-- copy dependencies to relative classpath -->
      <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>copy-dependencies</goal>
            </goals>
            <configuration>
              <outputDirectory>${project.build.directory}/lib</outputDirectory>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <!-- tell Java 8 JavaDoc tool to not complain about imperfect docs -->
      <plugin>
        <artifactId>maven-javadoc-plugin</artifactId>
        <version>2.10.3</version>
        <configuration>
          <additionalparam>-Xdoclint:none</additionalparam>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>


text:
#include <aws/mwaa/model/PublishMetricsRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::MWAA::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;

PublishMetricsRequest::PublishMetricsRequest() :
    m_environmentNameHasBeenSet(false),
    m_metricDataHasBeenSet(false)
{
}

Aws::String PublishMetricsRequest::SerializePayload() const
{
  JsonValue payload;

  if(m_metricDataHasBeenSet)
  {
   Aws::Utils::Array<JsonValue> metricDataJsonList(m_metricData.size());
   for(unsigned metricDataIndex = 0; metricDataIndex < metricDataJsonList.GetLength(); ++metricDataIndex)
   {
     metricDataJsonList[metricDataIndex].AsObject(m_metricData[metricDataIndex].Jsonize());
   }
   payload.WithArray("MetricData", std::move(metricDataJsonList));

  }

  return payload.View().WriteReadable();
}


text:
@interface WMFRandomArticleViewController : WMFArticleViewController

#if WMF_TWEAKS_ENABLED
@property (nonatomic, getter=isPermaRandomMode) BOOL permaRandomMode;
#endif
@end


text:
using System;

namespace NadekoBot.Modules.Music.Classes
{
    class PlaylistFullException : Exception
    {
        public PlaylistFullException(string message) : base(message)
        {
        }
        public PlaylistFullException() : base("Queue is full.") { }
    }
}


text:
'use strict';

var assert = require('assert');
var sinon = require('sinon');

var Printer = require('../src/printer.js');
var Pdfkit = require('pdfkit');

describe('Printer', function () {

	var SHORT_SIDE = 1000, LONG_SIDE = 2000;
	var fontDescriptors, printer;

	beforeEach(function () {
		fontDescriptors = {
			Roboto: {
				normal: 'tests/fonts/Roboto-Regular.ttf'
			}
		};
		Pdfkit.prototype.addPage = sinon.spy(Pdfkit.prototype.addPage);

	});

	it('should pass switched width and height to pdfkit if page orientation changes from default portrait to landscape', function () {
		printer = new Printer(fontDescriptors);
		var docDefinition = {
			pageSize: {width: SHORT_SIDE, height: LONG_SIDE},
			content: [
				{
					text: 'Page 1'
				},
				{
					text: 'Page 2',
					pageBreak: 'before',
					pageOrientation: 'landscape'
				}
			]
		};
		printer.createPdfKitDocument(docDefinition);

		assert(Pdfkit.prototype.addPage.callCount === 2);

		assert.equal(Pdfkit.prototype.addPage.firstCall.args[0], undefined);
		assert.deepEqual(Pdfkit.prototype.addPage.secondCall.args[0].size, [LONG_SIDE, SHORT_SIDE]);
	});

	it('should pass switched width and height to pdfkit if page orientation changes from portrait to landscape', function () {
		printer = new Printer(fontDescriptors);
		var docDefinition = {
			pageOrientation: 'portrait',
			pageSize: {width: SHORT_SIDE, height: LONG_SIDE},
			content: [
				{
					text: 'Page 1'
				},
				{
					text: 'Page 2',
					pageBreak: 'before',
					pageOrientation: 'landscape'
				}
			]
		};
		printer.createPdfKitDocument(docDefinition);

		assert(Pdfkit.prototype.addPage.callCount === 2);

		assert.equal(Pdfkit.prototype.addPage.firstCall.args[0], undefined);
		assert.deepEqual(Pdfkit.prototype.addPage.secondCall.args[0].size, [LONG_SIDE, SHORT_SIDE]);
	});

	it('should pass switched width and height to pdfkit if page orientation changes from landscape to portrait', function () {
		printer = new Printer(fontDescriptors);

		var docDefinition = {
			pageOrientation: 'landscape',
			pageSize: {width: SHORT_SIDE, height: LONG_SIDE},
			content: [
				{
					text: 'Page 1'
				},
				{
					text: 'Page 2',
					pageBreak: 'before',
					pageOrientation: 'portrait'
				},
				{
					text: 'Page 3 still portrait',
					pageBreak: 'before'
				}
			]
		};
		printer.createPdfKitDocument(docDefinition);

		assert(Pdfkit.prototype.addPage.callCount === 3);

		assert.equal(Pdfkit.prototype.addPage.firstCall.args[0], undefined);
		assert.deepEqual(Pdfkit.prototype.addPage.secondCall.args[0].size, [SHORT_SIDE, LONG_SIDE]);
		assert.deepEqual(Pdfkit.prototype.addPage.thirdCall.args[0].size, [SHORT_SIDE, LONG_SIDE]);
	});

	it('should not switch width and height for pdfkit if page orientation changes from landscape to landscape', function () {
		printer = new Printer(fontDescriptors);
		var docDefinition = {
			pageOrientation: 'portrait',
			pageSize: {width: SHORT_SIDE, height: LONG_SIDE},
			content: [
				{
					text: 'Page 1'
				},
				{
					text: 'Page 2',
					pageBreak: 'before',
					pageOrientation: 'landscape'
				},
				{
					text: 'Page 3 landscape again',
					pageOrientation: 'landscape',
					pageBreak: 'after'
				}
			]
		};
		printer.createPdfKitDocument(docDefinition);

		assert.equal(Pdfkit.prototype.addPage.callCount, 3);

		assert.equal(Pdfkit.prototype.addPage.firstCall.args[0], undefined);
		assert.deepEqual(Pdfkit.prototype.addPage.secondCall.args[0].size, [LONG_SIDE, SHORT_SIDE]);
		assert.deepEqual(Pdfkit.prototype.addPage.thirdCall.args[0].size, [LONG_SIDE, SHORT_SIDE]);
	});

	it('should print bullet vectors as ellipses', function () {
		printer = new Printer(fontDescriptors);
		var docDefinition = {
			pageOrientation: 'portrait',
			pageSize: {width: SHORT_SIDE, height: LONG_SIDE},
			content: [
				{
					"stack": [
						{
							"ul": [
								{"text": "item1"},
								{"text": "item2"}
							]
						}
					]
				}
			]
		};
		Pdfkit.prototype.ellipse = sinon.spy(Pdfkit.prototype.ellipse);

		printer.createPdfKitDocument(docDefinition);

		function assertEllipse(ellipseCallArgs) {
			var firstEllipse = {
				x: ellipseCallArgs[0],
				y: ellipseCallArgs[1],
				r1: ellipseCallArgs[2],
				r2: ellipseCallArgs[3]
			};
			assert(firstEllipse.x !== undefined);
			assert(!isNaN(firstEllipse.x));
			assert(firstEllipse.y !== undefined);
			assert(!isNaN(firstEllipse.y));
			assert(firstEllipse.r1 !== undefined);
			assert(!isNaN(firstEllipse.r1));
			assert(firstEllipse.r2 !== undefined);
			assert(!isNaN(firstEllipse.r2));
		}

		assert.equal(Pdfkit.prototype.ellipse.callCount, 2);

		assertEllipse(Pdfkit.prototype.ellipse.firstCall.args);
		assertEllipse(Pdfkit.prototype.ellipse.secondCall.args);

	});

	it('should print only the require number of pages', function () {
		printer = new Printer(fontDescriptors);

		var docDefinition = {
			pageSize: 'A4',
			maxPagesNumber: 1,
			content: [
				{
					text: 'Page 1'
				},
				{
					text: 'Page 2',
					pageBreak: 'before',
					pageOrientation: 'landscape'
				}]
		};

		printer.createPdfKitDocument(docDefinition);

		assert(Pdfkit.prototype.addPage.callCount === 1);
	});

	it('should print all pages when maxPagesNumber is undefined', function () {
		printer = new Printer(fontDescriptors);

		var docDefinition = {
			pageSize: 'A4',
			content: [
				{
					text: 'Page 1'
				},
				{
					text: 'Page 2',
					pageBreak: 'before',
					pageOrientation: 'landscape'
				},
				{
					text: 'Page 3',
					pageBreak: 'before',
				}]
		};

		printer.createPdfKitDocument(docDefinition);

		assert(Pdfkit.prototype.addPage.callCount === 3);
	});

	it('should report progress on each rendered item when a progressCallback is passed', function () {

		printer = new Printer(fontDescriptors);

		var progressCallback = sinon.spy(function (progress) {});

		var docDefinition = {
			pageSize: 'A4',
			content: [
				{
					text: 'Text item 1'
				},
				{
					image: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAGAQMAAADNIO3CAAAAA1BMVEUAAN7GEcIJAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB98DBREbA3IZ3d8AAAALSURBVAjXY2BABwAAEgAB74lUpAAAAABJRU5ErkJggg=='
				},
				{
					text: 'Text item 2'
				},
				{
					canvas: [{
							type: 'rect',
							x: 0,
							y: 0,
							w: 310,
							h: 260
						}]
				}]
		};

		printer.createPdfKitDocument(docDefinition, {progressCallback: progressCallback});

		assert(progressCallback.withArgs(0.25).calledOnce);
		assert(progressCallback.withArgs(0.5).calledOnce);
		assert(progressCallback.withArgs(0.75).calledOnce);
		assert(progressCallback.withArgs(1).calledOnce);
	});

	it('should work without a progressCallback', function () {
		printer = new Printer(fontDescriptors);

		var docDefinition = {
			pageSize: 'A4',
			content: [{text: 'Text item 1'}]
		};

		assert.doesNotThrow(function () {
			printer.createPdfKitDocument(docDefinition);
		});
	});

});


text:
''' Provide a set of objects to represent different stages of a connection
to a Bokeh server.

'''

#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function, unicode_literals

import logging
log = logging.getLogger(__name__)

from bokeh.util.api import public, internal ; public, internal

#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------

# Standard library imports

# External imports
from tornado import gen

# Bokeh imports

#-----------------------------------------------------------------------------
# Globals and constants
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Public API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Internal API
#-----------------------------------------------------------------------------

@internal((1,0,0))
class NOT_YET_CONNECTED(object):
    ''' The ``ClientConnection`` is not yet connected.

    '''
    @gen.coroutine
    @internal((1,0,0))
    def run(self, connection):
        yield connection._connect_async()

@internal((1,0,0))
class CONNECTED_BEFORE_ACK(object):
    ''' The ``ClientConnection`` connected to a Bokeh server, but has not yet
    received an ACK from it.

    '''
    @gen.coroutine
    @internal((1,0,0))
    def run(self, connection):
        yield connection._wait_for_ack()

@internal((1,0,0))
class CONNECTED_AFTER_ACK(object):
    ''' The ``ClientConnection`` connected to a Bokeh server, and has
    received an ACK from it.

    '''
    @gen.coroutine
    @internal((1,0,0))
    def run(self, connection):
        yield connection._handle_messages()

@internal((1,0,0))
class DISCONNECTED(object):
    ''' The ``ClientConnection`` was connected to a Bokeh server, but is
    now disconnected.

    '''
    @gen.coroutine
    @internal((1,0,0))
    def run(self, connection):
        raise gen.Return(None)

@internal((1,0,0))
class WAITING_FOR_REPLY(object):
    ''' The ``ClientConnection`` has sent a message to the Bokeh Server which
    should generate a paired reply, and is waiting for the reply.

    '''
    def __init__(self, reqid):
        self._reqid = reqid
        self._reply = None

    @property
    @internal((1,0,0))
    def reply(self):
        ''' The reply from the server. (``None`` until the reply arrives) '''
        return self._reply

    @property
    @internal((1,0,0))
    def reqid(self):
        ''' The request ID of the originating message. '''
        return self._reqid

    @gen.coroutine
    @internal((1,0,0))
    def run(self, connection):
        message = yield connection._pop_message()
        if message is None:
            yield connection._transition_to_disconnected()
        elif 'reqid' in message.header and message.header['reqid'] == self.reqid:
            self._reply = message
            yield connection._transition(CONNECTED_AFTER_ACK())
        else:
            yield connection._next()

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------


text:
    {{#if data}}
    <input id="toggle-all" type="checkbox" {{#if toggleAll}}checked{{/if}}>
    {{/if}}
    Mark all as complete

         {{#data}}

                    <input class="toggle" type="checkbox" {{#if completed}}checked{{/if}}>
                    {{todo}}
                    <button class="destroy"></button>

                <input class="edit" value="{{todo}}">

        {{/data}}


text:
<?php

error_reporting(E_ALL);

define('APP_PATH', realpath('..'));

try {

    include APP_PATH . "/vendor/autoload.php";

    /**
     * Read the configuration
     */
    $config = include APP_PATH . "/app/config/config.php";

    /**
     * Read auto-loader
     */
    include APP_PATH . "/app/config/loader.php";

    /**
     * Read services
     */
    include APP_PATH . "/app/config/services.php";

    /**
     * Custom Routes.
     */
    include APP_PATH . "/app/config/routes.php";

    /**
     * Handle the request
     */
    $application = new \Phalcon\Mvc\Application($di);

    echo $application->handle()->getContent();

} catch (\Exception $e) {
    echo $e->getMessage() . '
';
    //echo '
' . $e->getTraceAsString() . '
';
}


text:
import * as React from 'react';
import graphql from 'graphql-tag';

export default class extends React.Component<{}, {}> {
  public render() {
    return <div />;
  }
}

export const pageQuery = graphql`
  query IndexQuery {
    site {
      siteMetadata {
        title
      }
    }
  }
`;

// export const pageQuery = graphql`
//   query IndexQuery {
//     site {
//       siteMetadata {
//         title
//       }
//     }
//   }
// `;


text:
LOCAL_INCLUDES=-I./
HEADERS := $(wildcard *.h)

C_SOURCES := $(wildcard *.c)
CPP_SOURCES := $(wildcard *.cpp)
OBJECTS = $(patsubst %.c,%.o, $(C_SOURCES)) $(patsubst %.cpp,%.o, $(CPP_SOURCES))
default: lib

include ../Makefile.config

$(ARDUINO_LIBRARY): $(OBJECTS)
	${AR} crs ${ARDUINO_LIBRARY} ${OBJECTS}

lib: $(ARDUINO_LIBRARY)


text:
<?php

namespace Movibe\BackendBundle\Listener;

use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;

class PreMethodListener
{
    public function preMethod(FilterControllerEvent $event)
    {
        if (HttpKernelInterface::MASTER_REQUEST == $event->getRequestType())
        {
            $controller = $event->getController();
            if (isset($controller[0]))
            {
                $controller = $controller[0];
                if (method_exists($controller, "preExecute"))
                {
                    $controller->preExecute();
                }
            }
        }

    }
}


text:
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Navigation.css';
import Link from '../Link';
import {UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem} from 'reactstrap';

class Navigation extends React.Component {

  logout() {
    fetch('/logout', {
      credentials: 'include',
    }).then(function (response) {
      document.cookie = 'connect.sid' + '=; Max-Age=0';
      window.location.href = '/'
    }).catch(alert);
  }

  render() {
    const {profile} = this.props;
    return (

        {profile
          ? <Link className={s.link} to="/profile">
              {profile}
            </Link>
             или
               this.logout()}>Выйти

          :

              <Link className={`${s.link} ${s.forCompany}`} to="/register/company">
                ДЛЯ КОМПАНИЙ
              </Link>
               {' '} |
              <Link className={s.link} to="/login">
                ВОЙТИ
              </Link>
            {/*{' '} | */}
            {/*<UncontrolledDropdown className={s.dropdown}>*/}
            {/*<DropdownToggle>*/}
            {/**/}
            {/*</DropdownToggle>*/}
            {/*<DropdownMenu>*/}
              {/*<DropdownItem header>Header</DropdownItem>*/}
              {/*<DropdownItem disabled>Action</DropdownItem>*/}
              {/*<DropdownItem>Another Action</DropdownItem>*/}
              {/*<DropdownItem divider/>*/}
              {/*<DropdownItem>Another Action</DropdownItem>*/}
            {/*</DropdownMenu>*/}
          {/*</UncontrolledDropdown>*/}
            }

    );
  }
}

export default withStyles(s)(Navigation);


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('courses', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='courses',
            name='subject',
            field=models.TextField(default='Null Subject'),
            preserve_default=False,
        ),
    ]


text:
/* kbodata.js */

(function($) {

	var lib = {

        sortProperties: function() {
            // ordered by priority
            var props = [
                'http://www.w3.org/ns/locn#fullAddress',
                'prefLabel',
                'Label',
                'label',
                'identifier',
                'name', 'Name',
                'Type',
                'type'
            ].reverse();
            $.each(props, function() {
                $('th a[href*="' + this + '"]').parents('tr').each(function() {
                    $(this).prependTo($(this).parents('tbody'));
                });
            });
        },

        reformatResources: function() {
            $('[about]').each(lib.reformatResource);
        },

        reformatResource: function() {
            var subject = $(this).attr('about');
            var subjectContainer = $(this);
            subjectContainer.append([
                '
',
                    '

',
                    '

',
                '
'
            ].join("\n"));
            $(this).find('tr').each(function() {
                var predicate = $(this).find('th a').attr('href');
                var predicateLabel = $(this).find('th a').html();
                var object, title;
                $(this).find('td a').each(function() {
                    object = '' + $(this).text() + '';
                    title = lib.getTooltipTitle($(this).attr('resource'));
                });
                $(this).find('td span').each(function() {
                    object = $(this).html();
                    title = lib.getTooltipTitle(object);
                });
                var predicateContainer = lib.getPredicateContainer(subjectContainer, predicate, predicateLabel);
                predicateContainer.find('.objects').append([
                    '
',
                    object,
                    '
'
                ].join("\n"));
            });
            $(this).find('table').hide();
        },

        getTooltipTitle: function(value) {
            if (value.match(/^(http|[^\s]{30})/)) {
                value = value.replace(/([^\s]{50,60}[^a-z])([^\s]{20})/g, "$1$2");
                return ' title="' + value + '"';
            }
            return '';
        },

        getPredicateContainer: function(subjectContainer, predicate, predicateLabel) {
            var result = subjectContainer.find('.predicate[data-p="' + predicate +'"]');
            if (!result.length) {
                var col1Height = subjectContainer.find('.col-1').height();
                var col2Height = subjectContainer.find('.col-2').height();
                var container = col1Height > col2Height ? subjectContainer.find('.col-2') : subjectContainer.find('.col-1');
                var suffix = '';
                // address: always right
                if (predicate === 'http://www.w3.org/ns/locn#fullAddress') {
                    container = subjectContainer.find('.col-2');
                    suffix = '

';
                }
                container.append([
                    '
',
                    '   ' + lib.deCamelCase(predicateLabel) + '',
                    '

',
                        suffix,
                    '
'
                ].join("\n"));
                return lib.getPredicateContainer(subjectContainer, predicate);
            }
            return result;
        },

        deCamelCase: function(value) {
            return value.replace(/([a-z])([A-Z][a-z])/g, '$1 $2');
        },

        rearrangeResources: function() {
            $('[about] h2').each(function() {
                // move properly titled resources to the top
                if (!$(this).text().match(/^http/)) {
                    $('h1').after($(this).parents('[about]'));
                }
            });
        },

        injectMaps: function() {
            $('.map').each(function() {
                var address = $(this).prev('.objects').find('.object').first().text();
                var src = 'https://maps.google.be/maps?f=q&source=s_q&hl=en&q=' + encodeURIComponent(address) + '&iwloc=A&output=embed';
                $(this).html('\
                    \
                ');
            });
        },

		init: function() {
            lib.sortProperties();
            lib.reformatResources();
            lib.rearrangeResources();
            lib.injectMaps();
		}

	};

	$(lib.init);

})(jQuery);


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

<title>org.apache.jmeter.protocol.smtp.sampler.tools Class Hierarchy (Apache JMeter API)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache JMeter

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.apache.jmeter.protocol.smtp.sampler.tools

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

java.io.OutputStream (implements java.io.Closeable, java.io.Flushable)

org.apache.jmeter.protocol.smtp.sampler.tools.CounterOutputStream

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache JMeter

Prev

Next

Frames

No Frames

All Classes

Copyright © 1998-2016 Apache Software Foundation. All Rights Reserved.