text:
//
//  GameScene.m
//  ColouredStones
//
//  Created by Raúl Uranga on 5/17/11.
//  Copyright GrupoW 2011. All rights reserved.
//

// Import the interfaces
#import "Stone.h"
#import "Tutorial.h"
#import "GameScene.h"

@interface GameScene (private)
-(void)startGame;
-(void)removeSprite:(CCNode *)n;
-(void)removeSpriteAndBegin:(CCNode *)n;
-(void)moveBar:(CCSprite *)bar byAmount:(void *)amount;
@end

// GameScene implementation
@implementation GameScene

@synthesize score,allowTouch,remainingTime,bar,timeStatus,timerRunning,blueFrames;

+(id) scene
{
	// 'scene' is an autorelease object.
	CCScene *scene = [CCScene node];

	// 'layer' is an autorelease object.
	GameScene *layer = [GameScene node];

	// add layer as a child to scene
	[scene addChild: layer];

	// return the scene
	return scene;
}

// on "init" you need to initialize your instance
-(id) init
{
	// always call "super" init
	// Apple recommends to re-assign "self" with the "super" return value
	if( (self=[super init] )) {

		self.allowTouch = NO;
		self.timerRunning = NO;

		[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"colouredSheet1.plist"];

		blueFrames = [[NSMutableArray  alloc]init];
		for(int i = 1; i < 5; i++) {
			CCSpriteFrame *frame = [[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:[NSString stringWithFormat:@"sBlue%d.png",i]];
			[blueFrames addObject:frame];
		}

		CCSpriteBatchNode * sSheet = [CCSpriteBatchNode batchNodeWithFile:@"colouredSheet1.png"];
		[self addChild:sSheet z:1 tag:kSSheet];
		//*/
		CCSprite *background = [CCSprite spriteWithFile:@"background.png"];
		[self addChild:background z:0 tag:kBack];
		/*/
		CCSprite *background = [CCSprite spriteWithBatchNode:sSheet rect:CGRectMake(504, 1,480,320)];
		[sSheet addChild:background z:0 tag:kBack];
		//*/
		CGSize size = [[CCDirector sharedDirector] winSize];
		[background setPosition:ccp(size.width/2,size.height/2)];

		/*/
		CCSprite *gridBackground = [CCSprite spriteWithFile:@"grid.png"];
		[self addChild:gridBackground z:0 tag:kGBack];
		/*/
		CCSprite *gridBackground = [CCSprite spriteWithBatchNode:sSheet rect:CGRectMake(166, 1,337, 301)];
		[sSheet addChild:gridBackground z:0 tag:kGBack];
		//*/

		[gridBackground setPosition:ccp(305,160)];

		/*/

		CCLabelAtlas *scoreLabel = [CCLabelAtlas labelWithString:@"0" charMapFile:@"fps_images.png" itemWidth:16 itemHeight:24 startCharMap:'.'];

		/*/

		CCLabelBMFont *scoreLabel = [CCLabelBMFont labelWithString:@"0" fntFile:@"ArcadeClassic.fnt"];

		//*/

		[scoreLabel setPosition:ccp(115,280)];
		[scoreLabel setAnchorPoint:ccp(1,0.5)];

		[self addChild:scoreLabel z:2 tag:kScoreLabel];

		for(int i =0; i< GRID_WIDTH ; i++)
		{
			for(int j =0; j< GRID_HEIGHT ; j++)
			{
				Stone * s = [[Stone alloc]initWithGame:self];
				grid[i][j] = s;
				[s release];
			}
		}

		[self placeStones];

		remainingTime = MAX_TIME;

		bar = [CCSprite spriteWithFile:@"bar.png"];
		[self addChild:bar z:1];
		[bar setPosition:ccp(113,25)];
		[bar setScaleY:remainingTime];
		[bar setAnchorPoint:ccp(0.5,0)];

		[self schedule:@selector(drainTime) interval:0.20];

		[self startGame];

	}
	return self;
}

-(void)startGame
{
	CCSprite *ready = [CCSprite spriteWithFile:@"ready.png"];
	[self addChild:ready z:3];
	[ready setPosition:ccp(240,160)];
	[ready setOpacity:0];

	CCSprite *set = [CCSprite spriteWithFile:@"set.png"];
	[self addChild:set z:3];
	[set setPosition:ccp(240,160)];
	[set setOpacity:0];

	CCSprite *go = [CCSprite spriteWithFile:@"go.png"];
	[self addChild:go z:3];
	[go setPosition:ccp(240,160)];
	[go setOpacity:0];

	[ready runAction:[CCSequence actions:[CCDelayTime actionWithDuration:0.5],
										 [CCSpawn actions:[CCFadeIn actionWithDuration:0.4],[CCScaleTo actionWithDuration:0.4 scale:1.2],nil],
										 [CCDelayTime actionWithDuration:0.2],
										 [CCFadeOut actionWithDuration:0.4],
										 [CCCallFunc actionWithTarget:self selector:@selector(removeSprite:)],
										 nil]];

	[set runAction:[CCSequence actions:[CCDelayTime actionWithDuration:1.5],
					  [CCSpawn actions:[CCFadeIn actionWithDuration:0.4],[CCScaleTo actionWithDuration:0.4 scale:1.2],nil],
					  [CCDelayTime actionWithDuration:0.2],
					  [CCFadeOut actionWithDuration:0.4],
					  [CCCallFunc actionWithTarget:self selector:@selector(removeSprite:)],
					  nil]];

	[go runAction:[CCSequence actions:[CCDelayTime actionWithDuration:2.5],
					  [CCSpawn actions:[CCFadeIn actionWithDuration:0.4],[CCScaleTo actionWithDuration:0.4 scale:1.2],nil],
					  [CCDelayTime actionWithDuration:0.2],
					  [CCFadeOut actionWithDuration:0.4],
					  [CCCallFunc actionWithTarget:self selector:@selector(removeSpriteAndBegin:)],
					  nil]];
}

-(void)removeSprite:(CCNode *)n
{
	[self removeChild:n cleanup:YES];
}

-(void)removeSpriteAndBegin:(CCNode *)n
{
	[self removeChild:n cleanup:YES];
	self.allowTouch = YES;
	self.timerRunning = YES;

	Tutorial * t = [[[Tutorial alloc]initWithText:@"Welcome to Coloured Stones! \n To begin playing, touch an stone and drag it around to swap it with an adjacent one. \n Match 3 or more stones to score points." theGame:self]autorelease];

}

-(void)drainTime
{

	if (self.timerRunning) {

		if (remainingTime > 0) {
			remainingTime--;
		}

		[bar setScaleY:remainingTime];

		int currentTimeStatus = self.timeStatus;

		if (remainingTime < 100) {

			self.timeStatus = 1;

		} else  {

			self.timeStatus = 0;
		}

		//*/
		if (currentTimeStatus == 0 && timeStatus == 1) {

			[bar runAction:[CCTintTo actionWithDuration:1 red:255 green:0 blue:0]];

		} else  if (currentTimeStatus == 1 && timeStatus == 0) {

			[bar runAction:[CCTintTo actionWithDuration:1 red:255 green:255 blue:255]];
		}
		///*/

		if (remainingTime <= 0) {
			score = 0;

			CCLabelAtlas *label = [(CCLabelAtlas *) self getChildByTag:kScoreLabel];
			[label setString:[NSString stringWithFormat:@"%d",score]];

			NSLog(@"You Lost!");

			remainingTime = MAX_TIME;
		}
	}
}

-(void)changeTime:(int)time
{
	[bar runAction:[CCSequence actions:[CCBlink actionWithDuration:1 blinks:10],
									   [CCCallFuncND actionWithTarget:self selector:@selector(moveBar:byAmount:) data:(void *)time],
									   nil]];
}

-(void)moveBar:(CCSprite *)bar byAmount:(void *)amount
{
	remainingTime += (int)amount;

	if (remainingTime > MAX_TIME) {

		remainingTime = MAX_TIME;

	} else if (remainingTime <= 0) {
		remainingTime = 0;
	}
}

-(void)placeStones
{
	for (int i=0; i<GRID_WIDTH; i++) {
		for (int j=0; j<GRID_HEIGHT; j++) {

			Stone *leftS = nil;
			Stone *leftMostS = nil;
			Stone *topS = nil;
			Stone *topMostS = nil;

			int prohibitedLeft = -1;
			int prohibitedTop = -1;

			if (i >= 2) {
				leftS = (Stone *) grid[i-1][j];
				leftMostS = (Stone *) grid[i-2][j];
			}

			if (j >= 2) {
				topS = (Stone *) grid[i][j-1];
				topMostS = (Stone *) grid[i][j-2];
			}

			if (leftS && leftMostS && leftS.stoneType == leftMostS.stoneType) {
				prohibitedLeft = leftS.stoneType;
			}

			if (topS && topMostS && topS.stoneType == topMostS.stoneType) {
				prohibitedTop = topS.stoneType;
			}

			[grid[i][j] placeInGrid:ccp(42*i + GRID_OFFSET.x, 42*j + GRID_OFFSET.y) pt:prohibitedTop p1:prohibitedLeft];

		}
	}

}

-(void)swapStones:(Stone *) stone dir:(int)dir
{

	NSLog(@"swapStones: %d", dir);

	for (int i=0; i<GRID_WIDTH; i++) {
		for (int j=0; j<GRID_HEIGHT; j++) {
			if (grid[i][j] == stone) {
				switch (dir) {
					case 1:

						if (i<GRID_WIDTH-1) {
							grid[i][j] = grid[i+1][j];
							grid[i+1][j] = stone;

							[grid[i][j].mySprite setPosition:ccp(42*i + GRID_OFFSET.x, 42*j + GRID_OFFSET.y)];
							[grid[i + 1][j].mySprite setPosition:ccp(42*(i+1) + GRID_OFFSET.x, 42*j + GRID_OFFSET.y)];

						}

						[self checkGroups:YES];

						return;
						break;

					case 2:

						if (i>0) {
							grid[i][j] = grid[i-1][j];
							grid[i-1][j] = stone;

							[grid[i][j].mySprite setPosition:ccp(42*i + GRID_OFFSET.x, 42*j + GRID_OFFSET.y)];
							[grid[i - 1][j].mySprite setPosition:ccp(42*(i-1) + GRID_OFFSET.x, 42*j + GRID_OFFSET.y)];

						}
						[self checkGroups:YES];
						return;
						break;

					case 3:

						if (j<GRID_HEIGHT-1) {
							grid[i][j] = grid[i][j+1];
							grid[i][j+1] = stone;

							[grid[i][j].mySprite setPosition:ccp(42*i + GRID_OFFSET.x, 42*j + GRID_OFFSET.y)];
							[grid[i][j+1].mySprite setPosition:ccp(42*(i) + GRID_OFFSET.x, 42*(j+1) + GRID_OFFSET.y)];

						}
						[self checkGroups:YES];
						return;
						break;

					case 4:

						if (j>0) {
							grid[i][j] = grid[i][j-1];
							grid[i][j-1] = stone;

							[grid[i][j].mySprite setPosition:ccp(42*i + GRID_OFFSET.x, 42*j + GRID_OFFSET.y)];
							[grid[i][j-1].mySprite setPosition:ccp(42*(i) + GRID_OFFSET.x, 42*(j-1) + GRID_OFFSET.y)];

						}
						[self checkGroups:YES];
						return;
						break;
				}
			}
		}
	}
}

-(void)checkGroups:(bool)firstTime
{
	int curHGroup = 0;
	int curVGroup = 0;
	int lastGroup = -1;

	NSMutableArray *groupings = [[NSMutableArray alloc] init];

	for (int i=0; i<GRID_WIDTH; i++) {
		for (int j=0; j<GRID_HEIGHT; j++) {

			Stone *d = (Stone *) grid[i][j];
			d.disappearing = NO;
			Stone *l = nil;
			Stone *t = nil;

			if (i>0) {
				l = grid[i-1][j];
			}

			if (j>0) {
				t = grid[i][j-1];
			}

			//Horizontal Grouping
			if (l && l.stoneType == d.stoneType)
			{
				[[groupings objectAtIndex:l.curHGroup] addObject:grid[i][j]];
				grid[i][j].curHGroup = l.curHGroup;

			} else {
				curHGroup = lastGroup + 1;
				NSMutableSet *group = [[NSMutableSet alloc] init];
				[groupings addObject:group];
				[group release];
				[[groupings objectAtIndex:curHGroup] addObject:grid[i][j]];
				grid[i][j].curHGroup = curHGroup;
				lastGroup = curHGroup;
			}

			//Vertical Grouping
			if (t && t.stoneType == d.stoneType) {

				[[groupings objectAtIndex:t.curVGroup] addObject:grid[i][j]];
				grid[i][j].curVGroup = t.curVGroup;
			} else {
				curVGroup = lastGroup + 1;

				NSMutableSet * group2 = [[NSMutableSet alloc]init];
				[groupings addObject:group2];
				[group2 release];
				[[groupings objectAtIndex:curVGroup] addObject:grid[i][j]];
				grid[i][j].curVGroup = curVGroup;
				lastGroup = curVGroup;

			}
		}
	}

	BOOL moveStones = NO;
	for (NSMutableSet * n in groupings)  {

		CGPoint averagePos = CGPointZero;

		if ([n count] >= 3) {
			for(Stone * c in n){
				c.disappearing = YES;
				moveStones = YES;
				[c.mySprite setOpacity:95];
				//[c.mySprite setTexture:[[CCTextureCache sharedTextureCache] addImage:@"sSmile.png"]];
				//[c.mySprite setTextureRect:CGRectMake(34, 2, 32, 32)];
				//[c.mySprite runAction:[CCFadeOut actionWithDuration:0.5]];
				//*/
				 CCAction * action = [CCSpawn actions:
									  [CCFadeOut actionWithDuration:0.5],
									  [CCScaleTo actionWithDuration:0.5 scale:0.5],nil];
				[c.mySprite runAction:action];
				//*/

				score += 100 * [n count];
				NSLog(@"Score: %d",score);
				CCLabelAtlas *label = [(CCLabelAtlas *) self getChildByTag:kScoreLabel];
				[label setString:[NSString stringWithFormat:@"%d",score]];

				// TODO: enviar errata en el libro dice cp y es ccp p138
				averagePos = ccp(averagePos.x + c.mySprite.position.x, averagePos.y + c.mySprite.position.y);
			}

			averagePos = ccp(averagePos.x/[n count],averagePos.y/[n count]);

			int newScore = 100 * [n count];
			score += newScore;

			// TODO: CCBitmapFontAtlas deprecated use CCLabelBMFont instead
			//CCBitmapFontAtlas *feedTxt = [CCBitmapFontAtlas bitmapFontAtlasWithString:[NSString stringWithFormat:@"%d",newScore] fntFile:@"feedbackFont.fnt"];
			CCLabelBMFont *feedTxt = [CCLabelBMFont labelWithString:[NSString stringWithFormat:@"%d",newScore] fntFile:@"feedbackFont.fnt"];

			[feedTxt setPosition:averagePos];
			[feedTxt setColor:ccRED];
			[self addChild:feedTxt z:5];

			float dTime = 0;
			for (CCSprite *p in [feedTxt children]) {
				[p runAction:[CCSequence actions: [CCDelayTime actionWithDuration:1 + (dTime/3)],
												  [CCMoveBy actionWithDuration:1 position:ccp(0,30)],
												   nil
												   ]];
				dTime++;
			}

			[feedTxt runAction:[CCSequence actions: [CCFadeIn actionWithDuration:1],
								[CCDelayTime actionWithDuration:1],
								[CCFadeOut actionWithDuration:1],
								[CCCallFuncN actionWithTarget:self selector:@selector(removeSprite:)],
								nil
								]];

			/*/
			CCSprite * b  = (CCSprite *)[self getChildByTag:kGBack];
			CCAction * act = [CCSequence actions:[CCScaleTo actionWithDuration:0.2 scale:0.9],[CCScaleTo actionWithDuration:0.2 scale:1],nil];
			[b runAction:[CCRepeat actionWithAction:act times:3]];

			//*/
			/*/
			CCSpriteBatchNode * s = (CCSpriteBatchNode *)[self getChildByTag:kSSheet];
			CCSprite *b = (CCSprite *) [s getChildByTag:kGBack];

			//CCActionInterval removes warning
			CCAction * act = [CCSequence actions:
										[CCScaleTo actionWithDuration:0.2 scale:0.9],
										[CCScaleTo actionWithDuration:0.1 scale:1],nil];
			[b runAction:[CCRepeat actionWithAction:act times:3]];
			//*/

		}

		if ([n count] >= 4) {
			[self changeTime:50];
		}

		if ([n count] >= 5) {
			NSLog(@">>>>>>>>>>        run effect!!!!!!");

			/*/
			//
			//
			//TODO: ver porque no funciona si usas el sprite desde CCSpriteBatchNode
			//
			//
			CCSpriteBatchNode *s = (CCSpriteBatchNode *)[self getChildByTag:kSSheet];
			CCSprite *back = (CCSprite *) [s getChildByTag:kBack];
			/*/
			CCSprite *back = (CCSprite *) [self getChildByTag:kBack];
			//*/

			CCAction * effect = [CCSequence actions:
									[CCWaves actionWithWaves:10 amplitude:10 horizontal:YES vertical:YES grid:ccg(10, 10) duration:3],
									[CCStopGrid action],nil];
			[back runAction:effect];

			/*/
			//copy effect
			CCAction * effect2 = [[effect copy]autorelease];
			[bar runAction:effect2];
			//*/
		}
	}

	[groupings release];

	//[self unschedule:@selector(moveStonesDown)];

	if (moveStones) {
		//[self moveStonesDown];
		[self schedule:@selector(moveStonesDown) interval:1.0];
	}else {

		if (firstTime) {
			[self changeTime:-50];
		}

		self.allowTouch = YES;
	}

}

-(void)moveStonesDown
{
	[self unschedule:@selector(moveStonesDown)];

	self.allowTouch = NO;

	NSMutableArray * removeds = [[NSMutableArray alloc]init];

	for(int i =0; i< GRID_WIDTH ; i++)
	{
		int nilCount =0;
		for(int j =0; j< GRID_HEIGHT ; j++)
		{
			Stone * stone = grid[i][j];
			if(nilCount >0)
			{
				grid[i][j] = nil;
				grid[i][j -nilCount] = stone;
			}

			if(stone.disappearing)
			{
				nilCount ++;
				[removeds addObject:stone];
			}

			if(nilCount >0 && !stone.disappearing)
			{
				//[stone.mySprite setPosition:ccp(42*i + GRID_OFFSET.x,42*(j-nilCount) + GRID_OFFSET.y)];
				//[stone.mySprite runAction:[CCMoveTo actionWithDuration:0.5*nilCount/3 position:ccp(42*i + GRID_OFFSET.x,42*(j-nilCount) + GRID_OFFSET.y)]];

				CCAction *easeA = [CCEaseBounceOut actionWithAction:[CCMoveTo actionWithDuration:0.5*nilCount/3 position:ccp(42*i + GRID_OFFSET.x,42*(j-nilCount) + GRID_OFFSET.y)]];
				[stone.mySprite runAction:easeA];

			}
		}

		int q =0;
		for(Stone * stone in removeds)
		{
			[stone.mySprite setOpacity:255];
			int stoneT = arc4random() % STONE_TYPES;

			/*/
			NSString* color = [stone setStoneColor:stoneT];
			[stone.mySprite setTexture:[[CCTextureCache sharedTextureCache] addImage:[NSString stringWithFormat:@"s%@.png",color]]];
			/*/
			CGRect color =[stone setStoneColor:stoneT];
			[stone.mySprite setTextureRect:color];

			[stone setAnimation];

			//*/
			//[stone.mySprite setPosition:ccp(42*i + GRID_OFFSET.x,42*(GRID_HEIGHT -nilCount +q) + GRID_OFFSET.y)];

			//[stone.mySprite runAction:[CCMoveTo actionWithDuration:0.5 position:ccp(42*i + GRID_OFFSET.x,42*(GRID_HEIGHT -nilCount +q) + GRID_OFFSET.y)]];

			/*/
			CCAction *action = [CCSequence actions:
								[CCMoveTo actionWithDuration:0.5 position:ccp(42*i + GRID_OFFSET.x,42*(GRID_HEIGHT -nilCount +q) + GRID_OFFSET.y)],
								[CCScaleTo actionWithDuration:0.5 scale:1], nil ];
			[stone.mySprite runAction:action];
			/*/

			CCAction *easeA = [CCEaseBounceOut actionWithAction:[CCMoveTo actionWithDuration:0.5 position:ccp(42*i + GRID_OFFSET.x,42*(GRID_HEIGHT -nilCount +q) + GRID_OFFSET.y)]];
			CCAction *action = [CCSequence actions:easeA,[CCScaleTo actionWithDuration:0.5 scale:1], nil];
			[stone.mySprite runAction:action];

			//*/
			grid[i][GRID_HEIGHT -nilCount +q] = stone;
			q++;
		}
		[removeds removeAllObjects];
	}
	[self schedule:@selector(checkGroupsAgain) interval:1.0];
}

-(void)checkGroupsAgain
{
	[self unschedule:@selector(checkGroupsAgain)];
	[self checkGroups:NO];
}

// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
	// in case you have something to dealloc, do it in this method
	// in this particular example nothing needs to be released.
	// cocos2d will automatically release all the children (Label)

	// don't forget to call "super dealloc"
	[super dealloc];
}
@end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<title>SoundManager 2: Basic Video Template</title>

