text:
package raytracer

import (
	"math"

	"github.com/gmacd/rays/core"
	"github.com/gmacd/rays/geom"
	"github.com/gmacd/rays/intersections"
)

const MAX_TRACE_DEPTH = 5

func FindNearestIntersection(scene *geom.Scene, ray core.Ray) (hitPrim geom.Primitive, hit intersections.HitType, dist float64) {
	maxDist := math.MaxFloat64

	// Find nearest intersection
	for _, p := range scene.AllPrimitives() {
		currHit, currHitDist := p.Intersects(ray, maxDist)
		if currHit != intersections.MISS {
			hitPrim = p
			hit = currHit
			dist = currHitDist
		}
	}

	return hitPrim, hit, dist
}

func Raytrace(scene *geom.Scene, ray core.Ray, rIndex float64) (hitPrim geom.Primitive, hit intersections.HitType, dist float64, colour core.ColourRGB) {
	colour = core.NewColourRGB(0, 0, 0)
	hitPrim, hit, dist = FindNearestIntersection(scene, ray)
	if hit == intersections.MISS {
		return hitPrim, hit, dist, colour
	}

	// This is a bit rubbish - always white for direct light hit?
	if hitPrim.IsLight() {
		return hitPrim, hit, dist, core.NewColourRGB(1, 1, 1)
	}

	material := hitPrim.Material()
	intersectionPoint := ray.Origin.Add(ray.Dir.MulScalar(dist))

	// Trace lights
	for _, light := range scene.Lights() {
		// Point light shadows
		shade := 1.0
		// TODO is point light?
		l, lightDist := light.LightCentre().Sub(intersectionPoint).NormalWithLength()
		{
			// If point light
			r := core.NewRayWithDepth(intersectionPoint.Add(l.MulScalar(core.EPSILON)), l, ray.Depth+1)
			for _, primForShadow := range scene.AllPrimitives() {
				if primForShadow != light {
					if lightHit, _ := primForShadow.Intersects(r, lightDist); lightHit != intersections.MISS {
						shade = 0
						break
					}
				}
			}
		}

		// Diffuse
		n := hitPrim.Normal(intersectionPoint)
		if material.Diffuse > 0 {
			dot := n.Dot(l)
			if dot > 0 {
				diffuse := dot * material.Diffuse * shade
				colour.AddTo(material.Colour.MulScalar(diffuse).Mul(light.Material().Colour))
			}
		}

		// Specular
		specular := material.Specular
		v := ray.Dir
		r := l.Sub(n.MulScalar(2.0 * l.Dot(n)))
		dot := v.Dot(r)
		if dot > 0 {
			specular := math.Pow(dot, 20) * specular * shade
			colour.AddTo(light.Material().Colour.MulScalar(specular))
		}
	}

	// Reflection
	reflection := material.Reflection
	if (reflection > 0) && (ray.Depth < MAX_TRACE_DEPTH) {
		n := hitPrim.Normal(intersectionPoint)
		r := ray.Dir.Sub(n.MulScalar(2.0 * ray.Dir.Dot(n)))
		reflectionRay := core.NewRayWithDepth(
			intersectionPoint.Add(r.MulScalar(core.EPSILON)), r, ray.Depth+1)

		_, _, _, reflectionColour := Raytrace(scene, reflectionRay, rIndex)
		colour.AddTo(material.Colour.Mul(reflectionColour).MulScalar(reflection))
	}

	// Refraction
	refraction := material.Refraction
	if (refraction > 0) && (ray.Depth < MAX_TRACE_DEPTH) {
		primRIndex := material.RefractiveIndex
		n := rIndex / primRIndex
		N := hitPrim.Normal(intersectionPoint).MulScalar(float64(hit))
		cosI := -N.Dot(ray.Dir)
		cosT2 := 1.0 - n*n*(1.0-cosI*cosI)
		if cosT2 > 0 {
			T := ray.Dir.MulScalar(n).Add(N.MulScalar(n*cosI - math.Sqrt(cosT2)))
			refractiveRay := core.NewRayWithDepth(
				intersectionPoint.Add(T.MulScalar(core.EPSILON)),
				T, ray.Depth+1)
			_, _, refractiveHitDist, refractiveColour := Raytrace(scene, refractiveRay, primRIndex)

			absorbance := material.Colour.MulScalar(0.15 * -refractiveHitDist)
			transparency := core.NewColourRGB(
				math.Exp(absorbance.R),
				math.Exp(absorbance.G),
				math.Exp(absorbance.B))

			colour.AddTo(refractiveColour.Mul(transparency))
		}
	}

	return hitPrim, hit, dist, colour
}


text:
//
//  UVSuggestionDetailsViewController.m
//  UserVoice
//
//  Created by UserVoice on 10/29/09.
//  Copyright 2009 UserVoice Inc. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>
#import "UVSuggestionDetailsViewController.h"
#import "UVStyleSheet.h"
#import "UVSession.h"
#import "UVSuggestion.h"
#import "UVUser.h"
#import "UVClientConfig.h"
#import "UVImageView.h"
#import "UVComment.h"
#import "UVCommentViewController.h"
#import "UVTruncatingLabel.h"
#import "UVCallback.h"
#import "UVBabayaga.h"
#import "UVDeflection.h"
#import "UVCategory.h"
#import "UVUtils.h"

#define MARGIN 15

#define COMMENT_AVATAR_TAG 1000
#define COMMENT_NAME_TAG 1001
#define COMMENT_DATE_TAG 1002
#define COMMENT_TEXT_TAG 1003
#define SUGGESTION_DESCRIPTION 20
#define ADMIN_RESPONSE 30
#define LOADING 40

@implementation UVSuggestionDetailsViewController {
    CGFloat _footerHeight;
    BOOL _allCommentsRetrieved;
    BOOL _suggestionExpanded;
    BOOL _responseExpanded;
    BOOL _subscribing;
    BOOL _loading;
    UVCallback *_subscribeCallback;
    UISwitch *_toggle;
}

- (id)init {
    self = [super init];

    if (self) {
        _subscribeCallback = [[UVCallback alloc] initWithTarget:self selector:@selector(doSubscribe)];
    }

    return self;
}

- (id)initWithSuggestion:(UVSuggestion *)theSuggestion {
    self = [self init];

    if (self) {
        _suggestion = theSuggestion;
    }

    return self;
}

- (void)retrieveMoreComments {
    NSInteger page = (_comments.count / 10) + 1;
    [self showActivityIndicator];
    [UVComment getWithSuggestion:_suggestion page:page delegate:self];
}

- (void)didRetrieveComments:(NSArray *)theComments {
    if (theComments.count > 0) {
        [_comments addObjectsFromArray:theComments];
        if (_comments.count >= _suggestion.commentsCount) {
            _allCommentsRetrieved = YES;
        }
    } else {
        _allCommentsRetrieved = YES;
    }
    [self hideActivityIndicator];
    [_tableView reloadData];
}

- (void)didSubscribe:(UVSuggestion *)theSuggestion {
    [UVBabayaga track:VOTE_IDEA id:theSuggestion.suggestionId];
    [UVBabayaga track:SUBSCRIBE_IDEA id:theSuggestion.suggestionId];
    if (_deflectingType) {
        [UVDeflection trackDeflection:@"subscribed" deflectingType:_deflectingType deflector:theSuggestion];
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:_helpfulPrompt
                                                                 delegate:self
                                                        cancelButtonTitle:NSLocalizedStringFromTableInBundle(@"Cancel", @"UserVoice", [UserVoice bundle], nil)
                                                   destructiveButtonTitle:nil
                                                        otherButtonTitles:_returnMessage, NSLocalizedStringFromTableInBundle(@"No, I'm done", @"UserVoice", [UserVoice bundle], nil), nil];
        [actionSheet showInView:self.view];
    }
    [self updateSuggestion:theSuggestion];
    _subscribing = NO;
}

- (void)didUnsubscribe:(UVSuggestion *)theSuggestion {
    [self updateSuggestion:theSuggestion];
}

- (void)updateSuggestion:(UVSuggestion *)theSuggestion {
    _suggestion.subscribed = theSuggestion.subscribed;
    _suggestion.subscriberCount = theSuggestion.subscriberCount;
    _suggestion.rank = theSuggestion.rank;
    [self updateSubscriberCount];
}

- (void)updateSubscriberCount {
    if ([UVSession currentSession].clientConfig.displaySuggestionsByRank) {
        _subscriberCount.text = [NSString stringWithFormat:NSLocalizedStringFromTableInBundle(@"Ranked %@", @"UserVoice", [UserVoice bundle], nil), _suggestion.rankString];
    } else {
        if (_suggestion.subscriberCount == 1) {
            _subscriberCount.text = NSLocalizedStringFromTableInBundle(@"1 person", @"UserVoice", [UserVoice bundle], nil);
        } else {
            _subscriberCount.text = [NSString stringWithFormat:NSLocalizedStringFromTableInBundle(@"%d people", @"UserVoice", [UserVoice bundle], nil), _suggestion.subscriberCount];
        }
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    } else if (buttonIndex == 1) {
        [self dismiss];
    }
}

#pragma mark ===== UITableView Methods =====

- (UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *identifier;
    UITableViewCellStyle style = UITableViewCellStyleDefault;
    BOOL selectable = NO;

    if (indexPath.section == 0 && indexPath.row == 0) {
        identifier = @"Suggestion";
    } else if (indexPath.section == 0 && indexPath.row == 1) {
        identifier = @"Response";
    } else if (indexPath.section == 1) {
        identifier = @"AddComment";
        selectable = YES;
    } else if (indexPath.row < _comments.count) {
        identifier = @"Comment";
    } else {
        identifier = @"Load";
        selectable = YES;
    }

    return [self createCellForIdentifier:identifier
                               tableView:theTableView
                               indexPath:indexPath
                                   style:style
                              selectable:selectable];
}

- (void)initCellForComment:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    if (IOS7) {
        cell.separatorInset = UIEdgeInsetsMake(0, 64, 0, 0);
    }
    UVImageView *avatar = [UVImageView new];
    avatar.tag = COMMENT_AVATAR_TAG;

    UILabel *name = [UILabel new];
    name.tag = COMMENT_NAME_TAG;
    name.font = [UIFont boldSystemFontOfSize:13];
    name.textColor = [UIColor colorWithRed:0.19f green:0.20f blue:0.20f alpha:1.0f];

    UILabel *date = [UILabel new];
    date.tag = COMMENT_DATE_TAG;
    date.font = [UIFont systemFontOfSize:12];
    date.textColor = [UIColor colorWithRed:0.58f green:0.58f blue:0.60f alpha:1.0f];

    UILabel *text = [UILabel new];
    text.tag = COMMENT_TEXT_TAG;
    text.numberOfLines = 0;
    text.font = [UIFont systemFontOfSize:13];
    text.textColor = [UIColor colorWithRed:0.41f green:0.42f blue:0.43f alpha:1.0f];

    NSArray *constraints = @[
        @"|-16-[avatar(==40)]-[name]",
        @"[date]-|",
        @"[avatar]-[text]-|",
        @"V:|-14-[avatar(==40)]",
        @"V:|-14-[name]-[text]",
        @"V:|-14-[date]"
    ];
    [self configureView:cell.contentView
               subviews:NSDictionaryOfVariableBindings(avatar, name, date, text)
            constraints:constraints
         finalCondition:indexPath == nil
        finalConstraint:@"V:[text]-14-|"];
}

- (void)customizeCellForComment:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    UVComment *comment = [_comments objectAtIndex:indexPath.row];

    UVImageView *avatar = (UVImageView *)[cell viewWithTag:COMMENT_AVATAR_TAG];
    avatar.URL = comment.avatarUrl;

    UILabel *name = (UILabel *)[cell viewWithTag:COMMENT_NAME_TAG];
    name.text = comment.userName;

    UILabel *date = (UILabel *)[cell viewWithTag:COMMENT_DATE_TAG];
    date.text = [NSDateFormatter localizedStringFromDate:comment.createdAt dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];

    UILabel *text = (UILabel *)[cell viewWithTag:COMMENT_TEXT_TAG];
    text.text = comment.text;
}

- (void)initCellForLoad:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    cell.backgroundView = [[UIView alloc] initWithFrame:cell.frame];
    UILabel *label = [[UILabel alloc] initWithFrame:cell.frame];
    label.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:16];
    label.textAlignment = NSTextAlignmentCenter;
    label.tag = LOADING;
    [cell addSubview:label];
}

- (void)customizeCellForLoad:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    UILabel *label = (UILabel *)[cell viewWithTag:LOADING];
    label.text = _loading ? NSLocalizedStringFromTableInBundle(@"Loading...", @"UserVoice", [UserVoice bundle], nil) : NSLocalizedStringFromTableInBundle(@"Load more", @"UserVoice", [UserVoice bundle], nil);
}

- (void)initCellForSuggestion:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    UILabel *category = [UILabel new];
    category.font = [UIFont systemFontOfSize:13];
    category.text = _suggestion.category.name ? [NSString stringWithFormat:@"%@ / %@", NSLocalizedStringFromTableInBundle(@"Feedback", @"UserVoice", [UserVoice bundle], nil), _suggestion.category.name] : NSLocalizedStringFromTableInBundle(@"Feedback", @"UserVoice", [UserVoice bundle], nil);
    category.adjustsFontSizeToFitWidth = YES;
    category.minimumScaleFactor = 0.5;
    category.textColor = [UIColor colorWithRed:0.41f green:0.42f blue:0.43f alpha:1.0f];

    UILabel *title = [UILabel new];
    title.font = [UIFont boldSystemFontOfSize:17];
    title.text = _suggestion.title;
    title.numberOfLines = 0;

    UVTruncatingLabel *desc = [UVTruncatingLabel new];
    desc.font = [UIFont systemFontOfSize:14];
    desc.fullText = _suggestion.text;
    desc.delegate = self;
    desc.tag = SUGGESTION_DESCRIPTION;

    NSArray *constraints = @[
        @"|-16-[category]-|",
        @"|-16-[title]-|",
        @"|-16-[desc]-|",
        @"V:|-12-[category]-8-[title]-[desc]"
    ];
    [self configureView:cell.contentView
               subviews:NSDictionaryOfVariableBindings(category, title, desc)
            constraints:constraints
         finalCondition:indexPath == nil
        finalConstraint:@"V:[desc]-|"];
}

- (void)customizeCellForSuggestion:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    UVTruncatingLabel *desc = (UVTruncatingLabel *)[cell.contentView viewWithTag:SUGGESTION_DESCRIPTION];
    if (_suggestionExpanded)
        [desc expand];
}

- (void)initCellForResponse:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    UIView *statusColor = [UIView new];
    statusColor.backgroundColor = _suggestion.statusColor;

    UILabel *status = [UILabel new];
    status.font = [UIFont systemFontOfSize:12];
    status.text = _suggestion.status.uppercaseString;
    status.textColor = _suggestion.statusColor;

    UILabel *date = [UILabel new];
    date.font = [UIFont systemFontOfSize:12];
    date.textColor = [UIColor colorWithRed:0.58f green:0.58f blue:0.60f alpha:1.0f];
    date.text = [NSDateFormatter localizedStringFromDate:_suggestion.responseCreatedAt dateStyle:NSDateFormatterMediumStyle timeStyle:NSDateFormatterNoStyle];

    if ([_suggestion.responseText length] > 0) {
        UVImageView *avatar = [UVImageView new];
        avatar.URL = _suggestion.responseUserAvatarUrl;

        UVTruncatingLabel *text = [UVTruncatingLabel new];
        text.font = [UIFont systemFontOfSize:13];
        text.textColor = [UIColor colorWithRed:0.41f green:0.42f blue:0.43f alpha:1.0f];
        text.fullText = _suggestion.responseText;
        text.delegate = self;
        text.tag = ADMIN_RESPONSE;

        UILabel *admin = [UILabel new];
        admin.font = [UIFont systemFontOfSize:11];
        admin.text = _suggestion.responseUserWithTitle;
        admin.textColor = [UIColor colorWithRed:0.69f green:0.69f blue:0.72f alpha:1.0f];
        admin.adjustsFontSizeToFitWidth = YES;
        admin.minimumScaleFactor = 0.5;

        NSArray *constraints = @[
            @"|-16-[statusColor(==10)]-[status]-|",
            @"[date]-|",
            @"|-16-[text]-[avatar(==40)]-|",
            @"|-16-[admin]-|",
            @"V:|-14-[statusColor(==10)]",
            @"V:|-12-[status]",
            @"V:|-12-[date]-[avatar(==40)]",
            @"V:[status]-(>=10)-[text]-[admin]",
            @"V:[date]-(>=10)-[text]"
        ];
        [self configureView:cell.contentView
                   subviews:NSDictionaryOfVariableBindings(statusColor, status, date, text, admin, avatar)
                constraints:constraints
             finalCondition:indexPath == nil
            finalConstraint:@"V:[admin]-12-|"];
    } else {
        NSArray *constraints = @[
            @"|-16-[statusColor(==10)]-[status]-|",
            @"[date]-|",
            @"V:|-14-[statusColor(==10)]",
            @"V:|-12-[status]",
            @"V:|-12-[date]",
        ];
        [self configureView:cell.contentView
                   subviews:NSDictionaryOfVariableBindings(statusColor, status, date)
                constraints:constraints
             finalCondition:indexPath == nil
            finalConstraint:@"V:[status]-12-|"];
    }
}

- (void)customizeCellForResponse:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    UVTruncatingLabel *text = (UVTruncatingLabel *)[cell.contentView viewWithTag:ADMIN_RESPONSE];
    if (_responseExpanded)
        [text expand];
}

- (void)initCellForAddComment:(UITableViewCell *)cell indexPath:(NSIndexPath *)indexPath {
    cell.textLabel.text = NSLocalizedStringFromTableInBundle(@"Add a comment", @"UserVoice", [UserVoice bundle], nil);
    if (IOS7) {
        cell.textLabel.textColor = cell.textLabel.tintColor;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return _suggestion.status || _suggestion.responseText ? 2 : 1;
    } else if (section == 1) {
        return 1;
    } else {
        return _comments.count + (_allCommentsRetrieved ? 0 : 1);
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _instantAnswers ? 1 : 3;
}

- (CGFloat)tableView:(UITableView *)theTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 2 && indexPath.row < _comments.count) {
        return [self heightForDynamicRowWithReuseIdentifier:@"Comment" indexPath:indexPath];
    } else if (indexPath.section == 0 && indexPath.row == 0) {
        return [self heightForDynamicRowWithReuseIdentifier:@"Suggestion" indexPath:indexPath];
    } else if (indexPath.section == 0 && indexPath.row == 1) {
        return [self heightForDynamicRowWithReuseIdentifier:@"Response" indexPath:indexPath];
    } else {
        return 44;
    }
}

- (void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [theTableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 1 && indexPath.row == 0) {
        [self presentModalViewController:[[UVCommentViewController alloc] initWithSuggestion:_suggestion]];
    } else if (indexPath.section == 2 && indexPath.row == _comments.count) {
        if (!_loading) {
            [self retrieveMoreComments];
        }
    }
}

#pragma mark ===== Actions =====

- (void)toggleSubscribed {
    if (_suggestion.subscribed) {
        [self unsubscribe];
    } else {
        [self subscribe];
    }
}

- (void)subscribe {
    if (_subscribing) return;
    _subscribing = YES;
    [self requireUserSignedIn:_subscribeCallback];
}

- (void)doSubscribe {
    [_suggestion subscribe:self];
}

- (void)unsubscribe {
    [_suggestion unsubscribe:self];
}

- (void)signinManagerDidFail {
    _subscribing = NO;
    [_toggle setOn:_suggestion.subscribed];
    [super signinManagerDidFail];
}

- (void)didReceiveError:(NSError *)error {
    _subscribing = NO;
    [_toggle setOn:_suggestion.subscribed];
    [super didReceiveError:error];
}

#pragma mark ===== Basic View Methods =====

- (void)keyboardDidHide:(NSNotification*)notification {
    UIEdgeInsets contentInsets = UIEdgeInsetsMake([self scrollView].contentInset.top, 0.0, _footerHeight, 0.0);
    [self scrollView].contentInset = contentInsets;
    [self scrollView].scrollIndicatorInsets = contentInsets;
}