<link rel="stylesheet" href="template.css" />

SoundManager 2: Basic Video Example

This is a simple example showing how video can be loaded and played by SM2, with Flash 9.0r115+ (codename "MovieStar", AKA Flash 9 update 3.) See related Flash 9 release notes for supported formats.

How it works

This page includes the SoundManager 2 script which starts up ASAP, and assigns a few video-specific parameters. Javascript API calls can then be made to create, load and play certain MPEG4 video files.

Double-click the video to go full-screen.

Direct video link: Source .MP4

Code

soundManager.url = '../../swf/'; // path to directory containing SoundManager2 .SWF file
soundManager.flashVersion = 9;
soundManager.useMovieStar = true;
soundManager.allowFullScreen = true;

soundManager.onload = function() {
  // soundManager.createSound() etc. may now be called
  soundManager.createVideo({
    id:'photos3Demo',
    url:'http://freshly-ground.com/data/video/Yahoo! Photos 3 UI.MP4'
  });
  soundManager.play('photos3Demo');
}

Metadata, displaying the movie and so on

Additionally, an onmetadata() function handler may be assigned which will be called when meta data is available, including video dimensions (width/height). This is useful for setting the dimensions of the SWF, and/or positioning the container.

Note that to "hide" a movie, positioning or CSS visibility should be used; display:none will destroy a flash movie, and will break things. Also, only one movie can be played at a time.

redpajama_set_name: RedPajamaGithub


text:
namespace HtmlGenerator
{
    public class HtmlFormElement : HtmlElement
    {
        public HtmlFormElement() : base("form") { }

        public HtmlFormElement WithAcceptCharset(string value) => this.WithAttribute(Attribute.AcceptCharset(value));

        public HtmlFormElement WithAction(string value) => this.WithAttribute(Attribute.Action(value));

        public HtmlFormElement WithAutoComplete(string value) => this.WithAttribute(Attribute.AutoComplete(value));

        public HtmlFormElement WithEncType(string value) => this.WithAttribute(Attribute.EncType(value));

        public HtmlFormElement WithMethod(string value) => this.WithAttribute(Attribute.Method(value));

        public HtmlFormElement WithName(string value) => this.WithAttribute(Attribute.Name(value));

        public HtmlFormElement WithNoValidate() => this.WithAttribute(Attribute.NoValidate);

        public HtmlFormElement WithTarget(string value) => this.WithAttribute(Attribute.Target(value));
    }
}


text:
var config = require("../../shared/config");
var httpModule = require("http");
var observableArrayModule = require("data/observable-array");

function GroceryListViewModel(items) {
	var viewModel = new observableArrayModule.ObservableArray(items);

	viewModel.load = function() {
		httpModule.getJSON({
			url: config.apiUrl + "Groceries",
			method: "GET",
			headers: {
				"Authorization": "Bearer " + config.token
			}
		}).then(function(data) {
			data.Result.forEach(function(grocery) {
				viewModel.push({
					name: grocery.Name,
					id: grocery.Id
				});
			});
		});
	};

	viewModel.empty = function() {
		while (viewModel.length) {
			viewModel.pop();
		}
	};

	viewModel.add = function(grocery) {
		return new Promise(function(resolve, reject) {
			httpModule.request({
				url: config.apiUrl + "Groceries",
				method: "POST",
				content: JSON.stringify({
					Name: grocery
				}),
				headers: {
					"Authorization": "Bearer " + config.token,
					"Content-Type": "application/json"
				}
			}).then(function() {
				viewModel.push({ name: grocery });
				resolve();
			}).catch(function(error) {
				console.log(error);
				reject();
			});
		});
	};

	viewModel.delete = function(index) {
		return new Promise(function(resolve, reject) {
			httpModule.request({
				url: config.apiUrl + "Groceries/" + viewModel.getItem(index).id,
				method: "DELETE",
				headers: {
					"Authorization": "Bearer " + config.token,
					"Content-Type": "application/json"
				}
			}).then(function() {
				viewModel.splice(index, 1);
				resolve();
			}).catch(function(error) {
				console.log(error);
				reject();
			});
		});
	};

	return viewModel;
}

module.exports = GroceryListViewModel;


text:
{% extends "stats/base.html" %}

{% block content %}

{% for table in tables %}
{% include 'stats/table.html' with table=table %}
{% endfor %}

{% endblock content %}


text:
using System;

namespace Avalonia.Utilities
{
    /// <summary>
    /// Defines a listener to a event subscribed vis the <see cref="WeakSubscriptionManager"/>.
    /// </summary>
    /// <typeparam name="T">The type of the event arguments.</typeparam>
    public interface IWeakSubscriber<T> where T : EventArgs
    {
        /// <summary>
        /// Invoked when the subscribed event is raised.
        /// </summary>
        /// <param name="sender">The event sender.</param>
        /// <param name="e">The event arguments.</param>
        void OnEvent(object? sender, T e);
    }
}


text:
package org.eclipse.gemini.blueprint.service.exporter.support;

import org.eclipse.gemini.blueprint.util.internal.ClassUtils;
import org.springframework.core.enums.StaticLabeledEnum;

/**
 * Enum-like class indicatin class exporters available to {@link OsgiServiceFactoryBean} for registering object as OSGi
 * services.
 *
 * @author Costin Leau
 * @deprecated as of 2.0, replaced by {@link InterfaceDetector}
 */
public abstract class AutoExport extends StaticLabeledEnum implements InterfaceDetector {

	/** Do not export anything */
	public static final AutoExport DISABLED = new AutoExport(0, "DISABLED") {

		private static final long serialVersionUID = -8297270116184239840L;

		private final Class<?>[] clazz = new Class[0];

		Class<?>[] getExportedClasses(Class<?> targetClass) {
			return clazz;
		}
	};

	/**
	 * Export all interfaces (and their hierarchy) implemented by the given class
	 */
	public static final AutoExport INTERFACES = new AutoExport(1, "INTERFACES") {

		private static final long serialVersionUID = -8336152449611885031L;

		public Class<?>[] getExportedClasses(Class<?> targetClass) {
			return ClassUtils.getClassHierarchy(targetClass, ClassUtils.ClassSet.INTERFACES);
		}
	};

	/**
	 * Export the class hierarchy (all classes inherited by the given target excluding Object.class)
	 */
	public static final AutoExport CLASS_HIERARCHY = new AutoExport(2, "CLASS_HIERARCHY") {

		private static final long serialVersionUID = 6464782616822538297L;

		public Class<?>[] getExportedClasses(Class<?> targetClass) {
			return ClassUtils.getClassHierarchy(targetClass, ClassUtils.ClassSet.CLASS_HIERARCHY);

		}
	};

	/**
	 * Export every class, inherited or implemented by the given target. Similar to {@link #CLASS_HIERARCHY} +
	 * {@link #INTERFACES}
	 */
	public static final AutoExport ALL_CLASSES = new AutoExport(3, "ALL_CLASSES") {

		private static final long serialVersionUID = -6628398711158262852L;

		public Class<?>[] getExportedClasses(Class<?> targetClass) {
			return ClassUtils.getClassHierarchy(targetClass, ClassUtils.ClassSet.ALL_CLASSES);
		}
	};

	/**
	 * Determines the exported classes given a certain target class.
	 *
	 * @param targetClass class to be exported into OSGi
	 * @return array of classes that will be published for the OSGi service.
	 */
	abstract Class<?>[] getExportedClasses(Class<?> targetClass);

	public final Class<?>[] detect(Class<?> targetClass) {
		return getExportedClasses(targetClass);
	}

	/**
	 * Constructs a new AutoExport instance.
	 *
	 * @param code
	 * @param label
	 */
	private AutoExport(int code, String label) {
		super(code, label);
	}
}


text:
'use strict';

const CompositeError = require('..');

const error1 = new Error('Something went wrong');
const error2 = new Error('Something else went wrong');
const compositeError = new CompositeError('Multiple errors occurred', [error1, error2]);

console.log(compositeError.stack);


text:
from distutils.core import setup
import os

# Stolen from django-registration
# Compile the list of packages available, because distutils doesn't have
# an easy way to do this.
packages, data_files = [], []
root_dir = os.path.dirname(__file__)
if root_dir:
    os.chdir(root_dir)

for dirpath, dirnames, filenames in os.walk('jquery'):
    # Ignore dirnames that start with '.'
    for i, dirname in enumerate(dirnames):
        if dirname.startswith('.'):
            del dirnames[i]
    if '__init__.py' in filenames:
        pkg = dirpath.replace(os.path.sep, '.')
        if os.path.altsep:
            pkg = pkg.replace(os.path.altsep, '.')
        packages.append(pkg)
    elif filenames:
        prefix = dirpath[len('jquery/'):]
        for f in filenames:
            data_files.append(os.path.join(prefix, f))

setup(
    name='django-staticfiles-jquery',
    version=open("./VERSION").read(),
    description='jQuery meets Django staticfiles',
    author='Travis Swicegood',
    author_email='development@domain51.com',
    url='http://github.com/tswicegood/django-staticfiles-jquery/',
    packages=packages,
    package_data={'jquery': data_files},
    classifiers=[
        'Development Status :: 5 - Production/Stable',
        'Environment :: Web Environment',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: BSD License',
        'Operating System :: OS Independent',
        'Programming Language :: Python',
        'Topic :: Software Development :: Libraries :: Python Modules',
        'Topic :: Utilities',
    ],
)


text:
package org.csstudio.ui.fx.util;

import static org.csstudio.ui.fx.util.FXUtilities.setGridConstraints;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;

import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;

/**
 *
 * FXTaggingDialog is a Jface based input dialog using JavaFX components to input the tag name and tag
 * message.
 *
 * @author Jaka Bobnar
 *
 */
public class FXTaggingDialog extends FXBaseDialog<String> {

    private TextField tagName;
    private TextArea tagMessage;