- (void)labelExpanded:(UVTruncatingLabel *)label {
    if (label.tag == SUGGESTION_DESCRIPTION) {
        _suggestionExpanded = YES;
        [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    } else {
        _responseExpanded = YES;
        [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    }
}

- (void)loadView {
    [super loadView];
    [UVBabayaga track:VIEW_IDEA id:_suggestion.suggestionId];
    self.view = [[UIView alloc] initWithFrame:[self contentFrame]];

    _footerHeight = _instantAnswers ? 46 : 66;
    UITableView *table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.tableFooterView = [UIView new];
    table.contentInset = UIEdgeInsetsMake(0, 0, _footerHeight, 0);
    table.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, _footerHeight, 0);
    _tableView = table;

    BOOL byRank = [UVSession currentSession].clientConfig.displaySuggestionsByRank;
    NSArray *constraints;

    UIView *footer = [UIView new];
    footer.backgroundColor = [UIColor colorWithRed:0.97f green:0.97f blue:0.97f alpha:1.0f];
    UIView *border = [UIView new];
    border.backgroundColor = [UIColor colorWithRed:0.85f green:0.85f blue:0.85f alpha:1.0f];
    if (_instantAnswers) {
        UILabel *people = [UILabel new];
        people.font = [UIFont systemFontOfSize:14];
        people.textColor = [UIColor colorWithRed:0.58f green:0.58f blue:0.60f alpha:1.0f];
        people.backgroundColor = [UIColor clearColor];
        _subscriberCount = people;

        UIImageView *heart = [UVUtils imageViewWithImageNamed:@"uv_heart.png"];

        UILabel *this = [UILabel new];
        this.text = NSLocalizedStringFromTableInBundle(@"this idea", @"UserVoice", [UserVoice bundle], nil);
        this.font = people.font;
        this.backgroundColor = [UIColor clearColor];
        this.textColor = people.textColor;

        UIButton *want = [UIButton new];
        [want setTitle:NSLocalizedStringFromTableInBundle(@"I want this", @"UserVoice", [UserVoice bundle], nil) forState:UIControlStateNormal];
        [want setTitleColor:want.tintColor forState:UIControlStateNormal];
        [want addTarget:self action:@selector(subscribe) forControlEvents:UIControlEventTouchUpInside];

        if (byRank) {
            constraints = @[
                @"|[border]|", @"V:|[border(==1)]",
                @"|-[people]", @"[want]-|",
                @"V:|-14-[people]", @"V:|-6-[want]"
            ];
        } else {
            constraints = @[
                @"|[border]|", @"V:|[border(==1)]",
                @"|-[people]-4-[heart(==12)]-4-[this]", @"[want]-|",
                @"V:|-14-[people]", @"V:|-18-[heart(==11)]", @"V:|-14-[this]", @"V:|-6-[want]"
            ];
        }
        [self configureView:footer
                   subviews:byRank ? NSDictionaryOfVariableBindings(border, people, want) : NSDictionaryOfVariableBindings(border, want, people, heart, this)
                constraints:constraints];
    } else {
        UILabel *want = [UILabel new];
        want.text = NSLocalizedStringFromTableInBundle(@"I want this!", @"UserVoice", [UserVoice bundle], nil);
        want.font = [UIFont systemFontOfSize:16];
        want.backgroundColor = [UIColor clearColor];

        UILabel *people = [UILabel new];
        people.font = [UIFont systemFontOfSize:13];
        people.textColor = [UIColor colorWithRed:0.58f green:0.58f blue:0.60f alpha:1.0f];
        people.backgroundColor = [UIColor clearColor];
        _subscriberCount = people;

        UIImageView *heart = [UVUtils imageViewWithImageNamed:@"uv_heart.png"];

        UILabel *this = [UILabel new];
        this.text = NSLocalizedStringFromTableInBundle(@"this", @"UserVoice", [UserVoice bundle], nil);
        this.font = people.font;
        this.backgroundColor = [UIColor clearColor];
        this.textColor = people.textColor;

        _toggle = [UISwitch new];
        if (_suggestion.subscribed) {
            _toggle.on = YES;
        }
        [_toggle addTarget:self action:@selector(toggleSubscribed) forControlEvents:UIControlEventValueChanged];

        if (byRank) {
            constraints = @[
                @"|[border]|", @"V:|[border(==1)]",
                @"|-[want]", @"|-[people]", @"[_toggle]-|",
                @"V:|-14-[want]-2-[people]", @"V:|-16-[_toggle]"
            ];
        } else {
            constraints = @[
                @"|[border]|", @"V:|[border(==1)]",
                @"|-[want]", @"|-[people]-4-[heart(==12)]-4-[this]", @"[_toggle]-|",
                @"V:|-14-[want]-2-[people]", @"V:[want]-6-[heart(==11)]", @"V:[want]-2-[this]", @"V:|-16-[_toggle]"
            ];
        }
        [self configureView:footer
                   subviews:byRank ? NSDictionaryOfVariableBindings(border, want, people, _toggle) : NSDictionaryOfVariableBindings(border, want, people, heart, this, _toggle)
                constraints:constraints];
    }

    [self configureView:self.view
               subviews:NSDictionaryOfVariableBindings(table, footer)
            constraints:@[@"V:|[table]|", @"V:[footer]|", @"|[table]|", @"|[footer]|"]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:footer attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:_footerHeight]];
    [self.view bringSubviewToFront:footer];

    _allCommentsRetrieved = NO;
    _comments = [NSMutableArray arrayWithCapacity:10];
    [self retrieveMoreComments];

    [self updateSubscriberCount];
}

- (void)initNavigationItem {}

/*
 * The point of this is to put a newly created comment at the top of the list
 * without screwing things up too badly. This has to be done because the new
 * comment won't actually appear in the list until spam filtering is done, and
 * we don't know when that will be.
 *
 * Cutting the comment list down to 1 page with the new comment artificially
 * inserted at the top seems like the best way to do this. Pagination will
 * be slightly inaccurate if another comment was created since the first page
 * was loaded, or if the new comment gets caught in the spam filter. However,
 * that kind of inaccuracy is to be expected for offset-based pagination.
 */
- (void)commentCreated:(UVComment *)comment {
    NSMutableArray *newComments = [NSMutableArray arrayWithCapacity:10];
    [newComments addObject:comment];
    for (int i=0; i < MIN(9, _comments.count); i++) {
        [newComments addObject:[_comments objectAtIndex:i]];
    }
    if (_comments.count > 9)
        _allCommentsRetrieved = NO;
    _comments = newComments;
    [_tableView reloadData];
}

- (void)showActivityIndicator {
    _loading = YES;
    [_tableView reloadData];
}

- (void)hideActivityIndicator {
    _loading = NO;
}

- (void)dealloc {
    [_subscribeCallback invalidate];
}

@end

redpajama_set_name: RedPajamaGithub


text:
<?php
require_once 'netconf/Device.php';

class DeviceTest extends PHPUnit_Framework_TestCase {
    protected static $d;
    public static function setUpBeforeClass()
    {
        self::$d = new Device("hostname", "username", "password");
    }

/**
     * @covers Device::connect
     * @todo   Implement testConnect().
    */
  public function testConnect() {
    self::$d->connect();
    $conn= self::$d->last_rpc_reply;
    $this->assertGreaterThan(-1,strpos($conn, "</hello>"));
    }

/**
     * @covers Device::execute_rpc
     * @todo   Implement testExecute_rpc().
     * @depends testConnect
     */
  public function testExecute_rpc() {
      self::$d->execute_rpc("get-alarm-information");
      $exe=self::$d->last_rpc_reply;
      $this->assertGreaterThan(-1,strpos($exe,"rpc-reply"));
      $this->assertGreaterThan(-1, strpos($exe,"alarm"));
      $this->assertFalse(strpos($exe,"error"));
        }

    /**
     * @covers Device::lock_config
     * @todo   Implement testLock_config().
     * @depends testConnect
*/
   public function testLock_config() {
    self::$d->lock_config();
    $isloc=  self::$d->last_rpc_reply;
    $this->assertGreaterThan(-1,strpos($isloc,"rpc-reply"));
    $this->assertGreaterThan(-1,strpos($isloc,"<ok/>"));
    }

    /**
     * @covers Device::load_xml_configuration
     * @todo   Implement testLoad_xml_configuration().
     * @depends testConnect
     * @depends testLock_config
     */
    public function testLoad_xml_configuration() {
        $str1= "<system><services><ftp/></services></system>";
        self::$d->load_xml_configuration($str1, "merge");
        $isloaded=  self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1,strpos($isloaded,"rpc-reply"));
        $this->assertGreaterThan(-1,strpos($isloaded,"<ok/>"));
    }

    /**
     * @covers Device::load_text_configuration
     * @todo   Implement testLoad_text_configuration().
     * @depends testConnect
     * @depends testLock_config
     */
    public function testLoad_text_configuration() {
        $str1= "system { services {ftp; }}";
        self::$d->load_text_configuration($str1, "merge");
        $isloaded=  self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1,strpos($isloaded,"rpc-reply"));
        $this->assertGreaterThan(-1,strpos($isloaded,"<ok/>"));
    }

    /**
     * @covers Device::load_set_configuration
     * @todo   Implement testLoad_set_configuration().
     * @depends testConnect
     * @depends testLock_config
     */
    public function testLoad_set_configuration() {
        $str1= "set system services ftp";
        self::$d->load_set_configuration($str1);
        $isloaded=  self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1,strpos($isloaded,"rpc-reply"));
        $this->assertGreaterThan(-1,strpos($isloaded,"<ok/>"));
     }

    /**
     * @covers Device::commit
     * @todo   Implement testCommit().
     * @depends testConnect
     * @depends testLock_config
     */
    public function testCommit() {
        self::$d->commit();
        $comm=self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1,strpos($comm,"rpc-reply"));
        $this->assertGreaterThan(-1,strpos($comm,"<ok/>"));
     }

    /**
     * @covers Device::commit_confirm
     * @todo   Implement testCommit_confirm().
     * @depends testConnect
     */
    public function testCommit_confirm() {
        self::$d->commit_confirm(40);
        $ccon=  self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1,strpos($ccon,"rpc-reply"));
        $this->assertGreaterThan(-1,strpos($ccon,"<ok/>"));
    }

    /**
     * @covers Device::validate
     * @todo   Implement testValidate().
     * @depends testConnect
     */
    public function testValidate() {
        self::$d->validate();
        $val=  self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1,strpos($val,"rpc-reply"));
        $this->assertGreaterThan(-1,  strpos($val,"<ok/>"));
    }

    /**
     * @covers Device::load_xml_file
     * @todo   Implement testLoad_xml_file().
     * @depends testConnect
     * depends testLock_Config
     */
    public function testLoad_xml_file() {
        self::$d->load_xml_file("/path/of/file");
        $isloaded=  self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1,strpos($isloaded,"rpc-reply"));
        $this->assertGreaterThan(-1,strpos($isloaded,"<ok/>"));
    }

     /**
     * @covers Device::load_text_file
     * @todo   Implement testLoad_text_file().
     * depends testConnect
     * depends testLoad_config
     */
    public function testLoad_text_file() {
        self::$d->load_text_file("/path/of/file");
        $isloaded=  self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1,strpos($isloaded,"rpc-reply"));
        $this->assertGreaterThan(-1,strpos($isloaded,"<ok/>"));
   }

    /**
     * @covers Device::load_set_file
     * @todo   Implement testLoad_set_file().
     * @depends testConnect
     * @depends testLock_config
     */
    public function testLoad_set_file() {
        self::$d->load_set_file("path/of/file");
        $isloaded=  self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1,strpos($isloaded,"rpc-reply"));
        $this->assertGreaterThan(-1,strpos($isloaded,"<ok/>"));
    }

    /**
     * @covers Device::get_running_config
     * @todo   Implement testGet_running_config().
     * depends testConnect
     */
    public function testGet_running_config() {
        self::$d->get_running_config();
        $run_conf=  self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1, strpos($run_conf,"rpc-reply"));
        $this->assertGreaterThan(-1, strpos($run_conf,"<data>"));
   }

    /**
     * @covers Device::unlock_config
     * @todo   Implement testUnlock_config().
     * @depends testConnect
     * @depends testLock_config
     */
    public function testUnlock_config() {
    self::$d->unlock_config();
    $isloc=  self::$d->last_rpc_reply;
    $this->assertGreaterThan(-1,strpos($isloc,"rpc-reply"));
    $this->assertGreaterThan(-1,strpos($isloc,"<ok/>"));
    }

    /**
     * @covers Device::open_configuration
     * @todo   Implement testOpen_configuration().
     * @depends testConnect
     * @depends testUnlock_config

     */
    public function testOpen_configuration() {
        self::$d->open_configuration();
        $open_conn=  self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1,strpos($open_conn,"<error-severity>warning</error-severity>"));
     }

    /**
     * @covers Device::close_configuration
     * @todo   Implement testClose_configuration().
     * @depends testConnect
     * @depends testOpen_configuration
     */
    public function testClose_configuration() {
         self::$d->close_configuration();
         $close_conf=  self::$d->last_rpc_reply;
         $this->assertGreaterThan(-1,strpos($close_conf,"rpc-reply"));
    }

    /**
     * @covers Device::close
     * @todo   Implement testClose().
     * @depends testConnect
     */
    public function testClose() {
        self::$d->close();
        $c=  self::$d->last_rpc_reply;
        $this->assertGreaterThan(-1,strpos($c,"rpc-reply"));
    }
}