    /**
     * Creates an input dialog with OK and Cancel buttons. Note that the dialog will have no visual representation (no
     * widgets) until it is told to open.
     *
     * @param parentShell the parent shell, or null to create a top-level shell
     */
    public FXTaggingDialog(Shell parentShell) {
        super(parentShell, "Tag Snapshot",
            "Provide the name of the tag and an optional tag message for the selected snapshot:", "",
            e -> (e == null || e.trim().isEmpty()) ? "The tag name cannot be empty." : null);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.csstudio.saverestore.ui.util.FXBaseDialog#setFocus()
     */
    @Override
    protected void setFocus() {
        tagName.requestFocus();
    }

    /*
     * (non-Javadoc)
     *
     * @see org.csstudio.saverestore.ui.util.FXBaseDialog#setValueToComponent(java.lang.Object)
     */
    @Override
    protected void setValueToComponent(String value) {
        tagName.setText(value);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.csstudio.saverestore.ui.util.FXBaseDialog#getValueFromComponent()
     */
    @Override
    protected String getValueFromComponent() {
        return tagName.getText();
    }

    /*
     * (non-Javadoc)
     *
     * @see org.csstudio.ui.fx.util.FXBaseDialog#getScene(org.eclipse.swt.widgets.Composite)
     */
    @Override
    protected Scene getScene(Composite parent) {
        GridPane pane = new GridPane();
        tagName = new TextField();
        tagName.textProperty().addListener((a, o, n) -> validateInput());
        pane.add(tagName, 0, 0);
        pane.add(new Label("Tag message:"), 0, 1);
        tagMessage = new TextArea();
        tagMessage.setEditable(true);
        GridPane.setMargin(tagName, new Insets(0, 0, 10, 0));
        GridPane.setMargin(tagMessage, new Insets(5, 0, 0, 0));
        setGridConstraints(tagMessage, true, true, Priority.ALWAYS, Priority.ALWAYS);
        setGridConstraints(tagName, true, true, Priority.ALWAYS, Priority.ALWAYS);
        pane.add(tagMessage, 0, 2);
        return new Scene(pane);
    }

    /**
     * Returns the string typed into the tag message area.
     *
     * @return the tag message
     */
    public String getMessage() {
        return tagMessage.getText();
    }
}


text:
<editor>
    <help>/commander/pages/@PLUGIN_NAME@/@PLUGIN_KEY@_help?s=Administration&ss=Plugins#Create VM</help>
    <formElement>
        Configuration:

        <configuration>1</configuration>

        <property>connection_config</property>
        <value/>
        <documentation>The name of the configuration which holds all the connection information for Windows Azure.</documentation>
        <required>1</required>
        <type>entry</type>
    </formElement>
    <formElement>
        Virtual Network name:
        <property>vnet_name</property>
        <value/>
        <documentation>Name of the new Virtual Network.</documentation>
        <required>1</required>
        <type>entry</type>
    </formElement>
    <formElement>
        Virtual Network address space:
        <property>vnet_address_space</property>
        <value>10.0.0.0/16</value>
        <documentation>The Virtual Network's address space in CIDR notion.It must be contained in one of the standard private address spaces:10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16. ex: 10.12.0.0/16 -> 10.12.0.0 - 10.12.255.255 (65536 addresses) </documentation>
        <required>1</required>
        <type>entry</type>
    </formElement>
    <formElement>
        Subnet name:
        <property>subnet_name</property>
        <value/>
        <documentation>Name of the new Subnet.</documentation>
        <required>1</required>
        <type>entry</type>
    </formElement>
    <formElement>
        Subnet address space:
        <property>subnet_address_space</property>
        <value>10.0.0.0/24</value>
        <documentation>The Subnet's address space in CIDR notion.It must be contained in one of the standard private address spaces:10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16. ex: 10.12.0.0/24 -> 10.12.0.0 - 10.12.0.255 (256 addresses) </documentation>
        <required>1</required>
        <type>entry</type>
    </formElement>
    <formElement>
        Custom DNS Server:
        <property>dns_server</property>
        <value>10.1.1.1</value>
        <documentation>Address of DNS Server.</documentation>
        <required>0</required>
        <type>entry</type>
    </formElement>
    <formElement>
        Resource Group Name:
        <property>resource_group_name</property>
        <value/>
        <documentation>The name of the resource group in which VM is to be created.</documentation>
        <required>1</required>
        <type>entry</type>
    </formElement>
    <formElement>
        <type>select</type>
        Location:
        <property>location</property>
        <required>1</required>
        <documentation>Location of the resource.</documentation>
        <option><name>Brazil South</name><value>brazilsouth</value></option>
        <option><name>Central US</name><value>centralus</value></option>
        <option><name>East Asia</name><value>eastasia</value></option>
        <option><name>East US</name><value>eastus</value></option>
        <option><name>East US 2</name><value>eastus2</value></option>
        <option><name>Japan East</name><value>japaneast</value></option>
        <option><name>Japan West</name><value>japanwest</value></option>
        <option><name>North Central US</name><value>northcentralus</value></option>
        <option><name>North Europe</name><value>northeurope</value></option>
        <option><name>South Central US</name><value>southcentralus</value></option>
        <option><name>Southeast Asia</name><value>southeastasia</value></option>
        <option><name>West Europe</name><value>westeurope</value></option>
        <option><name>West US</name><value>westus</value></option>
    </formElement>
    <formElement>
        JobStep Timeout:
        <property>job_step_timeout</property>
        <value/>
        <documentation>Timeout for the step execution in minutes. Blank means no timeout.</documentation>
        <required>0</required>
        <type>entry</type>
    </formElement>
</editor>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. Soc. mycol. Fr. 70(3): 321 (1955)

#### Original name
Pseudhaplosporella aurantiorum Speg.

### Remarks
null


text:
using System;
using System.ComponentModel.DataAnnotations;

namespace SimpleQA.Models
{
    public interface IAnswerId
    {
        [Required]
        String AnswerId { get; set; }

        [Required]
        String QuestionId { get; set; }
    }

    public interface IAnswerData
    {
        [Required]
        String QuestionId { get; set; }

        [Required]
        [StringLength(1000, MinimumLength = 10)]
        String Content { get; set; }
    }

    // fields are repeated so MetadataType can be used,
    // otherwise validations are not infered
    public interface IAnswer : IAnswerId, IAnswerData
    {
        [Required]
        String AnswerId { get; set; }

        [Required]
        String QuestionId { get; set; }

        [Required]
        [StringLength(1000, MinimumLength = 10)]
        String Content { get; set; }
    }
}


text:
'use strict';

import chai from 'chai';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import sinonAsPromised from 'sinon-as-promised';
import promised from 'chai-as-promised';
import userModel from '../../../server/models/users.server.model.user';
import userSeed from '../../../server/models/users.server.model.user.seed';
import mongooseModule from '../../../../core/server/app/mongoose';
import aclModule from '../../../server/config/acl';

chai.use(promised);
chai.use(sinonChai);

let expect = chai.expect;
let should = chai.should();

let sandbox;

describe('/modules/users/server/schemas/users.server.schema.address.js', () => {

  before(() => {
    return mongooseModule.connect()
      .then(Promise.all([aclModule.init(), userModel.init()]))
      .then(userSeed.seedUser);
  });

  beforeEach(() => {
    return sandbox = sinon.sandbox.create();
  });

  afterEach(() => {
    return sandbox.restore();
  });

  describe('presave', () => {
    let model, users;

    beforeEach(() => {
      model = userModel.getModels().user;
      return model
        .find()
        .then(result => {
          users = result;
        });
    });

    it('should set updated timestamp if modified', (done) => {
      let user = users[0];
      let timestamp = user.timestamps.updated;

      setTimeout(function () {
        user.addresses[0].streetAddress = ~user.addresses[0].streetAddress;

        user.save()
          .then(result => {
            result.addresses[0].timestamps.updated.toString().should.not.equal(timestamp.toString());
            return done();
          });
      }, 1001);

    });

    it('should not updated timestamp if not modified', (done) => {
      let user = users[0];
      let timestamp = user.timestamps.updated;

      setTimeout(function () {
        user.save()
          .then(result => {
            result.addresses[0].timestamps.updated.toString().should.equal(timestamp.toString());
            return done();
          });
      }, 1001);

    });

  });

});


text:
package org.jboard.jboard.utilities;

import java.io.File;

/**
 * Utilities for files.
 *
 * @author Asher Stern
 * Date: Aug 24, 2014
 *
 */
public class FileUtilities
{
	public static final char EXTENSION_MARKER = '.';

	public static String getExtension(File file)
	{
		String name = file.getAbsolutePath();
		int index = name.lastIndexOf(EXTENSION_MARKER);
		if (index<=0)
		{
			return "";
		}
		else
		{
			if ((index+1)<name.length())
			{
				return name.substring(index+1);
			}
			else
			{
				return "";
			}
		}
	}
}


text:
<?php

/**
 * Adminhtml poll answer controller
 *
 * @category   Mage
 * @package    Mage_Adminhtml
 * @author      Magento Core Team <core@magentocommerce.com>
 */

class Mage_Adminhtml_Poll_AnswerController extends Mage_Adminhtml_Controller_Action
{
    public function editAction()
    {
        $this->loadLayout();

        $this->_setActiveMenu('cms/poll');
        $this->_addBreadcrumb(Mage::helper('poll')->__('Poll Manager'),
                              Mage::helper('poll')->__('Poll Manager'), $this->getUrl('*/*/'));
        $this->_addBreadcrumb(Mage::helper('poll')->__('Edit Poll Answer'),
                              Mage::helper('poll')->__('Edit Poll Answer'));

        $this->_addContent($this->getLayout()->createBlock('adminhtml/poll_answer_edit'));

        $this->renderLayout();
    }

    public function saveAction()
    {
        //print '@@';
        if ( $post = $this->getRequest()->getPost() ) {
            try {
                $model = Mage::getModel('poll/poll_answer');
                $model->setData($post)
                    ->setId($this->getRequest()->getParam('id'))
                    ->save();

                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('poll')->__('The answer has been saved.'));
                $this->_redirect('*/poll/edit',
                                 array('id' => $this->getRequest()->getParam('poll_id'), 'tab' => 'answers_section'));
                return;
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
                $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
                return;
            }
        }
        $this->_redirect('*/*/');
    }

    public function gridAction()
    {
        $this->getResponse()->setBody(
            $this->getLayout()->createBlock('adminhtml/poll_edit_tab_answers_grid')->toHtml()
        );
    }

    public function jsonSaveAction()
    {
        $response = new Varien_Object();
        $response->setError(0);

        if ( $post = $this->getRequest()->getPost() ) {
            $data = Zend_Json::decode($post['data']);
            try {
                if( trim($data['answer_title']) == '' ) {
                    throw new Exception(Mage::helper('poll')->__('Invalid Answer.'));
                }
                $model = Mage::getModel('poll/poll_answer');
                $model->setData($data)
                    ->save();
            } catch (Exception $e) {
                $response->setError(1);
                $response->setMessage($e->getMessage());
            }
        }
        $this->getResponse()->setBody( $response->toJson() );
    }

    public function jsonDeleteAction()
    {
        $response = new Varien_Object();
        $response->setError(0);

        if ( $id = $this->getRequest()->getParam('id') ) {
            try {
                $model = Mage::getModel('poll/poll_answer');
                $model->setId(Zend_Json::decode($id))
                    ->delete();
            } catch (Exception $e) {
                $response->setError(1);
                $response->setMessage($e->getMessage());
            }
        } else {
            $response->setError(1);
            $response->setMessage(Mage::helper('poll')->__('Unable to find an answer to delete.'));
        }
        $this->getResponse()->setBody( $response->toJson() );
    }

    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')->isAllowed('cms/poll');
    }

}


text:
package github.jk1.editor.web;

import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

import javax.servlet.ServletException;
import java.io.IOException;

import static org.junit.Assert.*;

/**
 * @author Evgeny Naumenko
 */
public class AuthenticationFilterTest {

    private LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalUserServiceTestConfig());
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;
    private MockFilterChain chain;
    private static final String REDIRECT_URL = "/_ah/login?continue=";

    private AuthenticationFilter filter;

    @Before
    public void setUp() {
        helper.setUp();
        filter = new AuthenticationFilter();
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
        chain = new MockFilterChain();
    }

    @After
    public void tearDown() {
        helper.tearDown();
    }

    @Test
    public void testLoggedIn() throws IOException, ServletException {
        helper.setEnvIsLoggedIn(true);

        filter.doFilter(request, response, chain);

        assertNull(response.getRedirectedUrl());
        assertNotNull(chain.getRequest());
    }

    @Test
    public void testNotLoggedIn() throws IOException, ServletException {
        helper.setEnvIsLoggedIn(false);

        filter.doFilter(request, response, chain);

        assertEquals(REDIRECT_URL, response.getRedirectedUrl());
    }

    @Test
    public void testRequestStatic() throws IOException, ServletException {
        helper.setEnvIsLoggedIn(false);
        request.setRequestURI("/img/icon.png");

        filter.doFilter(request, response, chain);

        assertNull(response.getRedirectedUrl());
        assertNotNull(chain.getRequest());
    }

    @Test
    public void testChannelCommunication() throws IOException, ServletException {
        helper.setEnvIsLoggedIn(false);
        request.setRequestURI("/_ah/channel/request");

        filter.doFilter(request, response, chain);

        assertNull(response.getRedirectedUrl());
        assertNotNull(chain.getRequest());
    }
}


text:
  * Enhance the warning message produced by the cli() method to recommend the corresponding rpc() call. #60
  * Enhance the sw.install() method with basic ISSU and NSSU support using the issu and nssu boolean arguments. #606
  ** NSSU support has not yet been tested and should currently be considered experimental.
  * Fix: Updated the interface-name glob pattern to correctly match et-x/y/z interfaces in several tables and views. #609
  * Fix: To take care of special chars on screen during console connection. #610
  * Enhance reboot() method to take a bool param all_re to decide if only connected dev to be rebooted or all. #613
  * Fix: Address issue with fact gathering stopping when it encounters a problem. #615

# Release 2.0.1

  * StartShell to take timeout (30 second by default) as paramter
  * Proper exception handling in case of Console connection #595
  * Fix: Config.lock() return exception when normalize is on
  * Added microbadge badge for the Docker image #593
  * Fix: print dev for Console conn was printing object not Device(....) #591
  * Fix: To take care of special chars with StartShell->run function call #589
  * Fix: ssh private key file to be considered for scp util #586
  * Added Dockerfile to enable automated image builds on project commits #585

# Release 2.0.0

  * Console connection using PyEZ
  * Python >=3.4 support
  * Configuration Tables to Define and Configure Structured Resources
  * JSON Config load
  * FTP Utility
  * Multi RPC error
  * various bug fixes

Refer below link for more details:
https://github.com/Juniper/py-junos-eznc/releases/tag/2.0.0

# Release 1.0

# Junos PyEZ Overview

The Junos PyEZ project is an open-source Apache 2.0 library for the Python programming language.  The purpose of this "micro-framework" library is to enable the networking professional community to effectively utilize the Junos OS NETCONF and XML APIs.

The Junos PyEZ library can be used on any number of server environments supporting Python 2.6 and 2.7.

At the time of this writing, Junos PyEZ is not distributed on devices running Junos OS.

For feature documentation and community support, refer to the following URLs:
  * Project Page hosted on the Juniper Networks TechWiki:
http://techwiki.juniper.net/Automation_Scripting/Junos_PyEZ
  * Source code hosted on Github:
https://github.com/Juniper/py-junos-eznc
  * Support forum hosted using Google Groups:
https://groups.google.com/forum/#!forum/junos-python-ez

# Installing Junos PyEZ
Junos PyEZ can be installed directly from the PyPi repository by typing `pip install junos-eznc` at the system command line.

The "pip" installation process also installs any related dependent Python modules and libraries.  Depending on your specific system, you might need to have the prerequisite build tools installed as well.

For the complete set of installation instructions for various platforms, see the Junos PyEZ project documentation at https://techwiki.juniper.net/Automation_Scripting/Junos_PyEZ/Installation.

# Recommended Junos Release
Junos PyEZ can be used with any device running Junos OS, because they all support the NETCONF and Junos XML APIs.   To take full advantage of the Junos PyEZ features, we recommend using Junos OS Release 11.4 or later release - see "Known Limitations and Restrictions" section for details.  For more information about Junos OS releases, refer to the Juniper Networks technical documentation site at https://www.juniper.net/techpubs/en_US/release-independent/junos/information-products/pathway-pages/junos/product/index.html .

# Supported Python Releases
The Junos PyEZ library has been tested with Python versions 2.6 and 2.7.
At the time of this writing PyEZ is not supported in Python 3.x environments.  This restriction is due to dependencies on other Python modules, such as ncclient, that do not support Python 3.x.

# Known Limitations and Restrictions
## General
  * Junos PyEZ maintains a "timeout" mechanism for each executed command and response pair.  The default timeout is 30 seconds.  You can override the default by using the Device.timeout property.  If a timeout does occur, a timeout exception is raised.
  * Some devices running Junos OS might disconnect the NETCONF session due to inactivity.  This behavior has been observed on SRX Series Services Gateways.  In such cases, an exception is raised upon execution of the next command.  The Junos PyEZ library does not reconnect to the device in these inactivity scenarios.  However, you can call Device.open() to reconnect.
  * Command execution is synchronous and blocking.  The underlying NETCONF transport library is the ncclient module.  If your application requires asynchronous or nonblocking execution logic, you should investigate other libraries to wrap around the PyEZ framework such as Twisted or Python Threads.
  * The `Device.cli()` method is intended to be used with interactive python, and as a means to facilitate the interactive experience as needed.  Please do not use this for "screen-scraping" the CLI output for automation purposes.

## Version-Specific Limitations
A couple software version-dependent limitations that must be noted:
* 11.4 - This is the first release where the Junos XML API supports the ability to retrieve the command output in text (CLI) format.  Prior to Junos OS Release 11.4, the response output was in XML.  If you use the Device.cli() feature, note that this only works with Junos OS Release 11.4 and later releases.
* 11.4 - This is the first release where the Junos XML API supports the ability to load configuration changes using Junos OS set commands.

## Restrictions
### Primary Routing Engine
For devices with multiple Routing Engines, you can only connect to the primary Routing Engine.  If you attempt to connect to the backup Routing Engine, the Device.open() method fails with an exception.

### Junos OS Software Upgrade
The primary restriction is on software-install functionality provided by the jnpr.junos.utils.sw module.  The software-install process is currently designed to support simple deployment scenarios.  The expected use case for this software is deploying new equipment.  The following scenarios are supported:
* Standalone devices with a single Routing Engine, for example EX4200 switches
* Standalone devices equipped with dual Routing Engines, for example MX960 routers
* EX Series Virtual Chassis in non-mixed-mode configurations (all devices use the same Junos OS software package)
* Deployment configurations that do not have any form of "in-service" features enabled, such as unified ISSU and NSSU.

The following scenarios are known not to be supported:
* SRX Series chassis clusters
* EX Series Virtual Chassis in mixed-mode configurations (devices use different Junos OS software packages)
* Virtual Chassis Fabric (VCF)
* MX Series Virtual Chassis
* Any deployments with "in-service" configurations enabled (such as unified ISSU or NSSU)


text:
../../crispr.pl --conf conf.txt --amp_fasta amp.fa --crispr site.bed \
	--sitemap sample.site --fastqmap fastq.list --codon_start 1


text:
import { Injectable } from '@angular/core';
import { Http, Headers, URLSearchParams } from '@angular/http';
import {Observable} from 'rxjs/Rx';
import 'rxjs/add/operator/map';

@Injectable()
export class RestService {

  host: string = "http://osiris.ubishops.ca";

  constructor(private _http: Http) {}

  getMessages() {
    return this._http.get(this.host + '/~gbianchet/restapi?method=chat').map(res => res.json());
  }

  sendMessage(username: string, message: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this._http.get(this.host + '/~gbianchet/restapi?method=chat1&username=' + username + '&message=' + message, {
      headers: headers
    })
      .map(res => res.json());
  }

  login(username: string, password: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this._http.get(this.host + '/~gbianchet/restapi?method=login&username=' + username + '&password=' + password, {
      headers : headers
    }).map(res => res.json());
  }

  createUser(firstname: string, lastname: string, email: string, username: string, password: string) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this._http.get(this.host + '/~gbianchet/restapi?method=create&firstname=' + firstname + "&lastname="
      + lastname + '&email=' + email + '&username=' + username + '&password=' + password,{
      headers : headers
    }).map(res => res.json());
  }

  getProfile(username: string) {
    return this._http.get(this.host + '/~gbianchet/restapi?method=profile&username=' + username).map(res => res.json());
  }

  getLeader() {
    return this._http.get(this.host + '/~gbianchet/restapi?method=leaderboard').map(res => res.json());
  }

  sendRes(username: string, res: number) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    return this._http.get(this.host + '/~gbianchet/restapi?method=stats&username=' + username + '&win=' + res, {
      headers : headers
    }).map(res => res.json());
  }

}


text:
package org.apache.carbondata.core.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.carbondata.common.logging.LogService;
import org.apache.carbondata.common.logging.LogServiceFactory;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.datastore.block.SegmentProperties;
import org.apache.carbondata.core.datastore.compression.CompressorFactory;
import org.apache.carbondata.core.datastore.compression.WriterCompressModel;
import org.apache.carbondata.core.metadata.BlockletInfoColumnar;
import org.apache.carbondata.core.metadata.ColumnarFormatVersion;
import org.apache.carbondata.core.metadata.ValueEncoderMeta;
import org.apache.carbondata.core.metadata.index.BlockIndexInfo;
import org.apache.carbondata.format.BlockIndex;
import org.apache.carbondata.format.BlockletBTreeIndex;
import org.apache.carbondata.format.BlockletIndex;
import org.apache.carbondata.format.BlockletInfo;
import org.apache.carbondata.format.BlockletInfo2;
import org.apache.carbondata.format.BlockletMinMaxIndex;
import org.apache.carbondata.format.ChunkCompressionMeta;
import org.apache.carbondata.format.ColumnSchema;
import org.apache.carbondata.format.CompressionCodec;
import org.apache.carbondata.format.DataChunk;
import org.apache.carbondata.format.DataChunk2;
import org.apache.carbondata.format.Encoding;
import org.apache.carbondata.format.FileFooter;
import org.apache.carbondata.format.IndexHeader;
import org.apache.carbondata.format.PresenceMeta;
import org.apache.carbondata.format.SegmentInfo;
import org.apache.carbondata.format.SortState;

/**
 * Util class to convert to thrift metdata classes
 */
public class CarbonMetadataUtil {

  /**
   * Attribute for Carbon LOGGER
   */
  private static final LogService LOGGER =
      LogServiceFactory.getLogService(CarbonMetadataUtil.class.getName());

  /**
   * It converts list of BlockletInfoColumnar to FileFooter thrift objects
   *
   * @param infoList
   * @param numCols
   * @param cardinalities
   * @return FileFooter
   */
  public static FileFooter convertFileFooter(List<BlockletInfoColumnar> infoList, int numCols,
      int[] cardinalities, List<ColumnSchema> columnSchemaList, SegmentProperties segmentProperties)
      throws IOException {
    FileFooter footer = getFileFooter(infoList, cardinalities, columnSchemaList);
    for (BlockletInfoColumnar info : infoList) {
      footer.addToBlocklet_info_list(getBlockletInfo(info, columnSchemaList, segmentProperties));
    }
    return footer;
  }

  /**
   * Below method will be used to get the file footer object
   *
   * @param infoList         blocklet info
   * @param cardinalities    cardinlaity of dimension columns
   * @param columnSchemaList column schema list
   * @return file footer
   */
  private static FileFooter getFileFooter(List<BlockletInfoColumnar> infoList, int[] cardinalities,
      List<ColumnSchema> columnSchemaList) {
    SegmentInfo segmentInfo = new SegmentInfo();
    segmentInfo.setNum_cols(columnSchemaList.size());
    segmentInfo.setColumn_cardinalities(CarbonUtil.convertToIntegerList(cardinalities));
    ColumnarFormatVersion version = CarbonProperties.getInstance().getFormatVersion();
    FileFooter footer = new FileFooter();
    footer.setVersion(version.number());
    footer.setNum_rows(getTotalNumberOfRows(infoList));
    footer.setSegment_info(segmentInfo);
    footer.setTable_columns(columnSchemaList);
    for (BlockletInfoColumnar info : infoList) {
      footer.addToBlocklet_index_list(getBlockletIndex(info));
    }
    return footer;
  }

  /**
   * Below method will be used to get the file footer object for
   *
   * @param infoList         blocklet info
   * @param cardinalities    cardinality of each column
   * @param columnSchemaList column schema list
   * @param dataChunksOffset data chunks offsets
   * @param dataChunksLength data chunks length
   * @return filefooter thrift object
   */
  public static FileFooter convertFilterFooter2(List<BlockletInfoColumnar> infoList,
      int[] cardinalities, List<ColumnSchema> columnSchemaList, List<List<Long>> dataChunksOffset,
      List<List<Short>> dataChunksLength) {
    FileFooter footer = getFileFooter(infoList, cardinalities, columnSchemaList);
    int index = 0;
    for (BlockletInfoColumnar info : infoList) {
      footer.addToBlocklet_info_list2(
          getBlockletInfo2(info, dataChunksOffset.get(index), dataChunksLength.get(index)));
      index++;
    }
    return footer;
  }

  private static BlockletIndex getBlockletIndex(
      org.apache.carbondata.core.metadata.blocklet.index.BlockletIndex info) {
    BlockletMinMaxIndex blockletMinMaxIndex = new BlockletMinMaxIndex();

    for (int i = 0; i < info.getMinMaxIndex().getMaxValues().length; i++) {
      blockletMinMaxIndex.addToMax_values(ByteBuffer.wrap(info.getMinMaxIndex().getMaxValues()[i]));
      blockletMinMaxIndex.addToMin_values(ByteBuffer.wrap(info.getMinMaxIndex().getMinValues()[i]));
    }
    BlockletBTreeIndex blockletBTreeIndex = new BlockletBTreeIndex();
    blockletBTreeIndex.setStart_key(info.getBtreeIndex().getStartKey());
    blockletBTreeIndex.setEnd_key(info.getBtreeIndex().getEndKey());
    BlockletIndex blockletIndex = new BlockletIndex();
    blockletIndex.setMin_max_index(blockletMinMaxIndex);
    blockletIndex.setB_tree_index(blockletBTreeIndex);
    return blockletIndex;
  }

  /**
   * Get total number of rows for the file.
   *
   * @param infoList
   * @return
   */
  private static long getTotalNumberOfRows(List<BlockletInfoColumnar> infoList) {
    long numberOfRows = 0;
    for (BlockletInfoColumnar info : infoList) {
      numberOfRows += info.getNumberOfKeys();
    }
    return numberOfRows;
  }

  private static BlockletIndex getBlockletIndex(BlockletInfoColumnar info) {

    BlockletMinMaxIndex blockletMinMaxIndex = new BlockletMinMaxIndex();
    for (byte[] max : info.getColumnMaxData()) {
      blockletMinMaxIndex.addToMax_values(ByteBuffer.wrap(max));
    }
    for (byte[] min : info.getColumnMinData()) {
      blockletMinMaxIndex.addToMin_values(ByteBuffer.wrap(min));
    }
    BlockletBTreeIndex blockletBTreeIndex = new BlockletBTreeIndex();
    blockletBTreeIndex.setStart_key(info.getStartKey());
    blockletBTreeIndex.setEnd_key(info.getEndKey());

    BlockletIndex blockletIndex = new BlockletIndex();
    blockletIndex.setMin_max_index(blockletMinMaxIndex);
    blockletIndex.setB_tree_index(blockletBTreeIndex);
    return blockletIndex;
  }