?>


text:
专业管理

<form action="" method="GET">

    <input type="text" class="form-control" name="q" placeholder="专业编号, 专业名称...">

      <button class="btn btn-danger" type="submit">    搜索    </button>

</form>

      <button type="button" class="btn btn-default" data-toggle="modal" data-target="#newMajor"> 添加教学计划</button>

      <button type="button" class="btn btn-default" data-toggle="modal" data-target="#importMajor" > 批量导入</button>

      <button type="button" class="btn btn-danger"> 批量删除</button>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

添加教学计划

      <form>

            <input type="text" class="form-control" name="subjectid" >

          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <input type="submit" class="btn btn-danger" value="添加">

      </form>

        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

导入教学计划

      <form >

              <input type="file" class="btn btn-default btn-block" name="file">

          <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
          <input type="submit" class="btn btn-danger" value="导入">

      </form>

      专业(ID)
      必修
      学科基础选修课
      专业任选课
      专业限选课

Comming Soon

«

1 (current)

2

3

4

5

»

<link href="<?php echo $this->path; ?>/assets/css/admin.css" rel="stylesheet">


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>KmlCoord Interface Reference - Google Earth API - Google Code</title>

<link href="../../../../css/codesite.pack.04102009.css" type="text/css" rel="stylesheet">

<link rel="search" type="application/opensearchdescription+xml" title="Google Code" href="http://code.google.com/osd.xml">

    <link href="../../../../css/semantic_headers.css" rel="stylesheet" type="text/css" />
    <link href="stylesheet.css" rel="stylesheet" type="text/css">
    <link href="tabs.css" rel="stylesheet" type="text/css">

    English ▼

  Skip to page content
  Skip to main navigation

      <form id="cse" action="http://www.google.com/cse" accept-charset="utf-8" class="gsc-search-box" onsubmit="executeGSearch(document.getElementById('gsearchInput').value); return false;">

      <input type="hidden" name="cref" value="http://code.google.com/cse/googlecode-context.xml">

        <input id="gsearchInput" type="text" name="q" maxlength="2048" class="gsc-input" autocomplete="off" title="Google Code Search" style="width:345px">

        <input title="Search" id="gsearchButton" class="gsc-search-button" name="sa" value="Search" type="submit">

e.g. "ajax apis" or "open source"

      </form>

Make web development faster with these Chrome Extensions!

Google Earth API

      Home

      Docs

      FAQ

      Articles

      Blog

      Forum

      Terms

Sign up for a Maps API key

API Reference

Developer's Guide

Introduction

Placemarks

Balloons

Geometries & Overlays

Camera Control

Layers & Controls

Time Updated

Ocean

Sky, Mars, & Moon

Touring

Events

Accessors New!

Object Containers

KML

Options

Debugging

Code Samples

Examples

Demo Gallery

Code Playground

More Resources

Media

Release Notes

Utility Library

Known Issues

Related Docs

KML

Maps API

        More Google Earth API resource links

KmlCoord Interface Reference
Inherits KmlObjectBase.

List of all members.

Public Member Functions

void 	setLatLngAlt (double latitude, double longitude, double altitude)

double 	getLatitude ()

void 	setLatitude (double latitude)

double 	getLongitude ()

void 	setLongitude (double longitude)

double 	getAltitude ()

void 	setAltitude (double altitude)

Detailed Description

A single tuple consisting of floating point values for longitude, latitude, and altitude (in that order). Longitude and latitude values are in degrees.

longitude = -180 and <= 180

latitude = -90 and = 90

altitude values (optional) are in meters above sea level

Member Function Documentation

          void KmlCoord.setLatLngAlt
          (
          double
           latitude,

          double
           longitude,

          double
           altitude

          )

Sets the latitude, longitude, altitude.

          double KmlCoord.getLatitude
          (

           )

Degrees north or south of the Equator (0 degrees). Values range from -90 degrees (South Pole) to 90 degrees (North Pole).

          void KmlCoord.setLatitude
          (
          double
           latitude
           )

Degrees north or south of the Equator (0 degrees). Values range from -90 degrees (South Pole) to 90 degrees (North Pole).

          double KmlCoord.getLongitude
          (

           )

Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. Values east of the Meridian range from 0 to 180 degrees.

          void KmlCoord.setLongitude
          (
          double
           longitude
           )

Angular distance in degrees, relative to the Prime Meridian. Values west of the Meridian range from -180 to 0 degrees. Values east of the Meridian range from 0 to 180 degrees.

          double KmlCoord.getAltitude
          (

           )

Distance from the earth's surface.

          void KmlCoord.setAltitude
          (
          double
           altitude
           )

Distance from the earth's surface.

    ©2010 Google -
    Code Home -
    Terms of Service -
    Privacy Policy -
    Site Directory

    Google Code offered in:
    English -
    Español -
    日本語 -
    한국어 -
    Português -
    Pусский -
    中文(简体) -
    中文(繁體)


text:
#pragma once

#if ENABLE(MATHML)

#include "RenderMathMLBlock.h"

namespace WebCore {

class MathMLTokenElement;

class RenderMathMLToken : public RenderMathMLBlock {
    WTF_MAKE_ISO_ALLOCATED(RenderMathMLToken);
public:
    RenderMathMLToken(MathMLTokenElement&, RenderStyle&&);
    RenderMathMLToken(Document&, RenderStyle&&);

    MathMLTokenElement& element();

    virtual void updateTokenContent();
    void updateFromElement() override;

protected:
    void paint(PaintInfo&, const LayoutPoint&) override;
    void paintChildren(PaintInfo& forSelf, const LayoutPoint&, PaintInfo& forChild, bool usePrintRect) override;
    std::optional<int> firstLineBaseline() const override;
    void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) override;
    void computePreferredLogicalWidths() override;

private:
    bool isRenderMathMLToken() const final { return true; }
    const char* renderName() const override { return "RenderMathMLToken"; }
    bool isChildAllowed(const RenderObject&, const RenderStyle&) const final { return true; };
    void styleDidChange(StyleDifference, const RenderStyle* oldStyle) override;
    void updateMathVariantGlyph();
    void setMathVariantGlyphDirty()
    {
        m_mathVariantGlyphDirty = true;
        setNeedsLayoutAndPrefWidthsRecalc();
    }
    std::optional<UChar32> m_mathVariantCodePoint { std::nullopt };
    bool m_mathVariantIsMirrored { false };
    bool m_mathVariantGlyphDirty { false };
};

} // namespace WebCore

SPECIALIZE_TYPE_TRAITS_RENDER_OBJECT(RenderMathMLToken, isRenderMathMLToken())

#endif // ENABLE(MATHML)


text:
class Api::V1::FeedVersionImportsController < Api::V1::BaseApiController
  include JsonCollectionPagination
  include AllowFiltering
  include DownloadableCsv

  before_action :set_feed_version_import, only: [:show]

  def index
    @feed_version_imports = FeedVersionImport.where('')
    @feed_version_imports = AllowFiltering.by_primary_key_ids(@feed_version_imports, params)

    if params[:feed_onestop_id].present?
      feed_onestop_ids = params[:feed_onestop_id].split(',')
      @feed_versions = @feed_version_imports.where(feed: Feed.where(onestop_id: feed_onestop_ids))
    end

    if params[:feed_version_sha1].present?
      feed_version_sha1s = params[:feed_version_sha1].split(',')
      @feed_versions = @feed_version_imports.where(feed_version: FeedVersion.where(sha1: feed_version_sha1s))
    end

    respond_to do |format|
      format.json { render paginated_json_collection(@feed_version_imports) }
      format.csv { return_downloadable_csv(@feed_version_imports, 'feed_version_imports') }
    end
  end

  def show
    render json: @feed_version_import
  end

  private

  def query_params
    super.merge({
      ids: {
        desc: "FeedVersionImport IDs",
        type: "integer",
        array: true
      },
      feed_onestop_id: {
        desc: "Feed",
        type: "onestop_id",
        array: true
      },
      feed_version_sha1: {
        desc: "Feed Version",
        type: "sha1",
        array: true
      }
    })
  end

  def set_feed_version_import
    @feed_version_import = FeedVersionImport.find(params[:id])
  end
end


text:
# Pack Command (choco pack)

Chocolatey will attempt to package a nuspec into a compiled nupkg. Some
 may prefer to use `cpack` as a shortcut for `choco pack`.