  /**
   * Below method will be used to get the blocklet info object for
   * data version 2 file
   *
   * @param blockletInfoColumnar blocklet info
   * @param dataChunkOffsets     data chunks offsets
   * @param dataChunksLength     data chunks length
   * @return blocklet info version 2
   */
  private static BlockletInfo2 getBlockletInfo2(BlockletInfoColumnar blockletInfoColumnar,
      List<Long> dataChunkOffsets, List<Short> dataChunksLength) {
    BlockletInfo2 blockletInfo = new BlockletInfo2();
    blockletInfo.setNum_rows(blockletInfoColumnar.getNumberOfKeys());
    blockletInfo.setColumn_data_chunks_length(dataChunksLength);
    blockletInfo.setColumn_data_chunks_offsets(dataChunkOffsets);
    return blockletInfo;
  }

  private static BlockletInfo getBlockletInfo(BlockletInfoColumnar blockletInfoColumnar,
      List<ColumnSchema> columnSchenma, SegmentProperties segmentProperties) throws IOException {

    BlockletInfo blockletInfo = new BlockletInfo();
    blockletInfo.setNum_rows(blockletInfoColumnar.getNumberOfKeys());

    List<DataChunk> colDataChunks = new ArrayList<DataChunk>();
    int j = 0;
    int aggregateIndex = 0;
    boolean[] isSortedKeyColumn = blockletInfoColumnar.getIsSortedKeyColumn();
    boolean[] aggKeyBlock = blockletInfoColumnar.getAggKeyBlock();
    boolean[] colGrpblock = blockletInfoColumnar.getColGrpBlocks();
    for (int i = 0; i < blockletInfoColumnar.getKeyLengths().length; i++) {
      DataChunk dataChunk = new DataChunk();
      dataChunk.setChunk_meta(getChunkCompressionMeta());
      List<Encoding> encodings = new ArrayList<Encoding>();
      if (containsEncoding(i, Encoding.DICTIONARY, columnSchenma, segmentProperties)) {
        encodings.add(Encoding.DICTIONARY);
      }
      if (containsEncoding(i, Encoding.DIRECT_DICTIONARY, columnSchenma, segmentProperties)) {
        encodings.add(Encoding.DIRECT_DICTIONARY);
      }
      dataChunk.setRowMajor(colGrpblock[i]);
      //TODO : Once schema PR is merged and information needs to be passed here.
      dataChunk.setColumn_ids(new ArrayList<Integer>());
      dataChunk.setData_page_length(blockletInfoColumnar.getKeyLengths()[i]);
      dataChunk.setData_page_offset(blockletInfoColumnar.getKeyOffSets()[i]);
      if (aggKeyBlock[i]) {
        dataChunk.setRle_page_offset(blockletInfoColumnar.getDataIndexMapOffsets()[aggregateIndex]);
        dataChunk.setRle_page_length(blockletInfoColumnar.getDataIndexMapLength()[aggregateIndex]);
        encodings.add(Encoding.RLE);
        aggregateIndex++;
      }
      dataChunk
          .setSort_state(isSortedKeyColumn[i] ? SortState.SORT_EXPLICIT : SortState.SORT_NATIVE);

      if (!isSortedKeyColumn[i]) {
        dataChunk.setRowid_page_offset(blockletInfoColumnar.getKeyBlockIndexOffSets()[j]);
        dataChunk.setRowid_page_length(blockletInfoColumnar.getKeyBlockIndexLength()[j]);
        encodings.add(Encoding.INVERTED_INDEX);
        j++;
      }

      //TODO : Right now the encodings are happening at runtime. change as per this encoders.
      dataChunk.setEncoders(encodings);

      colDataChunks.add(dataChunk);
    }

    for (int i = 0; i < blockletInfoColumnar.getMeasureLength().length; i++) {
      DataChunk dataChunk = new DataChunk();
      dataChunk.setChunk_meta(getChunkCompressionMeta());
      dataChunk.setRowMajor(false);
      //TODO : Once schema PR is merged and information needs to be passed here.
      dataChunk.setColumn_ids(new ArrayList<Integer>());
      dataChunk.setData_page_length(blockletInfoColumnar.getMeasureLength()[i]);
      dataChunk.setData_page_offset(blockletInfoColumnar.getMeasureOffset()[i]);
      //TODO : Right now the encodings are happening at runtime. change as per this encoders.
      List<Encoding> encodings = new ArrayList<Encoding>();
      encodings.add(Encoding.DELTA);
      dataChunk.setEncoders(encodings);
      //TODO writing dummy presence meta need to set actual presence
      //meta
      PresenceMeta presenceMeta = new PresenceMeta();
      presenceMeta.setPresent_bit_streamIsSet(true);
      presenceMeta
          .setPresent_bit_stream(blockletInfoColumnar.getMeasureNullValueIndex()[i].toByteArray());
      dataChunk.setPresence(presenceMeta);
      //TODO : PresenceMeta needs to be implemented and set here
      // dataChunk.setPresence(new PresenceMeta());
      //TODO : Need to write ValueCompression meta here.
      List<ByteBuffer> encoderMetaList = new ArrayList<ByteBuffer>();
      encoderMetaList.add(ByteBuffer.wrap(serializeEncoderMeta(
          createValueEncoderMeta(blockletInfoColumnar.getCompressionModel(), i))));
      dataChunk.setEncoder_meta(encoderMetaList);
      colDataChunks.add(dataChunk);
    }
    blockletInfo.setColumn_data_chunks(colDataChunks);

    return blockletInfo;
  }

  /**
   * @param blockIndex
   * @param encoding
   * @param columnSchemas
   * @param segmentProperties
   * @return return true if given encoding is present in column
   */
  private static boolean containsEncoding(int blockIndex, Encoding encoding,
      List<ColumnSchema> columnSchemas, SegmentProperties segmentProperties) {
    Set<Integer> dimOrdinals = segmentProperties.getDimensionOrdinalForBlock(blockIndex);
    //column groups will always have dictionary encoding
    if (dimOrdinals.size() > 1 && Encoding.DICTIONARY == encoding) {
      return true;
    }
    for (Integer dimOrdinal : dimOrdinals) {
      if (columnSchemas.get(dimOrdinal).encoders.contains(encoding)) {
        return true;
      }
    }
    return false;
  }

  private static byte[] serializeEncoderMeta(ValueEncoderMeta encoderMeta) throws IOException {
    // TODO : should remove the unnecessary fields.
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    ObjectOutputStream objStream = new ObjectOutputStream(aos);
    objStream.writeObject(encoderMeta);
    objStream.close();
    return aos.toByteArray();
  }

  private static ValueEncoderMeta createValueEncoderMeta(WriterCompressModel compressionModel,
      int index) {
    ValueEncoderMeta encoderMeta = new ValueEncoderMeta();
    encoderMeta.setMaxValue(compressionModel.getMaxValue()[index]);
    encoderMeta.setMinValue(compressionModel.getMinValue()[index]);
    encoderMeta.setDataTypeSelected(compressionModel.getDataTypeSelected()[index]);
    encoderMeta.setDecimal(compressionModel.getMantissa()[index]);
    encoderMeta.setType(compressionModel.getType()[index]);
    encoderMeta.setUniqueValue(compressionModel.getUniqueValue()[index]);
    return encoderMeta;
  }

  /**
   * Right now it is set to default values. We may use this in future
   */
  private static ChunkCompressionMeta getChunkCompressionMeta() {
    ChunkCompressionMeta chunkCompressionMeta = new ChunkCompressionMeta();
    chunkCompressionMeta.setCompression_codec(CompressionCodec.SNAPPY);
    chunkCompressionMeta.setTotal_compressed_size(0);
    chunkCompressionMeta.setTotal_uncompressed_size(0);
    return chunkCompressionMeta;
  }

  /**
   * It converts FileFooter thrift object to list of BlockletInfoColumnar objects
   *
   * @param footer
   * @return
   */
  public static List<BlockletInfoColumnar> convertBlockletInfo(FileFooter footer)
      throws IOException {
    List<BlockletInfoColumnar> listOfNodeInfo =
        new ArrayList<BlockletInfoColumnar>(CarbonCommonConstants.CONSTANT_SIZE_TEN);
    for (BlockletInfo blockletInfo : footer.getBlocklet_info_list()) {
      BlockletInfoColumnar blockletInfoColumnar = new BlockletInfoColumnar();
      blockletInfoColumnar.setNumberOfKeys(blockletInfo.getNum_rows());
      List<DataChunk> columnChunks = blockletInfo.getColumn_data_chunks();
      List<DataChunk> dictChunks = new ArrayList<DataChunk>();
      List<DataChunk> nonDictColChunks = new ArrayList<DataChunk>();
      for (DataChunk dataChunk : columnChunks) {
        if (dataChunk.getEncoders().get(0).equals(Encoding.DICTIONARY)) {
          dictChunks.add(dataChunk);
        } else {
          nonDictColChunks.add(dataChunk);
        }
      }
      int[] keyLengths = new int[dictChunks.size()];
      long[] keyOffSets = new long[dictChunks.size()];
      long[] keyBlockIndexOffsets = new long[dictChunks.size()];
      int[] keyBlockIndexLens = new int[dictChunks.size()];
      long[] indexMapOffsets = new long[dictChunks.size()];
      int[] indexMapLens = new int[dictChunks.size()];
      boolean[] sortState = new boolean[dictChunks.size()];
      int i = 0;
      for (DataChunk dataChunk : dictChunks) {
        keyLengths[i] = dataChunk.getData_page_length();
        keyOffSets[i] = dataChunk.getData_page_offset();
        keyBlockIndexOffsets[i] = dataChunk.getRowid_page_offset();
        keyBlockIndexLens[i] = dataChunk.getRowid_page_length();
        indexMapOffsets[i] = dataChunk.getRle_page_offset();
        indexMapLens[i] = dataChunk.getRle_page_length();
        sortState[i] = dataChunk.getSort_state().equals(SortState.SORT_EXPLICIT);
        i++;
      }
      blockletInfoColumnar.setKeyLengths(keyLengths);
      blockletInfoColumnar.setKeyOffSets(keyOffSets);
      blockletInfoColumnar.setKeyBlockIndexOffSets(keyBlockIndexOffsets);
      blockletInfoColumnar.setKeyBlockIndexLength(keyBlockIndexLens);
      blockletInfoColumnar.setDataIndexMapOffsets(indexMapOffsets);
      blockletInfoColumnar.setDataIndexMapLength(indexMapLens);
      blockletInfoColumnar.setIsSortedKeyColumn(sortState);

      int[] msrLens = new int[nonDictColChunks.size()];
      long[] msrOffsets = new long[nonDictColChunks.size()];
      ValueEncoderMeta[] encoderMetas = new ValueEncoderMeta[nonDictColChunks.size()];
      i = 0;
      for (DataChunk msrChunk : nonDictColChunks) {
        msrLens[i] = msrChunk.getData_page_length();
        msrOffsets[i] = msrChunk.getData_page_offset();
        encoderMetas[i] = deserializeValueEncoderMeta(msrChunk.getEncoder_meta().get(0));
        i++;
      }
      blockletInfoColumnar.setMeasureLength(msrLens);
      blockletInfoColumnar.setMeasureOffset(msrOffsets);
      blockletInfoColumnar.setCompressionModel(getValueCompressionModel(encoderMetas));
      listOfNodeInfo.add(blockletInfoColumnar);
    }

    setBlockletIndex(footer, listOfNodeInfo);
    return listOfNodeInfo;
  }

  private static ValueEncoderMeta deserializeValueEncoderMeta(ByteBuffer byteBuffer)
      throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream(byteBuffer.array());
    ObjectInputStream objStream = new ObjectInputStream(bis);
    ValueEncoderMeta encoderMeta = null;
    try {
      encoderMeta = (ValueEncoderMeta) objStream.readObject();
    } catch (ClassNotFoundException e) {
      LOGGER.error("Error while reading ValueEncoderMeta");
    }
    return encoderMeta;

  }

  private static WriterCompressModel getValueCompressionModel(ValueEncoderMeta[] encoderMetas) {
    Object[] maxValue = new Object[encoderMetas.length];
    Object[] minValue = new Object[encoderMetas.length];
    int[] decimalLength = new int[encoderMetas.length];
    Object[] uniqueValue = new Object[encoderMetas.length];
    char[] aggType = new char[encoderMetas.length];
    byte[] dataTypeSelected = new byte[encoderMetas.length];
    for (int i = 0; i < encoderMetas.length; i++) {
      maxValue[i] = encoderMetas[i].getMaxValue();
      minValue[i] = encoderMetas[i].getMinValue();
      decimalLength[i] = encoderMetas[i].getDecimal();
      uniqueValue[i] = encoderMetas[i].getUniqueValue();
      aggType[i] = encoderMetas[i].getType();
      dataTypeSelected[i] = encoderMetas[i].getDataTypeSelected();
    }
    return ValueCompressionUtil
        .getWriterCompressModel(maxValue, minValue, decimalLength, uniqueValue, aggType,
            dataTypeSelected);
  }

  private static void setBlockletIndex(FileFooter footer,
      List<BlockletInfoColumnar> listOfNodeInfo) {
    List<BlockletIndex> blockletIndexList = footer.getBlocklet_index_list();
    for (int i = 0; i < blockletIndexList.size(); i++) {
      BlockletBTreeIndex bTreeIndexList = blockletIndexList.get(i).getB_tree_index();
      BlockletMinMaxIndex minMaxIndexList = blockletIndexList.get(i).getMin_max_index();

      listOfNodeInfo.get(i).setStartKey(bTreeIndexList.getStart_key());
      listOfNodeInfo.get(i).setEndKey(bTreeIndexList.getEnd_key());
      byte[][] min = new byte[minMaxIndexList.getMin_values().size()][];
      byte[][] max = new byte[minMaxIndexList.getMax_values().size()][];
      for (int j = 0; j < minMaxIndexList.getMax_valuesSize(); j++) {
        min[j] = minMaxIndexList.getMin_values().get(j).array();
        max[j] = minMaxIndexList.getMax_values().get(j).array();
      }
      listOfNodeInfo.get(i).setColumnMaxData(max);
    }
  }

  /**
   * Below method will be used to get the index header
   *
   * @param columnCardinality cardinality of each column
   * @param columnSchemaList  list of column present in the table
   * @return Index header object
   */
  public static IndexHeader getIndexHeader(int[] columnCardinality,
      List<ColumnSchema> columnSchemaList, int bucketNumber) {
    // create segment info object
    SegmentInfo segmentInfo = new SegmentInfo();
    // set the number of columns
    segmentInfo.setNum_cols(columnSchemaList.size());
    // setting the column cardinality
    segmentInfo.setColumn_cardinalities(CarbonUtil.convertToIntegerList(columnCardinality));
    // create index header object
    IndexHeader indexHeader = new IndexHeader();
    ColumnarFormatVersion version = CarbonProperties.getInstance().getFormatVersion();
    indexHeader.setVersion(version.number());
    // set the segment info
    indexHeader.setSegment_info(segmentInfo);
    // set the column names
    indexHeader.setTable_columns(columnSchemaList);
    // set the bucket number
    indexHeader.setBucket_id(bucketNumber);
    return indexHeader;
  }

  /**
   * Below method will be used to get the block index info thrift object for each block
   * present in the segment
   *
   * @param blockIndexInfoList block index info list
   * @return list of block index
   */
  public static List<BlockIndex> getBlockIndexInfo(List<BlockIndexInfo> blockIndexInfoList) {
    List<BlockIndex> thriftBlockIndexList = new ArrayList<BlockIndex>();
    BlockIndex blockIndex = null;
    // below code to create block index info object for each block
    for (BlockIndexInfo blockIndexInfo : blockIndexInfoList) {
      blockIndex = new BlockIndex();
      blockIndex.setNum_rows(blockIndexInfo.getNumberOfRows());
      blockIndex.setOffset(blockIndexInfo.getOffset());
      blockIndex.setFile_name(blockIndexInfo.getFileName());
      blockIndex.setBlock_index(getBlockletIndex(blockIndexInfo.getBlockletIndex()));
      thriftBlockIndexList.add(blockIndex);
    }
    return thriftBlockIndexList;
  }

  /**
   * Below method will be used to get the data chunk object for all the
   * columns
   *
   * @param blockletInfoColumnar blocklet info
   * @param columnSchenma        list of columns
   * @param segmentProperties    segment properties
   * @return list of data chunks
   * @throws IOException
   */
  public static List<DataChunk2> getDatachunk2(BlockletInfoColumnar blockletInfoColumnar,
      List<ColumnSchema> columnSchenma, SegmentProperties segmentProperties) throws IOException {
    List<DataChunk2> colDataChunks = new ArrayList<DataChunk2>();
    int rowIdIndex = 0;
    int aggregateIndex = 0;
    boolean[] isSortedKeyColumn = blockletInfoColumnar.getIsSortedKeyColumn();
    boolean[] aggKeyBlock = blockletInfoColumnar.getAggKeyBlock();
    boolean[] colGrpblock = blockletInfoColumnar.getColGrpBlocks();
    for (int i = 0; i < blockletInfoColumnar.getKeyLengths().length; i++) {
      DataChunk2 dataChunk = new DataChunk2();
      dataChunk.setChunk_meta(getChunkCompressionMeta());
      List<Encoding> encodings = new ArrayList<Encoding>();
      if (containsEncoding(i, Encoding.DICTIONARY, columnSchenma, segmentProperties)) {
        encodings.add(Encoding.DICTIONARY);
      }
      if (containsEncoding(i, Encoding.DIRECT_DICTIONARY, columnSchenma, segmentProperties)) {
        encodings.add(Encoding.DIRECT_DICTIONARY);
      }
      dataChunk.setRowMajor(colGrpblock[i]);
      //TODO : Once schema PR is merged and information needs to be passed here.
      dataChunk.setData_page_length(blockletInfoColumnar.getKeyLengths()[i]);
      if (aggKeyBlock[i]) {
        dataChunk.setRle_page_length(blockletInfoColumnar.getDataIndexMapLength()[aggregateIndex]);
        encodings.add(Encoding.RLE);
        aggregateIndex++;
      }
      dataChunk
          .setSort_state(isSortedKeyColumn[i] ? SortState.SORT_EXPLICIT : SortState.SORT_NATIVE);

      if (!isSortedKeyColumn[i]) {
        dataChunk.setRowid_page_length(blockletInfoColumnar.getKeyBlockIndexLength()[rowIdIndex]);
        encodings.add(Encoding.INVERTED_INDEX);
        rowIdIndex++;
      }

      //TODO : Right now the encodings are happening at runtime. change as per this encoders.
      dataChunk.setEncoders(encodings);

      colDataChunks.add(dataChunk);
    }

    for (int i = 0; i < blockletInfoColumnar.getMeasureLength().length; i++) {
      DataChunk2 dataChunk = new DataChunk2();
      dataChunk.setChunk_meta(getChunkCompressionMeta());
      dataChunk.setRowMajor(false);
      //TODO : Once schema PR is merged and information needs to be passed here.
      dataChunk.setData_page_length(blockletInfoColumnar.getMeasureLength()[i]);
      //TODO : Right now the encodings are happening at runtime. change as per this encoders.
      List<Encoding> encodings = new ArrayList<Encoding>();
      encodings.add(Encoding.DELTA);
      dataChunk.setEncoders(encodings);
      //TODO writing dummy presence meta need to set actual presence
      //meta
      PresenceMeta presenceMeta = new PresenceMeta();
      presenceMeta.setPresent_bit_streamIsSet(true);
      presenceMeta.setPresent_bit_stream(CompressorFactory.getInstance().getCompressor()
          .compressByte(blockletInfoColumnar.getMeasureNullValueIndex()[i].toByteArray()));
      dataChunk.setPresence(presenceMeta);
      //TODO : PresenceMeta needs to be implemented and set here
      // dataChunk.setPresence(new PresenceMeta());
      //TODO : Need to write ValueCompression meta here.
      List<ByteBuffer> encoderMetaList = new ArrayList<ByteBuffer>();
      encoderMetaList.add(ByteBuffer.wrap(serializeEncoderMeta(
          createValueEncoderMeta(blockletInfoColumnar.getCompressionModel(), i))));
      dataChunk.setEncoder_meta(encoderMetaList);
      colDataChunks.add(dataChunk);
    }
    return colDataChunks;
  }
}


text:
<?php

namespace Ekyna\Bundle\CommerceBundle\Table\Filter;

use Ekyna\Bundle\CommerceBundle\Form\Type\Subject\SubjectChoiceType;
use Ekyna\Component\Commerce\Subject\Provider\SubjectProviderInterface;
use Ekyna\Component\Commerce\Subject\Provider\SubjectProviderRegistryInterface;
use Ekyna\Component\Table\Bridge\Doctrine\ORM\Source\EntityAdapter;
use Ekyna\Component\Table\Context\ActiveFilter;
use Ekyna\Component\Table\Extension\Core\Type\Filter\FilterType;
use Ekyna\Component\Table\Filter\AbstractFilterType;
use Ekyna\Component\Table\Filter\FilterInterface;
use Ekyna\Component\Table\Source\AdapterInterface;
use Ekyna\Component\Table\Util\FilterOperator;
use Ekyna\Component\Table\View\ActiveFilterView;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\NotNull;

/**
 * Class SaleSubjectType
 * @package Ekyna\Bundle\CommerceBundle\Table\Filter
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
class SaleSubjectType extends AbstractFilterType
{
    /**
     * @var SubjectProviderRegistryInterface
     */
    private $registry;

    /**
     * Constructor.
     *
     * @param SubjectProviderRegistryInterface $registry
     */
    public function __construct(SubjectProviderRegistryInterface $registry)
    {
        $this->registry = $registry;
    }

    public function buildActiveView(ActiveFilterView $view, FilterInterface $filter, ActiveFilter $activeFilter, array $options)
    {
        /** @var \Ekyna\Component\Commerce\Subject\Entity\SubjectIdentity $identity */
        $identity = $activeFilter->getValue();

        $provider = $this->registry->getProviderByName($identity->getProvider());

        $subject = $provider->getRepository()->find($identity->getIdentifier());

        $view->vars['value'] = (string)$subject;
    }

    public function buildForm(FormBuilderInterface $builder, FilterInterface $filter, array $options)
    {
        $builder
            ->add('operator', ChoiceType::class, [
                'label'   => false,
                'choices' => FilterOperator::getChoices([FilterOperator::IN]),
            ])
            ->add('value', SubjectChoiceType::class, [
                'label'   => false,
                'context' => SubjectProviderInterface::CONTEXT_SALE,
                'constraints' => [
                    new NotNull(),
                ],
            ]);

        return true;
    }

    public function applyFilter(AdapterInterface $adapter, FilterInterface $filter, ActiveFilter $activeFilter, array $options)
    {
        if (!$adapter instanceof EntityAdapter) {
            return false;
        }

        /** @var \Ekyna\Component\Commerce\Subject\Entity\SubjectIdentity $identity */
        $identity = $activeFilter->getValue();
        $qb = $adapter->getQueryBuilder();
        $alias = $qb->getRootAliases()[0];
        $qb
            ->join($alias . '.items', 'i1')
            ->leftJoin('i1.children', 'i2')
            ->leftJoin('i2.children', 'i3')
            ->leftJoin('i3.children', 'i4')
            ->andWhere($qb->expr()->orX(
                $qb->expr()->andX(
                    $qb->expr()->eq('i1.subjectIdentity.provider', ':provider'),
                    $qb->expr()->eq('i1.subjectIdentity.identifier', ':identifier')
                ),
                $qb->expr()->andX(
                    $qb->expr()->eq('i2.subjectIdentity.provider', ':provider'),
                    $qb->expr()->eq('i2.subjectIdentity.identifier', ':identifier')
                ),
                $qb->expr()->andX(
                    $qb->expr()->eq('i3.subjectIdentity.provider', ':provider'),
                    $qb->expr()->eq('i3.subjectIdentity.identifier', ':identifier')
                ),
                $qb->expr()->andX(
                    $qb->expr()->eq('i4.subjectIdentity.provider', ':provider'),
                    $qb->expr()->eq('i4.subjectIdentity.identifier', ':identifier')
                )
            ))
            ->setParameter('provider', $identity->getProvider())
            ->setParameter('identifier', $identity->getIdentifier());

        return true;
    }

    /**
     * @inheritdoc
     */
    public function getParent()
    {
        return FilterType::class;
    }
}