**NOTE:** 100% compatible with older chocolatey client (0.9.8.32 and below)
 with options and switches. In most cases you can still pass options
 and switches with one dash (`-`). For more details, see
 [[how to pass arguments|CommandsReference#how-to-pass-options--switches]] (`choco -?`).

**NOTE:** `cpack` has been deprecated as it has a name collision with CMake. Please
 use `choco pack` instead. The shortcut will be removed in v1.

## Usage

    choco pack [<path to nuspec>] [<options/switches>]
    cpack [<path to nuspec>] [<options/switches>] (DEPRECATED)

## Examples

    choco pack
    choco pack --version 1.2.3
    choco pack path/to/nuspec
    choco pack --outputdirectory build

## Options and Switches

**NOTE:** Options and switches apply to all items passed, so if you are
 running a command like install that allows installing multiple
 packages, and you use `--version=1.0.0`, it is going to look for and
 try to install version 1.0.0 of every package passed. So please split
 out multiple package calls when wanting to pass specific options.

Includes [[default options/switches|CommandsReference#default-options-and-switches]] (included below for completeness).

~~~

 -?, --help, -h
     Prints out the help menu.

 -d, --debug
     Debug - Show debug messaging.

 -v, --verbose
     Verbose - Show verbose messaging.

     --acceptlicense, --accept-license
     AcceptLicense - Accept license dialogs automatically. Reserved for
       future use.

 -y, --yes, --confirm
     Confirm all prompts - Chooses affirmative answer instead of prompting.
       Implies --accept-license

 -f, --force
     Force - force the behavior. Do not use force during normal operation -
       it subverts some of the smart behavior for commands.

     --noop, --whatif, --what-if
     NoOp / WhatIf - Don't actually do anything.

 -r, --limitoutput, --limit-output
     LimitOutput - Limit the output to essential information

     --timeout, --execution-timeout=VALUE
     CommandExecutionTimeout (in seconds) - The time to allow a command to
       finish before timing out. Overrides the default execution timeout in the
       configuration of 2700 seconds.

 -c, --cache, --cachelocation, --cache-location=VALUE
     CacheLocation - Location for download cache, defaults to %TEMP% or value
       in chocolatey.config file.

     --allowunofficial, --allow-unofficial, --allowunofficialbuild, --allow-unofficial-build
     AllowUnofficialBuild - When not using the official build you must set
       this flag for choco to continue.

     --failstderr, --failonstderr, --fail-on-stderr, --fail-on-standard-error, --fail-on-error-output
     FailOnStandardError - Fail on standard error output (stderr), typically
       received when running external commands during install providers. This
       overrides the feature failOnStandardError.

     --use-system-powershell
     UseSystemPowerShell - Execute PowerShell using an external process
       instead of the built-in PowerShell host. Should only be used when
       internal host is failing. Available in 0.9.10+.

     --version=VALUE
     Version - The version you would like to insert into the package.

     --outputdirectory=VALUE
     OutputDirectory - Specifies the directory for the created Chocolatey
       package file. If not specified, uses the current directory.

~~~

[[Command Reference|CommandsReference]]

***NOTE:*** This documentation has been automatically generated from `choco pack -h`.


text:
Check out [CodeDay](https://codeday.org), a 24-hour programming event for students.

This project is forked from [AlexEKoren/Technify](https://github.com/AlexEKoren/Technify).

Here's a [demo](http://codedayify.y4ng.com).

![Example image](https://scontent-iad3-1.xx.fbcdn.net/v/t1.0-9/13094188_1013828435371689_9026862867734553752_n.jpg?oh=a7bde7b9823ecf6e56fe7ca223f971c9&oe=57A93435 "Example image")
An example of what I got from putting my Facebook profile picture through it.

## Setup
```
pip install -r requirements.txt
```

## Running the app
```
python app.py
```
Runs on [http://localhost:5000](http://localhost:5000) by default.


text:
namespace cobalt {
namespace css_parser {

// This helps parsing and verifying syntax of the text-decoration shorthand
// property value.
struct TextDecorationShorthand {
  TextDecorationShorthand() : error(false) {}

  void ReplaceNullWithInitialValues();

  bool error;
  scoped_refptr<cssom::PropertyValue> line;
  scoped_refptr<cssom::PropertyValue> color;
};

}  // namespace css_parser
}  // namespace cobalt

#endif  // COBALT_CSS_PARSER_TEXT_DECORATION_SHORTHAND_PROPERTY_PARSE_STRUCTURES_H_


text:
package doodle.core

import scala.annotation.tailrec

/**
  * A value in the range [0, 1]
  */
final case class Normalized(get: Double) extends AnyVal {
  def +(that: Normalized): Double =
    this.get + that.get

  def -(that: Normalized): Double =
    this.get - that.get

  def max(that: Normalized): Normalized =
    if(this.get > that.get)
      this
    else
      that

  def min(that: Normalized): Normalized =
    if(this.get < that.get)
      this
    else
      that

  def toTurns: Angle =
    Angle.turns(get)

  def toPercentage: String =
    s"${get * 100}%"

  def toUnsignedByte: UnsignedByte =
    UnsignedByte.clip(Math.round(get * UnsignedByte.MaxValue.get).toInt)

  def toCanvas: String =
    get.toString
}

object Normalized {
  val MinValue = Normalized(0.0)
  val MaxValue = Normalized(1.0)

  def clip(value: Double): Normalized =
    value match {
      case v if value < 0.0 => MinValue
      case v if value > 1.0 => MaxValue
      case v => Normalized(v)
    }

  def wrap(value: Double): Normalized = {
    @tailrec def loop(value: Double): Normalized = value match {
      case v if v > 1.0 => loop(v - 1.0)
      case v if v < 0.0 => loop(v + 1.0)
      case v => Normalized(v)
    }

    loop(value)
  }
}


text:
package com.helger.as4.client;

import java.io.IOException;

import javax.annotation.Nonnull;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.http.HttpHost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import com.helger.as4.attachment.WSS4JAttachment;
import com.helger.as4.crypto.AS4CryptParams;
import com.helger.as4.crypto.AS4CryptoFactory;
import com.helger.as4.crypto.AS4SigningParams;
import com.helger.as4.http.HttpMimeMessageEntity;
import com.helger.as4.http.HttpXMLEntity;
import com.helger.as4.messaging.crypto.AS4Encryptor;
import com.helger.as4.messaging.crypto.AS4Signer;
import com.helger.as4.messaging.domain.AS4UserMessage;
import com.helger.as4.messaging.domain.MessageHelperMethods;
import com.helger.as4.messaging.mime.AS4MimeMessage;
import com.helger.as4.messaging.mime.MimeMessageCreator;
import com.helger.as4.soap.ESOAPVersion;
import com.helger.as4.util.AS4ResourceHelper;
import com.helger.commons.collection.impl.CommonsArrayList;
import com.helger.commons.collection.impl.ICommonsList;
import com.helger.commons.io.resource.ClassPathResource;
import com.helger.commons.mime.CMimeType;
import com.helger.httpclient.HttpClientFactory;
import com.helger.xml.serialize.read.DOMReader;

public final class MainAS4Client
{
  private static final Logger LOGGER = LoggerFactory.getLogger (MainAS4Client.class);

  private MainAS4Client ()
  {}

  public static Document getSoapEnvelope11ForTest (@Nonnull final String sPath) throws SAXException,
                                                                                IOException,
                                                                                ParserConfigurationException
  {
    final DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance ();
    domFactory.setNamespaceAware (true); // never forget this!
    final DocumentBuilder builder = domFactory.newDocumentBuilder ();
    return builder.parse (new ClassPathResource (sPath).getInputStream ());
  }

  /**
   * Starting point for the SAAJ - SOAP Client Testing
   *
   * @param args
   *        ignored
   */
  public static void main (final String [] args)
  {
    try (final AS4ResourceHelper aResHelper = new AS4ResourceHelper ())
    {
      String sURL = "http://127.0.0.1:8080/as4";
      if (false)
        sURL = "http://msh.holodeck-b2b.org:8080/msh";

      // Deactivate if not sending to localholodeck
      if (false)
        sURL = "http://localhost:8080/msh/";

      final HttpClientFactory aHCF = new HttpClientFactory ();
      if (sURL.startsWith ("https"))
        aHCF.setSSLContextTrustAll ();
      if (true)
      {
        aHCF.setProxy (new HttpHost ("172.30.9.6", 8080));
        aHCF.addNonProxyHostsFromPipeString ("localhost|127.0.0.1");
      }
      final CloseableHttpClient aClient = aHCF.createHttpClient ();

      LOGGER.info ("Sending to " + sURL);
      final HttpPost aPost = new HttpPost (sURL);

      final ICommonsList <WSS4JAttachment> aAttachments = new CommonsArrayList <> ();
      final Node aPayload = DOMReader.readXMLDOM (new ClassPathResource ("SOAPBodyPayload.xml"));
      final ESOAPVersion eSOAPVersion = ESOAPVersion.SOAP_12;
      final AS4CryptoFactory aCryptoFactory = AS4CryptoFactory.DEFAULT_INSTANCE;

      // No Mime Message Not signed or encrypted, just SOAP + Payload in SOAP -
      // Body
      if (true)
      {
        // final Document aDoc = TestMessages.testSignedUserMessage
        // (ESOAPVersion.SOAP_11, aPayload, aAttachments);
        final AS4UserMessage aMsg = MockClientMessages.testUserMessageSoapNotSigned (eSOAPVersion,
                                                                                aPayload,
                                                                                aAttachments);
        final Document aDoc = aMsg.getAsSOAPDocument (aPayload);
        aPost.setEntity (new HttpXMLEntity (aDoc, eSOAPVersion));
      }
      else
        // BodyPayload SIGNED
        if (false)
        {
          final Document aDoc = MockClientMessages.testSignedUserMessage (eSOAPVersion,
                                                                          aPayload,
                                                                          aAttachments,
                                                                          aResHelper);
          aPost.setEntity (new HttpXMLEntity (aDoc, eSOAPVersion));
        }
        // BodyPayload ENCRYPTED
        else
          if (false)
          {
            final AS4UserMessage aMsg = MockClientMessages.testUserMessageSoapNotSigned (eSOAPVersion,
                                                                                aPayload,
                                                                                aAttachments);
            Document aDoc = aMsg.getAsSOAPDocument (aPayload);
            aDoc = AS4Encryptor.encryptSoapBodyPayload (aCryptoFactory,
                                                        eSOAPVersion,
                                                        aDoc,
                                                        false,
                                                        AS4CryptParams.createDefault ().setAlias ("dummy"));

            aPost.setEntity (new HttpXMLEntity (aDoc, eSOAPVersion));
          }
          else
            if (true)
            {
              aAttachments.add (WSS4JAttachment.createOutgoingFileAttachment (ClassPathResource.getAsFile ("attachment/test.xml.gz"),
                                                                              CMimeType.APPLICATION_GZIP,
                                                                              null,
                                                                              aResHelper));
              final AS4UserMessage aMsg = MockClientMessages.testUserMessageSoapNotSigned (eSOAPVersion,
                                                                                null,
                                                                                aAttachments);
              final AS4MimeMessage aMimeMsg = MimeMessageCreator.generateMimeMessage (eSOAPVersion,
                                                                                AS4Signer.createSignedMessage (aCryptoFactory,
                                                                                aMsg.getAsSOAPDocument (null),
                                                                                eSOAPVersion,
                                                                                aMsg.getMessagingID (),
                                                                                aAttachments,
                                                                                aResHelper,
                                                                                false,
                                                                                AS4SigningParams.createDefault ()),
                                                                                aAttachments);

              // Move all global mime headers to the POST request
              MessageHelperMethods.forEachHeaderAndRemoveAfterwards (aMimeMsg, aPost::addHeader);
              aPost.setEntity (new HttpMimeMessageEntity (aMimeMsg));
            }
            else
              if (false)
              {
                Document aDoc = MockClientMessages.testSignedUserMessage (eSOAPVersion,
                                                                          aPayload,
                                                                          aAttachments,
                                                                          aResHelper);
                aDoc = AS4Encryptor.encryptSoapBodyPayload (aCryptoFactory,
                                                            eSOAPVersion,
                                                            aDoc,
                                                            false,
                                                            AS4CryptParams.createDefault ().setAlias ("dummy"));
                aPost.setEntity (new HttpXMLEntity (aDoc, eSOAPVersion));
              }
              else
                throw new IllegalStateException ("Some test message should be selected :)");

      // XXX reinstate if you wanna see the request that is getting sent
      LOGGER.info (EntityUtils.toString (aPost.getEntity ()));

      final CloseableHttpResponse aHttpResponse = aClient.execute (aPost);

      LOGGER.info ("GET Response Status:: " + aHttpResponse.getStatusLine ().getStatusCode ());

      // print result
      LOGGER.info (EntityUtils.toString (aHttpResponse.getEntity ()));
    }
    catch (final Exception e)
    {
      LOGGER.error ("Error occurred while sending SOAP Request to Server", e);
    }
  }
}


text:
function SerieFunction( name, arg ){
    name.trim();
    this._name = name;
    this._arg = arg;
}

SerieFunction.prototype.getName = function(){
    return this._name;
};

SerieFunction.prototype.getArguments = function(){
    return this._arg;
};

SerieFunction.prototype.getArgumentAtIndex = function( index ){
    return this._arg[index];
};


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.XPath;

namespace FifteenBelow.Deployment.Update
{
    public class TagDictionary : Dictionary<string, object>
    {
        public struct DbLogin
        {
            public string Username;
            public string Password;
            public string DefaultDb;
            public string ConnectionString;

            public override string ToString()
            {
                return Username;
            }
        }

        public struct User
        {
            public string Name;
            public string Role;
        }

        public Dictionary<string, DbLogin> DbLogins = new Dictionary<string, DbLogin>();
        // These values (and no others) can be used as tags in property values
        private static readonly string[] ValidTagsInProperties = new[] { "ClientCode", "Environment", "DbServer" };
        private HashSet<string> idSpecificValues = new HashSet<string>();
        private Dictionary<string, IEnumerable<string>> labelsAndIdentities = new Dictionary<string, IEnumerable<string>>();

        private TagDictionary(string identifier, bool isLabel, params Tuple<string, TagSource>[] sources)
        {
            if (sources.Length == 0) { sources = new[] { Tuple.Create("", TagSource.Environment) }; }
            foreach (var source in sources)
            {
                switch (source.Item2)
                {
                    case TagSource.Environment:
                        LoadEnviroment();
                        break;
                    case TagSource.XmlFileName:
                        LoadXmlFileName(source.Item1, identifier);
                        break;
                    case TagSource.XmlData:
                        LoadXmlData(source.Item1, identifier);
                        break;
                }
            }
            this.ToList().ForEach(pair => this[pair.Key] = GetExpandedPropertyValue(pair.Value.ToString()));
            var expandedLogins = new Dictionary<string, DbLogin>();
            foreach (var name in DbLogins.Keys)
            {
                var login = DbLogins[name];
                expandedLogins[name] = new DbLogin { DefaultDb = GetExpandedPropertyValue(login.DefaultDb), Password = login.Password, Username = GetExpandedPropertyValue(login.Username), ConnectionString = GetExpandedPropertyValue(login.ConnectionString) };
            }
            DbLogins = expandedLogins;
            Add("DbLogins", DbLogins);
            if (!isLabel)
            {
                foreach (var label in labelsAndIdentities.Keys)
                {
                    if (ContainsKey(label))
                    {
                        throw new InvalidDataException(
                            string.Format(
                                "A label for a method group has been specified that clashes with a property name. The conflicting label is {0}",
                                label));
                    }
                    var labelEnumerable = new List<IDictionary<string, object>>();
                    foreach (var id in labelsAndIdentities[label])
                    {
                        labelEnumerable.Add(new TagDictionary(id, true, sources));
                    }
                    this[label] = labelEnumerable;
                }
            }
        }

        public TagDictionary(string identifier, params Tuple<string, TagSource>[] sources)
            : this(identifier, false, sources)
        {

        }

        public TagDictionary(string identifier, string xmlData) :
            this(identifier, Tuple.Create("", TagSource.Environment), Tuple.Create(xmlData, TagSource.XmlData))
        { }

        private void LoadXmlFileName(string fileName, string identifier)
        {
            XDocument doc;
            try
            {
                doc = XDocument.Load(new FileStream(fileName, FileMode.Open, FileAccess.Read));
            }
            catch (Exception)
            {
                doc = new XDocument();
            }
            PropertiesFromXml(identifier, doc);
        }

        private void LoadXmlData(string xml, string identifier)
        {
            if (string.IsNullOrEmpty(xml)) return;
            XDocument doc;
            try
            {
                doc = XDocument.Parse(xml);
            }
            catch (Exception)
            {
                doc = new XDocument();
            }
            PropertiesFromXml(identifier, doc);
        }

        private static Tuple<string, string> GetTagInPropertyValue(XDocument doc, string propName)
        {
            var xEl = doc.XPathSelectElement(string.Format("Structure/{0}", propName)) ??
                      doc.XPathSelectElements("/Structure/Properties/Property").FirstOrDefault(
                          el => el.Attribute("name").Value == propName);
            return Tuple.Create(propName, xEl == null ? "" : xEl.Value);
        }

        private void PropertiesFromXml(string identifier, XDocument doc)
        {
            if (!string.IsNullOrEmpty(identifier)) AddOrDiscard("identity", identifier);
            ValidTagsInProperties
                .Select(str => GetTagInPropertyValue(doc, str))
                .ToList()
                .ForEach(tuple => AddOrDiscard(tuple.Item1, tuple.Item2));

            var matchingGroupProperties =
                doc.XPathSelectElements("/Structure/PropertyGroups/PropertyGroup")
                    .Where(p => p.Name == "PropertyGroup").Where(p => p.Attribute("identity").Value == identifier)
                    .Select(pg => pg.XPathSelectElements("Properties/Property"))
                    .Aggregate(new List<XElement>(), (list, elements) => list.Concat(elements).ToList());
            var generalProperties =
                doc.XPathSelectElements("/Structure/Properties/Property");
            var labelledGroups =
                doc.XPathSelectElements("/Structure/PropertyGroups/PropertyGroup")
                    .Where(pg => pg.Elements().Select(e => e.Name).Contains("Label"));

            foreach (var prop in matchingGroupProperties)
            {
                var key = prop.Attribute("name").Value;
                var value = prop.Value.Trim();
                AddOrDiscard(key, value, true);
            }
            foreach (var prop in generalProperties)
            {
                var key = prop.Attribute("name").Value;
                var value = prop.Value.Trim();
                AddOrDiscard(key, value);
            }
            foreach (var labelledGroup in labelledGroups)
            {
                var labels = labelledGroup.Elements("Label").Select(e => e.Value);
                var identity = labelledGroup.Attribute("identity").Value;
                foreach (var label in labels)
                {
                    if (labelsAndIdentities.Keys.Contains(label))
                    {
                        labelsAndIdentities[label] = labelsAndIdentities[label].Concat(new List<string> { identity });
                    }
                    else
                    {
                        labelsAndIdentities[label] = new List<string> { identity };
                    }
                }
            }

            var dbLoginElements =
                doc.XPathSelectElements("/Structure/DbLogins/DbLogin");
            foreach (var dbLoginElement in dbLoginElements)
            {
                var fullname = dbLoginElement.XPathSelectElement("Name").Value;
                const string prefix = "tagClientCode-tagEnvironment-";
                var key = fullname.StartsWith(prefix) ? fullname.Substring(prefix.Length) : fullname;
                if (!DbLogins.ContainsKey(key))
                {
                    string password = string.Empty;
                    string defaultDb = string.Empty;
                    string connectionString = string.Empty;

                    if (string.IsNullOrWhiteSpace(dbLoginElement.TryXPathValueWithDefault("ConnectionString", "")))
                    {
                        password = dbLoginElement.XPathSelectElement("Password").Value;
                        defaultDb = dbLoginElement.XPathSelectElement("DefaultDb").Value;
                        connectionString = string.Format("Data Source={{{{ DbServer }}}}; Initial Catalog={0}; User ID={1}; Password={2};",dbLoginElement.XPathSelectElement("DefaultDb").Value, fullname,dbLoginElement.XPathSelectElement("Password").Value);
                    }
                    else
                    {
                        connectionString = dbLoginElement.XPathSelectElement("ConnectionString").Value;
                    }

                    DbLogins.Add(key,
                    new DbLogin
                        {
                            Username = fullname,
                            Password = password,
                            DefaultDb = defaultDb,
                            ConnectionString = connectionString
                        });
                }
            }
        }

        private string GetExpandedPropertyValue(string baseValue)
        {
            var shortTagList = ValidTagsInProperties.Where(Keys.Contains).ToDictionary(str => str, str => this[str]);

            // TODO: Remove this replacement set once move to delimetered tags complete
            var djangoStyleValue = baseValue
                .Replace("tagDbServer", "{{ DbServer }}")
                .Replace("tagClientCode", "{{ ClientCode }}")
                .Replace("tagEnvironment", "{{ Environment }}");
            return djangoStyleValue.RenderTemplate(shortTagList);
        }

        private void LoadEnviroment()
        {
            var env = Environment.GetEnvironmentVariables();
            foreach (var key in env.Keys)
            {
                var wantedKey = key.ToString();
                if (wantedKey.StartsWith("Octopus"))
                {
                    wantedKey = wantedKey
                        .Split(new[] { "Octopus" }, 2, StringSplitOptions.RemoveEmptyEntries).Last();
                    if (wantedKey.EndsWith("Name"))
                        wantedKey = wantedKey.Substring(0, wantedKey.Length - "Name".Length);
                }
                AddOrDiscard(wantedKey, env[key].ToString());
            }
        }

        public void AddOrDiscard(string key, string value, bool idSpecific = false)
        {
            if (!Keys.Contains(key))
                Add(key, value);
            if (Keys.Contains(key) && !idSpecificValues.Contains(key) && idSpecific)
                this[key] = value;
            if (idSpecific) idSpecificValues.Add(key);
        }

        public string GetDbPassword(string dbUserName)
        {
            return DbLogins[dbUserName].Password;
        }
    }

    public enum TagSource
    {
        Environment,
        XmlFileName,
        XmlData
    }
}


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

namespace ConsensusBot.Voting
{
   class ConsensusVote
   {
   }
}


text:
<!-- [![Travis](https://img.shields.io/travis/c0bra/generator-ui-grid-plugin.svg)](https://travis-ci.org/c0bra/generator-ui-grid-plugin) [![devDependencies](https://img.shields.io/david/dev/c0bra/generator-ui-grid-plugin.svg?style=flat)](https://david-dm.org/c0bra/ui-grid-plugin-skeleton#info=devDependencies) [![Coveralls](https://img.shields.io/coveralls/c0bra/generator-ui-grid-plugin.svg?style=flat)](https://coveralls.io/r/c0bra/generator-ui-grid-plugin) -->

This repo is a Yeoman generator for [UI-Grid](http://ui-grid.info) plugins.

![Screenshot](http://brianhann.com/wp-content/uploads/2015/04/ui-grid-plugin-generator.png)

# What You Get

* Standard Angular project build cycle, with jshint, jsrc, ngAnnotate, and lesscss
* Automated tests with Karma
* ~~Automated e2e tests with Protractor~~
* Automated docs generation with Dgeni
* Development environment based on your docs: use examples to demonstrate and test functionality.
* Automated publishing with gh-pages: use your generated docs files to create your plugin's website.

# Get Started

Install yeoman if you don't already have it, and the plugin generator:

    npm install -g yo generator-ui-grid-plugin

Create your plugin folder and bootstrap the plugin

    mkdir my-plugin
    cd my-plugin
    yo ui-grid-plugin

Follow the prompts. The generator will ask you for your plugin's name, its description, and blah. Wait for all the dependencies to be installed, then you can get started.

# Run it!

You can start up a development task like so. It will run on port 4000. If you want another port there's a switch for that.

    gulp watch
    gulp watch --port 9999

# Writing Your Plugin

* All the .js files in src/ will be concatenated together and ngAnnotated.
* Tests in test/ will be run with karma.
* You can add tutorials by putting .md files in `docs/content/`. They use markdown and @ngdoc formatting.
* You can add whatever other dependencies you need, from npm or bower.

# Caveats

* The JSHint and JSCS config follows the same practices that UI-Grid does (or at least UI-Grid tries to). It's kind of strict, so if you want to make modifications feel free.

# Badges

There's a generator for adding badge/shield images to the top of your README.md Just run this and select the options you want (you'll need to have your repository set in package.json):

    yo ui-grid-plugin:badges

## Coveralls

One of the badges is for Coveralls, and you'll need to sign up at http://coveralls.io if you want to use it. It's a great free, automated test coverage tool.

# Development

## Protractor

**Note:** Protractor tests do not work, currently. They throw a "window is not defined" error, which isn't documented well anywhere that I can find.

## Publish

The `publish` task takes automatically generated docs and dist files and push them to the gh-pages branch.

    gulp publish --tag v0.0.1

Travis will also publish to gh-pages. You will need to set the version in `bower.json` and `package.json`. A gulp-bump task is included to make it easier. Here's some examples:

    gulp bump --version 1.0.1
    gulp bump --type minor
    gulp bump --type patch

Commit and then push to GitHub. Travis will pick up the commit, create a tag for the new version, and push the updates to you gh-pages branch.

## Travis

In order for Travis to publish your generated content to your gh-pages branch on GitHub, you need to give it a secure token it can use. First you'll need to make sure you've set up your GitHub repo if you haven't already:

    git remote add origin https://github.com/yourname/your-repo.git

Then for encrypting your secure token Travis has a ruby gem that can do it:

    gem install travis

    travis login
    # enter your login info

    travis encrypt GITHUB_TOKEN=youtokenhere

It will print out the encrypted string. It's important to make sure you use `GITHUB_TOKEN` as the name and that you're in your project folder.

You can run this generator to add it:

    yo ui-grid-plugin:travis

It will prompt you for the encrypted string, and will store it in your `.travis.yml` file. Be sure to paste *just* the encrypted string and not the `secure: ` prefix or the double quotes around the string.


text:
"""
Generate a list of Arduino library Github URLs that can be consumed by the
Arduino team to add to their master repository list.  Takes a list of Arduino
library Github names on standard input (like the output of the find_libraries.py
script).  Will output on standard output a list of library Github URLs and types
in a tab delimited format.  Create a bug on the Arduino github to have this list
of libraries added to the master Arduino library list.
"""
import argparse
import os
import sys

from github import Github

if __name__ == '__main__':
    # Build command line argument parser and parse arguments.
    # Use docstring of the file as the description of the tool.
    parser = argparse.ArgumentParser(description=sys.modules[__name__].__doc__)
    parser.add_argument('-u', '--username',
                        action='store',
                        metavar='USERNAME',
                        default=os.environ.get('GITHUB_USERNAME', None),
                        help='Github username for accessing Github API.  If not specified the GITHUB_USERNAME environment variable value will be used.')
    parser.add_argument('-p', '--password',
                        action='store',
                        metavar='PASSWORD',
                        default=os.environ.get('GITHUB_PASSWORD', None),
                        help='Github password for accessing Github API.  If not specified the GITHUB_PASSWORD environment variable value will be used.')
    parser.add_argument('-t', '--type',
                        action='store',
                        metavar='TYPE',
                        default='Contributed',
                        help='repository type to assign to each library.  Defaults to Contributed.')
    parser.add_argument('github_root',
                        action='store',
                        help='Github user/organization name that owns the Arduino libraries')
    args = parser.parse_args()

    # Create github API instance and get account root.
    gh = Github(args.username, args.password)
    root = gh.get_user(args.github_root)

    # Process all Arduino library names from standard input.
    for repo_name in sys.stdin:
        repo_name = repo_name.strip()
        # Skip blank lines.
        if repo_name == '':
            continue
        # Get repository from github to find its description and other metadata.
        repo = root.get_repo(repo_name)
        # Print out git URL and repository type.
        url = repo.clone_url
        print('{0}\t{1}'.format(url, args.type))


text:
#include "Codec.h"

namespace ffmpeg {

struct Encoder : Codec
{
	Encoder() {}
	virtual ~Encoder(){}

	virtual AVCodec* find(AVCodecID id) { return avcodec_find_encoder(id); }
	virtual AVCodec* find(const char* name) { return avcodec_find_encoder_by_name(name); }

	virtual bool open()
	{
		context->pix_fmt = codec->pix_fmts[0];
		return Codec::open();
	}

	bool encode(AVFrame* frame, AVPacket* packet)
	{
		int got_packet = 0;
		return !avcodec_encode_video2(context, packet, frame, &got_packet) && got_packet;
	}
};

} //namespace ffmpeg

#endif // _FFMPEG_ENCODER_H__


text:
package cn.aezo.spring.base.annotation.aop;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Created by smalle on 2017/6/3.
 * 拦截规则
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Action {
    String name();
}


text:
<template name="home">

Welcome

This online chat application will be used as a common platform for all your social media accounts for chatting purposes, thus creating a pool of all your online friends and contacts.

</template>


text:
'use strict';

const util = require('util');
const utils = require('./utils');
const async = require('async');
const https = require('https');
const axios = require('axios');
const request = axios.create({
  httpsAgent: new https.Agent({
    rejectUnauthorized: false
  })
});

const {
  defaultOptions
} = require('./config');

// The rules define how the request and the response
// should look with output regex validation or request http options
// also formats the user input and cleans it in case of characters restrictions
const rules = require('./rules');

/**
 * Custom no match error
 */
function NoMatchException(message) {
  this.name = 'NOMATCH';
  this.message = message;
  this.response = {
    status: 200
  };
}

/**
 * Get the given url, optionally test rule matches
 * than resolve with the response body
 */
function execute(url, rule, options) {
  return new Promise((resolve, reject) => {
    const reqOpts = Object.assign({},
      options.requestOptions,
      rule.requestOptions || {}, {
        url
      }
    );

    request(reqOpts)
      .then(response => {
        const body = response.data;

        // Optionally perform additional checks
        // for example multiple regex test on response body
        if (rule.matches && utils.stringsMatch(rule.matches, body) === false) {
          throw new NoMatchException('Page content does not match rule regexp.');
        }

        resolve(body);
      }).catch(err => reject({
        status: err.response && err.response.status,
        message: err.message,
        error: err.name
      }));
  });
}

/**
 * The main module method than take a target username
 * and perform a deep scan following various rules
 * described in the rules file, optionally applying filters to
 * the username value to match the website schema defined in rule
 * @param  {String}   target       The username to scan for
 * @param  {Object}   options      The scanner options
 * @param  {Function} callback     The callback to execute when everything has done
 */
module.exports = function (target, options, callback) {
  if (!target || target === '') {
    throw new Error('The target parameter is missing.');
  }

  // Prepare variables
  const username = target;
  let filteredRules = rules.slice(0);

  // Extend options with default settings
  options = Object.assign({}, defaultOptions, options);

  // Extend the default HTTP request options
  options.requestOptions = Object.assign({}, defaultOptions.requestOptions, options.requestOptions || {});

  // Optionally filter by rule categories
  if (Array.isArray(options.restrictCategories) && options.restrictCategories.length > 0) {
    filteredRules = rules.filter(r => {
      if (!r.category || !Array.isArray(r.category)) {
        return false;
      }

      for (var i = 0; i < r.category.length; i++) {
        if (options.restrictCategories.includes(r.category[i])) {
          return true;
        }
      }

      return false;
    });
  }

  // Optionally filter the rules within restricted array
  if (Array.isArray(options.restrict) && options.restrict.length > 0) {
    filteredRules = utils.filterRules(options.restrict);
  }

  // Run the social scanner for each url
  async.map(filteredRules, (rule, cb) => {
    let input = username;

    // Optionally apply rule filters for input value
    if (rule.filters && Array.isArray(rule.filters)) {
      rule.filters.forEach(f => {
        input = f(username);
      });
    }

    // #8 Support for multiple url in rules
    if (Array.isArray(rule.url)) {
      async.map(rule.url, (url, callback) => {
        let address = util.format(url, input);
        execute(address, rule, options)
          .then(body => callback(null, {
            address: address,
            error: false,
            body: body
          }))
          .catch(err => callback(null, {
            address: address,
            error: err
          }));
      }, (err, results) => {
        cb(err, {
          name: rule.name,
          category: rule.category,
          value: input,
          address: results.map(r => r.address),
          error: results.some(r => r.error) &&
            results.map(r => r.error).filter(r => r),
          body: options.capture && results.map(r => r.body)
        });
      });
    } else {
      let address = util.format(rule.url, input);
      execute(address, rule, options)
        .then(body => cb(null, {
          name: rule.name,
          category: rule.category,
          value: input,
          address: address,
          error: false,
          body: options.capture && body
        }))
        .catch(err => cb(null, {
          address: address,
          error: err
        }));
    }
  }, (err, results) => {
    if (options.onlySuccess) {
      results = results.filter(r => !r.error);
    }

    callback(err, results);
  });
};


text:
namespace synth {

Controller::Controller()
    : key_frequency_(0.0f),
      arpeggio_enabled_(false),
      arpeggio_(&key_stack_),
      key_lag_processor_(&arpeggio_),
      combined_osc_(&osc1_, &osc2_, &key_lag_processor_),
      osc_sync_(false),
      modulation_source_(LFO_SRC_SQUARE),
      modulation_destination_(LFO_DEST_WAVE),
      modulation_frequency_(0.0f),
      modulation_amount_(0.0f) {
  modulation_osc_.set_frequency(&modulation_frequency_);
  modulation_.set_oscillator(&modulation_osc_);
  modulation_.set_level(&modulation_amount_);

  lowpass_filter_.set_cutoff(&filter_cutoff_);
  resonant_filter_.set_cutoff(&filter_cutoff_);

  reset_routing();
}

void Controller::set_volume(float volume) {
  volume_.set_level(volume);
}

void Controller::set_sample_rate(float sample_rate) {
  osc1_.set_sample_rate(sample_rate);
  osc2_.set_sample_rate(sample_rate);
}

void Controller::NoteOn(int note) {
  assert(note >= 1);
  assert(note <= 88);
  key_stack_.NoteOn(note);
  if (key_stack_.size() == 1) {
    // This is the first note played, so start attacking
    key_lag_processor_.reset();
    arpeggio_.reset();
    volume_envelope()->NoteOn();
    filter_envelope()->NoteOn();
  }
  float frequency = KeyToFrequency(key_stack_.GetCurrentNote());
  key_frequency_.set_value(frequency);
}

void Controller::NoteOnFrequency(float frequency) {
  key_frequency_.set_value(frequency);
  volume_envelope()->NoteOn();
  filter_envelope()->NoteOn();
}

void Controller::NoteOff(int note) {
  key_stack_.NoteOff(note);
  if (key_stack_.size() == 0) {
    // All notes were release, so start the release phase of the envelope
    NoteOff();
  } else {
    // There are still notes on key stack -- switch!
    float frequency = KeyToFrequency(key_stack_.GetCurrentNote());
    key_frequency_.set_value(frequency);
  }
}

void Controller::NoteOff() {
  key_stack_.clear();
  volume_envelope()->NoteOff();
  filter_envelope()->NoteOff();
}

void Controller::set_osc1_level(float level) {
  combined_osc_.set_osc1_level(level);
}

void Controller::set_osc1_wave_type(Oscillator::WaveType wave_type) {
  osc1_.set_wave_type(wave_type);
}

void Controller::set_osc1_octave(OctaveShift octave) {
  combined_osc_.set_osc1_octave((int)octave);
}

void Controller::set_osc2_level(float level) {
  combined_osc_.set_osc2_level(level);
}

void Controller::set_osc2_wave_type(Oscillator::WaveType wave_type) {
  osc2_.set_wave_type(wave_type);
}

void Controller::set_osc2_octave(OctaveShift octave) {
  combined_osc_.set_osc2_octave((int)octave);
}

void Controller::set_osc2_shift(int cents) {
  combined_osc_.set_osc2_shift(cents);
}

void Controller::set_osc_sync(bool sync) {
  combined_osc_.set_osc_sync(sync);
}

void Controller::set_glide_samples(long samples) {
  key_lag_processor_.set_samples(samples);
}

void Controller::set_arpeggio_enabled(bool enabled) {
  arpeggio_enabled_ = enabled;
  reset_routing();
}

void Controller::set_arpeggio_samples(long samples) {
  arpeggio_.set_samples_per_note(samples);
}

void Controller::set_arpeggio_octaves(int octaves) {
  arpeggio_.set_octaves(octaves);
}

void Controller::set_arpeggio_step(Arpeggio::Step step) {
  arpeggio_.set_step(step);
}

void Controller::set_modulation_amount(float amount) {
  modulation_amount_.set_value(amount);
}

void Controller::set_modulation_frequency(float frequency) {
  modulation_frequency_.set_value(frequency);
}

void Controller::set_modulation_source(ModulationSource src) {
  modulation_source_ = src;
  reset_routing();
}

void Controller::set_modulation_destination(ModulationDestination dest) {
  modulation_destination_ = dest;
  reset_routing();
}

void Controller::reset_routing() {
  switch (modulation_source_) {
    case LFO_SRC_SQUARE:
      modulation_osc_.set_wave_type(Oscillator::SQUARE);
      break;
    case LFO_SRC_TRIANGLE:
      modulation_osc_.set_wave_type(Oscillator::TRIANGLE);
      break;
    case LFO_SRC_SAWTOOTH:
      modulation_osc_.set_wave_type(Oscillator::SAWTOOTH);
      break;
    case LFO_SRC_REVERSE_SAWTOOTH:
      modulation_osc_.set_wave_type(Oscillator::REVERSE_SAWTOOTH);
      break;
    default:
      assert(false);
  }

  // Reset the destinations
  volume_.set_modulation(NULL);
  filter_cutoff_.set_modulation(NULL);
  combined_osc_.set_frequency_modulation(NULL);

  // Route modulation into the correct pipeline
  switch (modulation_destination_) {
    case LFO_DEST_WAVE:
      // Modulate the volume (tremelo)
      volume_.set_modulation(&modulation_);
      break;
    case LFO_DEST_PITCH:
      // Modulate the frequency (vibrato)
      combined_osc_.set_frequency_modulation(&modulation_);
      break;
    case LFO_DEST_FILTER:
      // Modulate the cutoff frequency
      filter_cutoff_.set_modulation(&modulation_);
      break;
    default:
      assert(false);
  }

  if (arpeggio_enabled_) {
    key_lag_processor_.set_param(&arpeggio_);
  } else {
    key_lag_processor_.set_param(&key_frequency_);
  }
}

void Controller::set_filter_cutoff(float frequency) {
  filter_cutoff_.set_cutoff(frequency);
}

void Controller::set_filter_resonance(float value) {
  resonant_filter_.set_resonance(value);
}

void Controller::GetFloatSamples(float* buffer, int size) {
  for (int i = 0; i < size; ++i) {
    buffer[i] = GetSample();
  }
}

float Controller::GetSample() {
  if (volume_envelope()->released() || filter_envelope()->released()) {
    return 0;
  }

  // Combined oscillators, volume/envelope/modulation
  float value = combined_osc_.GetValue();
  // Clip!
  value = fmaxf(-1.0f, value);
  value = fminf(1.0f, value);
  // Combined filter with envelope/modulation
  value = lowpass_filter_.GetValue(value);
  value = resonant_filter_.GetValue(value);
  // Clip!
  value = fmaxf(-1.0f, value);
  value = fminf(1.0f, value);
  // Adjust volume
  value *= volume_.GetValue();
  return value;
}

Volume::Volume() : level_(1.0f),
                   modulation_(NULL) { }

Volume::~Volume() { }

float Volume::GetValue() {
  float value = level_ * envelope_.GetValue();
  if (modulation_) {
    value *= modulation_->GetValue();
  }
  return value;
}

}  // namespace synth


text:
local vars = {}

-- Default modkey.
-- Usually, Mod4 is the key with a logo between Control and Alt.
-- If you do not like this or do not have such a key,
-- I suggest you to remap Mod4 to another key using xmodmap or other tools.
-- However, you can use another modifier like Mod1, but it may interact with others.
vars.modkey = "Mod4"

-- Names for the workspaces
vars.tag_names = {
    "main",
    "edit",
    "www",
    "log",
    "email",
    "im",
    "gimp",
    "office",
    "misc"
}

vars.num_tags = #vars.tag_names

return vars


text:
using namespace std;

class ELUupdateOutput_functor : public HasOperator1, public HasOperator2, public HasScalars {
public:
  int getNumScalars() const { return 1; }
  float getScalar(int index) const { return alpha_; }

  const float alpha_;

  ELUupdateOutput_functor(float alpha) : alpha_(alpha) {}

  std::string operator1() const {
    return "*out = *out <= 0 ? (exp(*out)-1) * val1 : *out";
  }
  std::string operator2() const {
    return "*out = *in1 <= 0 ? (exp(*in1)-1) * val1 : *in1";
  }
};

void THNN_ClELU_updateOutput(THClState *state, THClTensor *input, THClTensor *output, float alpha, bool inplace)
{
  THAssert(THClTensor_checkGPU(state, 2, input, output));
  if(inplace) {
    THError("inplace should be false for now, in ELU.  If you need inplace true, please raise an issue");
  }
  THClTensor_resizeAs(state, output, input);
  ELUupdateOutput_functor func(alpha);
  THClTensor_pointwiseApply2(state, output, input, &func);
}

class ELUupdateGradInput_functor : public HasOperator2, public HasOperator3, public HasScalars
{
public:
  int getNumScalars() const { return 1; }
  float getScalar(int index) const { return alpha_; }

  const float alpha_;

  ELUupdateGradInput_functor(float alpha) : alpha_(alpha) {}

  std::string operator2() const {
    return "*out = (*out) <= 0 ? (*in1 * (*out + val1)) : (*in1)";
  }
  std::string operator3() const {
    return "*out = (*in1) <= 0 ? (*in2 * (*in1 + val1)) : (*in2)";
  }
};

void THNN_ClELU_updateGradInput(THClState *state, THClTensor *input, THClTensor *gradOutput,
  THClTensor *gradInput, THClTensor *output, float alpha, bool inplace)
{
  THAssert(THClTensor_checkGPU(state, 3, output, gradOutput, gradInput));
  if(inplace) {
    THError("inplace should be false for now, in ELU.  If you need inplace true, please raise an issue");
  }
  THClTensor_resizeAs(state, gradInput, output);
  ELUupdateGradInput_functor func(alpha);
  THClTensor_pointwiseApply3(state, gradInput, output, gradOutput, &func);
}


text:
wordpress_id: 279
title: Welcome again
wordpress_url: http://spaetzel.com/PermaLink,guid,483.aspx
layout: post
---
This is the future of Redune. What do you think? Is it great?