text:
using System.Text;
using JetBrains.Annotations;

namespace Reusable.IOnymous
{
    [PublicAPI]
    public interface IEmailBody
    {
        string Value { get; }

        Encoding Encoding { get; }
    }

    public class EmailBody : IEmailBody
    {
        public string Value { get; set; }

        public Encoding Encoding { get; set; } = Encoding.UTF8;
    }
}


text:
package com.twitter.server

import com.twitter.app.Flags
import com.twitter.finagle.{Addr, Announcer, Announcement, Resolver}
import com.twitter.util.{Await, Future, RandomSocket}
import java.net.InetSocketAddress
import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner

case class TestAnnouncement(addr: InetSocketAddress, target: String) extends Announcement {
  def unannounce() = Future.Done
}

class TestAnnouncer extends Announcer {
  val scheme = "test"
  def announce(addr: InetSocketAddress, target: String) =
    Future.value(TestAnnouncement(addr, target))
}

@RunWith(classOf[JUnitRunner])
class ResolverTest extends FunSuite {
  test("resolvers resolve from the main resolver") {
    val flag = new Flags("my", includeGlobal=true)
    flag.parse(Array("-com.twitter.server.resolverMap", "foo=:8080"))

    Resolver.eval("flag!foo") // doesn't throw.
  }

  test("announcers resolve from the main announcer") {
    val addr = RandomSocket()
    val flag = new Flags("my", includeGlobal=true)
    flag.parse(Array("-com.twitter.server.announcerMap", "foo=test!127.0.0.1:80"))

    // checks for non-exceptional
    Await.result(Announcer.announce(addr, "flag!foo"))
  }
}


text:
'use strict';

import { TPromise } from 'vs/base/common/winjs.base';
import { ExtHostContext, ObjectIdentifier, IExtHostContext } from '../node/extHost.protocol';
import { consumeSignals, GCSignal } from 'gc-signals';
import { createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { registerSingleton } from 'vs/platform/instantiation/common/extensions';
import Event, { Emitter } from 'vs/base/common/event';
import { IDisposable } from 'vs/base/common/lifecycle';
import { extHostCustomer } from 'vs/workbench/api/electron-browser/extHostCustomers';

export const IHeapService = createDecorator<IHeapService>('heapService');

export interface IHeapService {
	_serviceBrand: any;

	readonly onGarbageCollection: Event<number[]>;

	/**
	 * Track gc-collection for all new objects that
	 * have the $ident-value set.
	 */
	trackRecursive<T>(p: TPromise<T>): TPromise<T>;

	/**
	 * Track gc-collection for all new objects that
	 * have the $ident-value set.
	 */
	trackRecursive<T>(obj: T): T;
}

export class HeapService implements IHeapService {

	_serviceBrand: any;

	private _onGarbageCollection: Emitter<number[]> = new Emitter<number[]>();
	public readonly onGarbageCollection: Event<number[]> = this._onGarbageCollection.event;

	private _activeSignals = new WeakMap<any, GCSignal>();
	private _activeIds = new Set<number>();
	private _consumeHandle: number;

	constructor() {
		this._consumeHandle = setInterval(() => {
			const ids = consumeSignals();

			if (ids.length > 0) {
				// local book-keeping
				for (const id of ids) {
					this._activeIds.delete(id);
				}

				// fire event
				this._onGarbageCollection.fire(ids);
			}

		}, 15 * 1000);
	}

	dispose() {
		clearInterval(this._consumeHandle);
	}

	trackRecursive<T>(p: TPromise<T>): TPromise<T>;
	trackRecursive<T>(obj: T): T;
	trackRecursive(obj: any): any {
		if (TPromise.is(obj)) {
			return obj.then(result => this.trackRecursive(result));
		} else {
			return this._doTrackRecursive(obj);
		}
	}

	private _doTrackRecursive(obj: any): any {

		const stack = [obj];
		while (stack.length > 0) {

			// remove first element
			let obj = stack.shift();

			if (!obj || typeof obj !== 'object') {
				continue;
			}

			for (let key in obj) {
				if (!Object.prototype.hasOwnProperty.call(obj, key)) {
					continue;
				}

				const value = obj[key];
				// recurse -> object/array
				if (typeof value === 'object') {
					stack.push(value);

				} else if (key === ObjectIdentifier.name) {
					// track new $ident-objects

					if (typeof value === 'number' && !this._activeIds.has(value)) {
						this._activeIds.add(value);
						this._activeSignals.set(obj, new GCSignal(value));
					}
				}
			}
		}

		return obj;
	}
}

@extHostCustomer
export class MainThreadHeapService {

	private _toDispose: IDisposable;

	constructor(
		extHostContext: IExtHostContext,
		@IHeapService heapService: IHeapService,
	) {
		const proxy = extHostContext.get(ExtHostContext.ExtHostHeapService);
		this._toDispose = heapService.onGarbageCollection((ids) => {
			// send to ext host
			proxy.$onGarbageCollection(ids);
		});
	}

	public dispose(): void {
		this._toDispose.dispose();
	}

}

registerSingleton(IHeapService, HeapService);


text:
<!DOCTYPE html>

<meta charset="utf-8">
<title>Conformance test for WebGL2 texture image formats specification</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>

<canvas id="canvas" width="64" height="64"> </canvas>


text:
apetools.commands.dumpsyswifi.DumpsysWifi.interface
===================================================

.. currentmodule:: apetools.commands.dumpsyswifi

.. autoattribute:: DumpsysWifi.interface


text:
import {
  Component,
  Input,
  OnChanges,
  SimpleChanges,
  ChangeDetectionStrategy
} from '@angular/core';
import { LocationStrategy, PathLocationStrategy } from '@angular/common';
import { area, line } from 'd3-shape';

import { id } from '../utils/id';
import { sortLinear, sortByTime, sortByDomain } from '../utils/sort';

@Component({
  selector: 'g[ngx-charts-custom-line-series]',
  template: `
    <svg:g>
      <defs>
        <svg:g ngx-charts-svg-linear-gradient *ngIf="hasGradient"
          orientation="vertical"
          [name]="gradientId"
          [stops]="gradientStops"
        />
      </defs>
      <svg:g ngx-charts-area
        class="line-highlight"
        [data]="data"
        [path]="areaPath"
        [fill]="hasGradient ? gradientUrl : colors.getColor(data.name)"
        [opacity]="0.25"
        [startOpacity]="0"
        [gradient]="true"
        [stops]="areaGradientStops"
        [class.active]="isActive(data)"
        [class.inactive]="isInactive(data)"
      />
      <svg:g ngx-charts-custom-line
        class="line-series"
        [data]="data"
        [path]="path"
        [stroke]="stroke"
        [class.active]="isActive(data)"
        [class.inactive]="isInactive(data)"
      />
     <svg:g ngx-charts-area
        *ngIf="hasRange"
        class="line-series-range"
        [data]="data"
        [path]="outerPath"
        [fill]="hasGradient ? gradientUrl : colors.getColor(data.name)"
        [class.active]="isActive(data)"
        [class.inactive]="isInactive(data)"
        [opacity]="rangeFillOpacity"
      />
    </svg:g>
  `,
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CustomLineSeriesComponent implements OnChanges {

  @Input() data;
  @Input() xScale;
  @Input() yScale;
  @Input() colors;
  @Input() scaleType;
  @Input() curve: any;
  @Input() activeEntries: any[];
  @Input() rangeFillOpacity: number;
  @Input() hasRange: boolean;

  path: string;
  outerPath: string;
  areaPath: string;
  gradientId: string;
  gradientUrl: string;
  hasGradient: boolean;
  gradientStops: any[];
  areaGradientStops: any[];
  stroke: any;

  constructor(private location: LocationStrategy) {
  }

  ngOnChanges(changes: SimpleChanges): void {
    this.update();
  }

  update(): void {
    this.updateGradients();

    const data = this.sortData(this.data.series);

    const line = this.getLineGenerator();
    this.path = line(data) || '';

    const area = this.getAreaGenerator();
    this.areaPath = area(data) || '';

    if (this.hasRange) {
      const range = this.getRangeGenerator();
      this.outerPath = range(data) || '';
    }

    if (this.hasGradient) {
      this.stroke = this.gradientUrl;
      const values = this.data.series.map(d => d.value);
      const max = Math.max(...values);
      const min = Math.min(...values);
      if (max === min) {
        this.stroke = this.colors.getColor(max);
      }
    } else {
      this.stroke = this.colors.getColor(this.data.name);
    }
  }

  getLineGenerator(): any {
    return line<any>()
      .x(d => {
        const label = d.name;
        let value;
        if (this.scaleType === 'time') {
          value = this.xScale(label);
        } else if (this.scaleType === 'linear') {
          value = this.xScale(Number(label));
        } else {
          value = this.xScale(label);
        }
        return value;
      })
      .y(d => this.yScale(d.value))
      .curve(this.curve);
  }

  getRangeGenerator(): any {
    return area<any>()
        .x(d => {
          const label = d.name;
          let value;
          if (this.scaleType === 'time') {
            value = this.xScale(label);
          } else if (this.scaleType === 'linear') {
            value = this.xScale(Number(label));
          } else {
            value = this.xScale(label);
          }
          return value;
        })
        .y0(d => this.yScale(d.min ? d.min : d.value))
        .y1(d => this.yScale(d.max ? d.max : d.value))
        .curve(this.curve);
  }

  getAreaGenerator(): any {
    const xProperty = (d) => {
      const label = d.name;
      return this.xScale(label);
    };

    return area<any>()
      .x(xProperty)
      .y0(() => this.yScale.range()[0])
      .y1(d => this.yScale(d.value))
      .curve(this.curve);
  }

  sortData(data) {
    if (this.scaleType === 'linear') {
      data = sortLinear(data, 'name');
    } else if (this.scaleType === 'time') {
      data = sortByTime(data, 'name');
    } else {
      data = sortByDomain(data, 'name', 'asc', this.xScale.domain());
    }

    return data;
  }

  updateGradients() {
    if (this.colors.scaleType === 'linear') {
      this.hasGradient = true;

      const pageUrl = this.location instanceof PathLocationStrategy
        ? this.location.path()
        : '';

      this.gradientId = 'grad' + id().toString();
      this.gradientUrl = `url(${pageUrl}#${this.gradientId})`;
      const values = this.data.series.map(d => d.value);
      const max = Math.max(...values);
      const min = Math.min(...values);
      this.gradientStops = this.colors.getLinearGradientStops(max, min);
      this.areaGradientStops = this.colors.getLinearGradientStops(max);
    } else {
      this.hasGradient = false;
      this.gradientStops = undefined;
      this.areaGradientStops = undefined;
    }
  }

  isActive(entry): boolean {
    if(!this.activeEntries) return false;
    const item = this.activeEntries.find(d => {
      return entry.name === d.name;
    });
    return item !== undefined;
  }

  isInactive(entry): boolean {
    if(!this.activeEntries || this.activeEntries.length === 0) return false;
    const item = this.activeEntries.find(d => {
      return entry.name === d.name;
    });
    return item === undefined;
  }

}