text:
@interface CKRadialMenu()

@property (nonatomic, strong) NSMutableDictionary *poputIDs;
@property (nonatomic, strong) UIView *positionView;
@property (nonatomic, strong) UILabel *distanceLabel;
@property (nonatomic, strong) UILabel *distanceBetweenLabel;
@property (nonatomic, strong) UILabel *angleLabel;
@property (nonatomic, strong) UILabel *staggerLabel;
@property (nonatomic, strong) UILabel *animationLabel;

@end

@implementation CKRadialMenu

#pragma mark Initalizer

-(id)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    [self doInitialSetup];
    return self;
}

-(instancetype)init {
    self = [self initWithFrame:CGRectZero];
    [self doInitialSetup];
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    [self doInitialSetup];
    return self;
}

-(void)doInitialSetup {
    self.popoutViews = [NSMutableArray new];
    self.poputIDs = [NSMutableDictionary new];
    self.isMenuExpanded = false;
    self.startAngle = -75;
    self.distanceBetweenPopouts = 50;
    self.distanceFromCenter = 61;
    self.stagger = 0.06;
    self.animationDuration = 0.4;

    self.centerView = [self makeDefaultCenterView];
    self.centerView.frame = self.bounds;
    [self addSubview:self.centerView];
}

#pragma mark Setters
- (void) setCenterView:(UIView *) centerView {
    if (!centerView) {
        centerView = [self makeDefaultCenterView];
    }
    _centerView = centerView;

    UIGestureRecognizer *tap = [UITapGestureRecognizer new];
    [tap addTarget:self action:@selector(didTapCenterView:)];
    [self.centerView addGestureRecognizer:tap];
}

-(void)setFrame:(CGRect)frame{
    [super setFrame:frame];
    self.centerView.frame = self.bounds;

}

-(void) setGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer {
    _gestureRecognizer = gestureRecognizer;

    for (UIGestureRecognizer *gesture in self.centerView.gestureRecognizers) {
        [self.centerView removeGestureRecognizer:gesture];
    }

    [self.centerView addGestureRecognizer:_gestureRecognizer];
}

-(void) setMenuBackgroundColor:(UIColor *) menuBackgroundColor {
    _menuBackgroundColor = menuBackgroundColor;

    self.centerView.backgroundColor = _menuBackgroundColor;
    //TODO: add menubackground color to
}

-(void) setHasShadow:(BOOL)hasShadow {
    _hasShadow = hasShadow;

    if (_hasShadow)
        [self addShadowToCenterView];
}

#pragma mark Gesture Recognizers
- (void) didTapCenterView: (UITapGestureRecognizer *) sender {
    if (self.isMenuExpanded) {
        [self retract];
    }

    else {
        [self expand];
    }
}

- (void) expand {
    if (![self.delegate respondsToSelector:@selector(radialMenuShouldExpand:)] || [self.delegate radialMenuShouldExpand:self]) {
        NSInteger i = 0;
        for (UIView *subView in self.popoutViews) {
            subView.alpha = 0;
            [UIView animateWithDuration:self.animationDuration
                                  delay:self.stagger*i
                 usingSpringWithDamping:0.7
                  initialSpringVelocity:0.4
                                options:UIViewAnimationOptionAllowUserInteraction animations:^{
                                    subView.alpha = 1;
                                    subView.transform = [self getTransformForPopupViewAtIndex:i];
                                } completion:^(BOOL finished) {
                                    if ([self.delegate respondsToSelector:@selector(radialMenuDidExpand:)]) {
                                        [self.delegate radialMenuDidExpand:self];
                                    }
                                }];
            i++;
        }
        self.isMenuExpanded = true;
    }
}

- (void) retract {
    if (![self.delegate respondsToSelector:@selector(radialMenuShouldRetract:)] || [self.delegate radialMenuShouldRetract:self]) {
        NSInteger i = 0;
        for (UIView *subView in self.popoutViews) {

            [UIView animateWithDuration:self.animationDuration
                                  delay:self.stagger*i
                 usingSpringWithDamping:0.7
                  initialSpringVelocity:0.4
                                options:UIViewAnimationOptionAllowUserInteraction animations:^{
                                    subView.transform = CGAffineTransformIdentity;
                                    subView.alpha = 0;
                                } completion:^(BOOL finished) {
                                    if ([self.delegate respondsToSelector:@selector(radialMenuDidRetract:)]) {
                                        [self.delegate radialMenuDidRetract:self];
                                    }
                                }];
            i++;
        }
        self.isMenuExpanded = false;
    }
}

- (void) didTapPopoutView: (UITapGestureRecognizer *) sender {
    UIView *view = sender.view;
    NSString * key = [self.poputIDs allKeysForObject:view][0];
    [self.delegate radialMenu:self didSelectPopoutWithIndentifier:key];
}

#pragma mark Popout Views

- (void) addPopoutView: (UIView *) popoutView withIndentifier: (NSString *) identifier {
    if (!popoutView){
        popoutView = [self makeDefaultPopupView];
    }
    [self.popoutViews addObject:popoutView];
    [self.poputIDs setObject:popoutView forKey:identifier];
    UIGestureRecognizer *tap = [UITapGestureRecognizer new];
    [tap addTarget:self action:@selector(didTapPopoutView:)];
    [popoutView addGestureRecognizer:tap];
    popoutView.alpha = 0;
    [self addSubview:popoutView];
    [self sendSubviewToBack:popoutView];
    popoutView.center = CGPointMake(self.bounds.origin.x + self.bounds.size.width/2,self.bounds.origin.y + self.bounds.size.height/2);
}

-(UIView *)getPopoutViewWithIndentifier:(NSString *)identifier {

    return [self.poputIDs objectForKey:identifier];

}

#pragma mark Make Default Views

- (UIView *) makeDefaultCenterView {
    UIView *view = [UIView new];
    view.layer.cornerRadius = self.frame.size.width/2;
    view.backgroundColor = [UIColor redColor];

    return view;
}

- (UIView *) makeDefaultPopupView {
    UIView *view = [UIView new];
    view.frame = CGRectMake(0, 0, self.frame.size.width/1.5, self.frame.size.height / 1.5);
    view.layer.cornerRadius = view.frame.size.width/2;
    view.backgroundColor = [UIColor blueColor];
    view.layer.shadowColor = [[UIColor blackColor] CGColor];
    view.layer.shadowOpacity = 0.6;
    view.layer.shadowRadius = 3.0;
    view.layer.shadowOffset = CGSizeMake(0, 3);
    return view;
}

#pragma mark Helper Methods

-(void) addShadowToCenterView {
    self.centerView.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.centerView.layer.shadowOpacity = 0.6;
    self.centerView.layer.shadowRadius = 2.0;
    self.centerView.layer.shadowOffset = CGSizeMake(0, 3);
}

- (CGAffineTransform) getTransformForPopupViewAtIndex: (NSInteger) index {
    CGFloat newAngle = self.startAngle + (self.distanceBetweenPopouts * index);
    CGFloat deltaY = -self.distanceFromCenter * cos(newAngle/ 180.0 * M_PI);
    CGFloat deltaX = self.distanceFromCenter * sin(newAngle/ 180.0 * M_PI);
    return CGAffineTransformMakeTranslation(deltaX, deltaY);

}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    if (CGRectContainsPoint(self.bounds, point)) {
        return true;
    }
    for (UIView *subView in self.popoutViews) {
        if (CGRectContainsPoint(subView.frame, point)) {
            return true;
        }
    }
    return false;
}

- (void) enableDevelopmentMode {

    UIView *positionView = [UIView new];
    CGRect screenRect = [UIScreen mainScreen].bounds;
    positionView.frame = CGRectMake(screenRect.origin.x, screenRect.origin.y, screenRect.size.width,110);
    [[[[UIApplication sharedApplication] delegate] window] addSubview:positionView];
    [[[[UIApplication sharedApplication] delegate] window] bringSubviewToFront:positionView];

    self.distanceLabel = [UILabel new];
    self.distanceLabel.frame = CGRectMake(10, 20, 300, 20);
    [positionView addSubview:self.distanceLabel];
    self.distanceLabel.text = [NSString stringWithFormat:@"Distance From Center: %.02f", self.distanceFromCenter];
    self.distanceLabel.font = [UIFont fontWithName:@"Avenir" size:16];

    self.angleLabel = [UILabel new];
    self.angleLabel.frame = CGRectMake(10, 40, 300, 20);
    [positionView addSubview:self.angleLabel];
    self.angleLabel.text = [NSString stringWithFormat:@"Start Angle: %.02f", self.startAngle];
    self.angleLabel.font = [UIFont fontWithName:@"Avenir" size:16];

    self.distanceBetweenLabel = [UILabel new];
    self.distanceBetweenLabel.frame = CGRectMake(10, 60, 200, 20);
    [positionView addSubview:self.distanceBetweenLabel];
    self.distanceBetweenLabel.text = [NSString stringWithFormat:@"Distance Between: %.02f", self.distanceBetweenPopouts];
    self.distanceBetweenLabel.font = [UIFont fontWithName:@"Avenir" size:16];
    UISlider *distanceSlider = [UISlider new];
    distanceSlider.frame = CGRectMake(200, 60, screenRect.size.width - 225, 20);
    [positionView addSubview:distanceSlider];
    distanceSlider.maximumValue = 180;
    distanceSlider.minimumValue = 0;
    distanceSlider.value = self.distanceBetweenPopouts;
    [distanceSlider addTarget:self action:@selector(distanceSliderChanged:) forControlEvents:UIControlEventValueChanged];

    self.staggerLabel = [UILabel new];
    self.staggerLabel.frame = CGRectMake(10, 100, 200, 20);
    [positionView addSubview:self.staggerLabel];
    self.staggerLabel.text = [NSString stringWithFormat:@"Stagger in Seconds: %.02f", self.stagger];
    self.staggerLabel.font = [UIFont fontWithName:@"Avenir" size:16];
    UISlider *staggerSlider = [UISlider new];
    staggerSlider.frame = CGRectMake(200, 100, screenRect.size.width - 225, 20);
    [positionView addSubview:staggerSlider];
    staggerSlider.maximumValue = 1;
    staggerSlider.minimumValue = 0;
    staggerSlider.value = self.stagger;
    [staggerSlider addTarget:self action:@selector(staggerSliderChanged:) forControlEvents:UIControlEventValueChanged];

    for (UIView *subView in self.popoutViews) {
        //[subView removeGestureRecognizer:[subView gestureRecognizers][0]];
        UIPanGestureRecognizer *panner = [UIPanGestureRecognizer new];
        [panner addTarget:self action:@selector(didPanPopout:)];
        [subView addGestureRecognizer:panner];
    }

}

-(void) didPanPopout:(UIPanGestureRecognizer *)sender {
    UIView *view = sender.view;
    NSInteger i = [self.popoutViews indexOfObject:view];
    CGPoint point = [sender locationInView:self];
    CGFloat centerX = self.bounds.origin.x + self.bounds.size.width/2;
    CGFloat centerY = self.bounds.origin.y + self.bounds.size.height/2;
    if (sender.state == UIGestureRecognizerStateChanged) {

        // Do Calculations
        CGFloat deltaX = point.x - centerX;
        CGFloat deltaY = point.y - centerY;
        CGFloat angle = atan2(deltaX, -deltaY) * 180.0 / M_PI ;
        CGFloat distanceFromCenter = sqrt(pow(point.x - centerX, 2) + pow(point.y - centerY, 2));

        // Assign Results
        self.distanceFromCenter = distanceFromCenter;
        self.startAngle = angle - self.distanceBetweenPopouts * i;

        // Change Labels
        self.distanceLabel.text = [NSString stringWithFormat:@"Distance From Center: %.02f", self.distanceFromCenter];
        self.angleLabel.text = [NSString stringWithFormat:@"Start Angle: %.02f", self.startAngle];

        // Change Position of Views
        view.center = point;
        view.transform = CGAffineTransformIdentity;

        NSInteger i = 0;
        for (UIView *subView in self.popoutViews) {
            if (subView != view) {
                subView.transform = [self getTransformForPopupViewAtIndex:i];
            }
            i++;
        }

    } else if (sender.state == UIGestureRecognizerStateEnded) {
        view.center = CGPointMake(centerX, centerY);
        NSInteger i = 0;
        for (UIView *subView in self.popoutViews) {
            subView.transform = [self getTransformForPopupViewAtIndex:i];
            i++;
        }
    }
}

- (void)distanceSliderChanged:(UISlider *)sender {

    if (!self.isMenuExpanded){
        [self expand];
    }

    self.distanceBetweenPopouts = sender.value;
    self.distanceBetweenLabel.text = [NSString stringWithFormat:@"Distance Between: %.02f", self.distanceBetweenPopouts];

    NSInteger i = 0;
    for (UIView *subView in self.popoutViews) {
        subView.transform = [self getTransformForPopupViewAtIndex:i];
        i++;
    }
}

- (void)staggerSliderChanged:(UISlider *)sender {
    self.stagger = sender.value;
    self.staggerLabel.text = [NSString stringWithFormat:@"Stagger In Seconds: %.02f", self.stagger];
}

- (void)durationSliderChanged:(UISlider *)sender {
    self.animationDuration = sender.value;
    self.animationLabel.text = [NSString stringWithFormat:@"Duration In Seconds: %.02f", self.animationDuration];
}

@end


text:
@implementation LRUCacheNode

@end

redpajama_set_name: RedPajamaGithub


text:
package com.udacity.silver.grading;

import java.util.List;

/**
 * Created by silver on 6/15/16.
 */

public class Teacher {

    private final String name;
    private List<Class> classes;

    public Teacher(String name, List<Class> classes) {
        this.name = name;
        this.classes = classes;
    }

    public String getName() {
        return name;
    }

    public List<Class> getClasses() {
        return classes;
    }

    public void setClasses(List<Class> classes) {
        this.classes = classes;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "classes=" + classes +
                '}';
    }
}


text:
<?php
namespace Payum\Offline\Tests;

use Payum\Offline\PaymentFactory;

class PaymentFactoryTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @test
     */
    public function shouldImplementPaymentFactoryInterface()
    {
        $rc = new \ReflectionClass('Payum\Offline\PaymentFactory');

        $this->assertTrue($rc->implementsInterface('Payum\Core\PaymentFactoryInterface'));
    }

    /**
     * @test
     */
    public function couldBeConstructedWithoutAnyArguments()
    {
        new PaymentFactory();
    }

    /**
     * @test
     */
    public function shouldAllowCreatePayment()
    {
        $factory = new PaymentFactory();

        $payment = $factory->create();

        $this->assertInstanceOf('Payum\Core\Payment', $payment);

        $this->assertAttributeEmpty('apis', $payment);
        $this->assertAttributeNotEmpty('actions', $payment);

        $extensions = $this->readAttribute($payment, 'extensions');
        $this->assertAttributeNotEmpty('extensions', $extensions);
    }

    /**
     * @test
     */
    public function shouldAllowCreatePaymentConfig()
    {
        $factory = new PaymentFactory();

        $config = $factory->createConfig();

        $this->assertInternalType('array', $config);
        $this->assertNotEmpty($config);
    }

    /**
     * @test
     */
    public function shouldConfigContainDefaultOptions()
    {
        $factory = new PaymentFactory();

        $config = $factory->createConfig();

        $this->assertInternalType('array', $config);

        $this->assertArrayHasKey('options.default', $config);
        $this->assertEquals(array(), $config['options.default']);
    }

    /**
     * @test
     */
    public function shouldConfigContainFactoryNameAndTitle()
    {
        $factory = new PaymentFactory();

        $config = $factory->createConfig();

        $this->assertInternalType('array', $config);

        $this->assertArrayHasKey('factory.name', $config);
        $this->assertEquals('offline', $config['factory.name']);

        $this->assertArrayHasKey('factory.title', $config);
        $this->assertEquals('Offline', $config['factory.title']);
    }
}


text:
"""This prints the state of a logical file.

* By default, prints errors on stdout.
* Optional argument --log: logs output to system log.
"""

from django.core.management.base import BaseCommand
from hs_core.models import BaseResource

def debug_resource(short_id):
    """ Debug view for resource depicts output of various integrity checking scripts """

    try:
        res = BaseResource.objects.get(short_id=short_id)
    except BaseResource.DoesNotExist:
        print("{} does not exist".format(short_id))

    resource = res.get_content_model()
    assert resource, (res, res.content_model)

    irods_issues, irods_errors = resource.check_irods_files(log_errors=False, return_errors=True)

    print("resource: {}".format(short_id))
    print("resource type: {}".format(resource.resource_type))
    print("resource creator: {} {}".format(resource.creator.first_name, resource.creator.last_name))
    print("resource irods bag modified: {}".format(str(resource.getAVU('bag_modified'))))
    print("resource irods isPublic: {}".format(str(resource.getAVU('isPublic'))))
    print("resource irods resourceType: {}".format(str(resource.getAVU('resourceType'))))
    print("resource irods quotaUserName: {}".format(str(resource.getAVU('quotaUserName'))))
    if irods_errors:
        print("iRODS errors:")
        for e in irods_issues:
            print("    {}".format(e))
    else:
        print("No iRODS errors")

    if resource.resource_type == 'CompositeResource':
        print("Resource file logical files:")
        for res_file in resource.files.all():
            if not res_file.has_logical_file:
                print("    {} logical file NOT SPECIFIED".format(res_file.short_path))
            else:
                print("    {} logical file {} is [{}]".format(res_file.short_path,
                                                              str(type(res_file.logical_file)),
                                                              str(res_file.logical_file.id)))

    # context = {
    #     'shortkey': shortkey,
    #     'creator': resource.creator,
    #     'resource': resource,
    #     'raccess': resource.raccess,
    #     'owners': resource.raccess.owners,
    #     'editors': resource.raccess.get_users_with_explicit_access(PrivilegeCodes.CHANGE),
    #     'viewers': resource.raccess.get_users_with_explicit_access(PrivilegeCodes.VIEW),
    #     'public_AVU': resource.getAVU('isPublic'),
    #     'type_AVU': resource.getAVU('resourceType'),
    #     'modified_AVU': resource.getAVU('bag_modified'),
    #     'quota_AVU': resource.getAVU('quotaUserName'),
    #     'irods_issues': irods_issues,
    #     'irods_errors': irods_errors,
    # }

class Command(BaseCommand):
    help = "Print debugging information about logical files."

    def add_arguments(self, parser):

        # a list of resource id's: none does nothing.
        parser.add_argument('resource_ids', nargs='*', type=str)

        # Named (optional) arguments
        parser.add_argument(
            '--log',
            action='store_true',  # True for presence, False for absence
            dest='log',           # value is options['log']
            help='log errors to system log',
        )

    def handle(self, *args, **options):
        if len(options['resource_ids']) > 0:  # an array of resource short_id to check.
            for rid in options['resource_ids']:
                debug_resource(rid)

            else:
                print("No resources to check.")


text:
package tiller

import (
	"sort"
)

// SortOrder is an ordering of Kinds.
type SortOrder []string

// InstallOrder is the order in which manifests should be installed (by Kind).
//
// Those occurring earlier in the list get installed before those occurring later in the list.
var InstallOrder SortOrder = []string{
	"Namespace",
	"ResourceQuota",
	"LimitRange",
	"Secret",
	"ConfigMap",
	"PersistentVolume",
	"PersistentVolumeClaim",
	"ServiceAccount",
	"ClusterRole",
	"ClusterRoleBinding",
	"Role",
	"RoleBinding",
	"Service",
	"DaemonSet",
	"Pod",
	"ReplicationController",
	"ReplicaSet",
	"Deployment",
	"StatefulSet",
	"Job",
	"CronJob",
	"Ingress",
	"APIService",
}

// UninstallOrder is the order in which manifests should be uninstalled (by Kind).
//
// Those occurring earlier in the list get uninstalled before those occurring later in the list.
var UninstallOrder SortOrder = []string{
	"APIService",
	"Ingress",
	"Service",
	"CronJob",
	"Job",
	"StatefulSet",
	"Deployment",
	"ReplicaSet",
	"ReplicationController",
	"Pod",
	"DaemonSet",
	"RoleBinding",
	"Role",
	"ClusterRoleBinding",
	"ClusterRole",
	"ServiceAccount",
	"PersistentVolumeClaim",
	"PersistentVolume",
	"ConfigMap",
	"Secret",
	"LimitRange",
	"ResourceQuota",
	"Namespace",
}

// sortByKind does an in-place sort of manifests by Kind.
//
// Results are sorted by 'ordering'
func sortByKind(manifests []manifest, ordering SortOrder) []manifest {
	ks := newKindSorter(manifests, ordering)
	sort.Sort(ks)
	return ks.manifests
}

type kindSorter struct {
	ordering  map[string]int
	manifests []manifest
}

func newKindSorter(m []manifest, s SortOrder) *kindSorter {
	o := make(map[string]int, len(s))
	for v, k := range s {
		o[k] = v
	}

	return &kindSorter{
		manifests: m,
		ordering:  o,
	}
}

func (k *kindSorter) Len() int { return len(k.manifests) }

func (k *kindSorter) Swap(i, j int) { k.manifests[i], k.manifests[j] = k.manifests[j], k.manifests[i] }

func (k *kindSorter) Less(i, j int) bool {
	a := k.manifests[i]
	b := k.manifests[j]
	first, ok := k.ordering[a.head.Kind]
	if !ok {
		// Unknown is always last
		return false
	}
	second, ok := k.ordering[b.head.Kind]
	if !ok {
		return true
	}
	return first < second
}


text:
/* Add your application specific styles here */

.bg-login-image {
	background-image: url('https://source.unsplash.com/4rDCa5hBlCs/600x800');
}

.bg-password-image {
	background-image: url('https://source.unsplash.com/4rDCa5hBlCs/600x800');
}

.bg-register-image {
	background-image: url('https://source.unsplash.com/4rDCa5hBlCs/600x800');
}


text:
#include <openspace/util/universalhelpers.h>

namespace openspace::helpers {

double shiftAndScale(double t, double start, double end) {
    ghoul_assert(
        0.0 < start && start < end && end < 1.0,
        "Values must be 0.0 < start < end < 1.0"
    );

    double tScaled = t / (end - start) - start;
    return std::max(0.0, std::min(tScaled, 1.0));
}

} // namespace openspace::helpers


text:
/* global HTMLElement */

var aframeCore = require('aframe-core');
var utils = require('../lib/utils');

var registerElement = aframeCore.registerElement.registerElement;
var stateEls = {};
var listeners = {};
var targetData = {};

var attributeBlacklist = {
  // TODO: Consider ignoring unique attributes too
  // (e.g., `class`, `id`, `name`, etc.).
  target: true
};

// State management

function addState (el, state) {
  el.addState(state);
  recordState(el, state);
}

function recordState (el, state) {
  if (state in stateEls) {
    stateEls[state].push(el);
  } else {
    stateEls[state] = [el];
  }
}

function unrecordState (el, state) {
  if (!(state in stateEls)) { return; }
  var elIdx = stateEls[state].indexOf(el);
  if (elIdx === -1) { return; }
  stateEls[state].splice(elIdx, 1);
}

function removeState (el, state) {
  el.removeState(state);
  unrecordState(el, state);
}

function hasState (el, state) {
  if (!(state in stateEls)) { return false; }
  var elIdx = stateEls[state].indexOf(el);
  return elIdx !== -1;
}

// Unique event listeners

function recordListener (el, type) {
  if (type in listeners) {
    listeners[type].push(el);
  } else {
    listeners[type] = [el];
  }
}

function hasListener (el, type) {
  if (!(type in listeners)) { return false; }
  var elIdx = listeners[type].indexOf(el);
  return elIdx !== -1;
}

function addDelegatedListener (el, type, listener, useCapture) {
  if (hasListener(el, type)) { return; }  // Add the event listener only once.
  recordListener(el, type);
  el.addEventListener(type, listener, useCapture);
}

// Target data

function recordTargetData (type, sourceEl, targetSel, attributes) {
  var key = type;
  var obj = {sourceEl: sourceEl, targetSel: targetSel, attributes: attributes};
  if (key in targetData) {
    targetData[key].push(obj);
  } else {
    targetData[key] = [obj];
  }
}

function getTargetData (type) {
  var key = type;
  return targetData[key];
}

function targetListener (e) {
  // Not to be confused with the `target` we are modifying below.
  var eventFiredOnEl = getRealNode(e.target);
  var eventType = e.type;

  var allTargetData = getTargetData(eventType, eventFiredOnEl);
  if (!allTargetData) { return; }

  allTargetData.forEach(updateTargetEl);

  function updateTargetEl (targetData) {
    var sourceEl = targetData.sourceEl;
    if (sourceEl !== eventFiredOnEl) { return; }

    var targetAttributes = targetData.attributes;
    // TODO: Support updating multiple elements later by using `$$` and iterating.
    var targetSel = targetData.targetSel;
    var targetEl = typeof targetSel === 'string' ? utils.$(targetSel) : targetSel;

    if (!targetEl) { return; }

    updateAttrs(targetEl, targetAttributes);
  }
}

function updateAttrs (targetEl, targetAttributes) {
  utils.$$(targetAttributes).forEach(function (attr) {
    if (attr.name in attributeBlacklist) { return; }

    if (attr.name === 'state') {
      var states = utils.splitString(attr.value);
      states.forEach(function (state) {
        // Set the state on this element.
        addState(targetEl, state);
        // Remove the state on the other element(s).
        stateEls[state].forEach(function (el) {
          if (el === targetEl) { return; }  // Don't remove my state!
          removeState(el, state);
        });
      });
    } else {
      targetEl.setAttribute(attr.name, attr.value);
    }
  });
}

// Synthesize events for cursor `mouseenter` and `mouseleave`

window.addEventListener('stateadded', function (e) {
  var detail = e.detail;
  var state = detail.state;
  var el = e.target;

  recordState(el, state);

  if (state === 'hovering') {
    el.emit('mouseenter');
  }
  if (state === 'hovered') {
    if (hasState(el, 'selected')) {
      removeState(el, 'hovered');
    }
  }
});

window.addEventListener('stateremoved', function (e) {
  var detail = e.detail;
  var state = detail.state;
  var el = e.target;

  unrecordState(el, state);

  if (state === 'hovering') {
    el.emit('mouseleave');
  }
});

/**
 * Returns the true node (useful for a wrapped object in a template instance).
 */
function getRealNode (el) {
  if (el.tagName.toLowerCase() === 'a-root') {
    return el.parentNode;
  }
  if (!el.previousElementSibling && !el.nextElementSibling && el.closest('a-root')) {
    return el.closest('a-root').parentNode;
  }
  return el;
}

var AEvent = registerElement(
  'a-event',
  {
    prototype: Object.create(
      HTMLElement.prototype,
      {
        attachedCallback: {
          value: function () {
            var self = this;
            var el = self.parentNode;
            if (el.isNode) {
              attach();
            } else {
              el.addEventListener('nodeready', attach);
            }

            function attach () {
              self.isAEvent = true;
              self.type = self.type || self.getAttribute('type');
              self.target = self.target || self.getAttribute('target');
              self.sceneEl = utils.$('a-scene');
              self.attachEventListener();
            }
          },
          writable: window.debug
        },

        detachedCallback: {
          value: function () {
            // TODO: Remove all event listeners.
          },
          writable: window.debug
        },

        attributeChangedCallback: {
          value: function (attr, oldVal, newVal) {
            if (oldVal === newVal) { return; }
            if (attr === 'type') {
              this.type = newVal;
            } else if (attr === 'target') {
              this.target = newVal;
            }
          },
          writable: window.debug
        },

        attachEventListener: {
          value: function () {
            var self = this;
            var sourceEl;
            var targetEl;
            var listener;

            // TODO: Land `on` PR in `aframe-core`: https://github.com/aframevr/aframe-core/pull/330

            this.sceneEl = this.sceneEl || utils.$('a-scene');

            if (self.type === 'load') {
              sourceEl = getRealNode(self.parentNode);
              targetEl = self.target ? utils.$(self.target) : sourceEl;
              listener = function (e) {
                if (e.target !== sourceEl) { return; }
                updateAttrs(targetEl, self.attributes);
              };
              if (sourceEl && sourceEl.hasLoaded) {
                listener(sourceEl);
                return;
              }
              this.sceneEl.addEventListener('load', listener);
              return;
            }

            listener = targetListener;

            // We must delegate events because the target nodes may not exist yet.
            addDelegatedListener(this.sceneEl, self.type, listener);
            sourceEl = getRealNode(self.parentNode);
            targetEl = self.target || sourceEl;
            recordTargetData(self.type, sourceEl, targetEl, self.attributes);
          },
          writable: window.debug
        }
      }
    )
  }
);

module.exports = AEvent;


text:
import { div, h1, h } from '@cycle/dom'
import QuoteHistoricalData from '../../../models/quote-historical-data'
import { chartClass } from '../../../helpers'
import { formatMoney, toFixed } from 'accounting'

const view = (state$) => state$.map(s => {
  const position = s.positions.find(p => p.instrument.symbol === s.currentInstrument)
  const quoteHistoricalData = new QuoteHistoricalData(position, '1Y')
  const absChange = quoteHistoricalData.absChange()
  const percentChange = quoteHistoricalData.percentChange()
  const quoteClass = chartClass(absChange)

  return div('.graph-container', [
    h1(`${position.instrument.name} (${position.instrument.symbol})`),
    h1(`.center.equity.${quoteClass}`,
      `${formatMoney(position.instrument.quote.last_trade_price)}`),
    div('.center', [
      h(`small.${quoteClass}`,
        `${formatMoney(absChange)} (${toFixed(percentChange, 2)}%)`)]),
    div(`.quote-${position.instrument.symbol}-chart-placeholder .chart-big`),
  ])
})

export default view


text:
<?php
namespace StandardExceptions\IOExceptions;
use StandardExceptions\Traits\ThrowIf;

/**
* Use this exception when an IO operation tries to reach a remote host that
* cannot be resolved due to DNS or IP issues.
*
* @package  Standard-Exceptions
* @author   Mathieu Dumoulin aka CrazyCodr <crazyone@crazycoders.net>
* @license  MIT
*/
class UnknownHostException extends \RuntimeException
{
    use ThrowIf;

    public function __construct($message = 'The specified resource\'s hostname could not be resolved', $code = 0, $previous = NULL)
    {
    	parent::__construct($message, $code, $previous);
    }

}


text:
require_relative '../../lib/vcenter_lib_mongodb'

# no logging output during spec tests
VcenterLibMongodb::Logging.logger.level = Logger::FATAL


text:
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) > [puppeteer](./puppeteer.md) > [Protocol](./puppeteer.protocol.md) > [Input](./puppeteer.protocol.input.md) > [EmulateTouchFromMouseEventRequest](./puppeteer.protocol.input.emulatetouchfrommouseeventrequest.md) > [x](./puppeteer.protocol.input.emulatetouchfrommouseeventrequest.x.md)

## Protocol.Input.EmulateTouchFromMouseEventRequest.x property

X coordinate of the mouse pointer in DIP.

<b>Signature:</b>

```typescript
x: integer;
```


text:
module ApiV3
  module Plugin
    class SCMPluginInfoRepresenter < BasePluginInfoRepresenter
      property :display_name

      property :scm_settings,
               skip_nil: true,
               expect_hash: true,
               inherit: false,
               class: PluggableInstanceSettings,
               decorator: PluggableInstanceSettingsRepresenter

    end
  end
end


text:
package io.druid.math.expr;

import com.google.common.base.Strings;
import io.druid.java.util.common.IAE;

/**
 */
public abstract class ExprEval<T>
{
  public static ExprEval ofLong(Number longValue)
  {
    return new LongExprEval(longValue);
  }

  public static ExprEval of(long longValue)
  {
    return new LongExprEval(longValue);
  }

  public static ExprEval ofDouble(Number doubleValue)
  {
    return new DoubleExprEval(doubleValue);
  }

  public static ExprEval of(double doubleValue)
  {
    return new DoubleExprEval(doubleValue);
  }

  public static ExprEval of(String stringValue)
  {
    return new StringExprEval(stringValue);
  }

  public static ExprEval of(boolean value, ExprType type)
  {
    switch (type) {
      case DOUBLE:
        return ExprEval.of(Evals.asDouble(value));
      case LONG:
        return ExprEval.of(Evals.asLong(value));
      case STRING:
        return ExprEval.of(String.valueOf(value));
      default:
        throw new IllegalArgumentException("invalid type " + type);
    }
  }

  public static ExprEval bestEffortOf(Object val)
  {
    if (val instanceof ExprEval) {
      return (ExprEval) val;
    }
    if (val instanceof Number) {
      if (val instanceof Float || val instanceof Double) {
        return new DoubleExprEval((Number)val);
      }
      return new LongExprEval((Number)val);
    }
    return new StringExprEval(val == null ? null : String.valueOf(val));
  }

  final T value;

  private ExprEval(T value)
  {
    this.value = value;
  }

  public abstract ExprType type();

  public Object value()
  {
    return value;
  }

  public boolean isNull()
  {
    return value == null;
  }

  public Number numericValue()
  {
    return (Number) value;
  }

  public abstract int asInt();

  public abstract long asLong();

  public abstract double asDouble();

  public String asString()
  {
    return value == null ? null : String.valueOf(value);
  }

  public abstract boolean asBoolean();

  public abstract ExprEval castTo(ExprType castTo);

  public abstract Expr toExpr();

  private static abstract class NumericExprEval extends ExprEval<Number> {

    private NumericExprEval(Number value)
    {
      super(value);
    }

    @Override
    public final int asInt()
    {
      return value.intValue();
    }

    @Override
    public final long asLong()
    {
      return value.longValue();
    }

    @Override
    public final double asDouble()
    {
      return value.doubleValue();
    }
  }

  private static class DoubleExprEval extends NumericExprEval
  {
    private DoubleExprEval(Number value)
    {
      super(value);
    }

    @Override
    public final ExprType type()
    {
      return ExprType.DOUBLE;
    }

    @Override
    public final boolean asBoolean()
    {
      return Evals.asBoolean(asDouble());
    }

    @Override
    public final ExprEval castTo(ExprType castTo)
    {
      switch (castTo) {
        case DOUBLE:
          return this;
        case LONG:
          return ExprEval.of(asLong());
        case STRING:
          return ExprEval.of(asString());
      }
      throw new IAE("invalid type " + castTo);
    }

    @Override
    public Expr toExpr()
    {
      return new DoubleExpr(value == null ? null : value.doubleValue());
    }
  }

  private static class LongExprEval extends NumericExprEval
  {
    private LongExprEval(Number value)
    {
      super(value);
    }

    @Override
    public final ExprType type()
    {
      return ExprType.LONG;
    }

    @Override
    public final boolean asBoolean()
    {
      return Evals.asBoolean(asLong());
    }

    @Override
    public final ExprEval castTo(ExprType castTo)
    {
      switch (castTo) {
        case DOUBLE:
          return ExprEval.of(asDouble());
        case LONG:
          return this;
        case STRING:
          return ExprEval.of(asString());
      }
      throw new IAE("invalid type " + castTo);
    }

    @Override
    public Expr toExpr()
    {
      return new LongExpr(value == null ? null : value.longValue());
    }
  }

  private static class StringExprEval extends ExprEval<String>
  {
    private StringExprEval(String value)
    {
      super(value);
    }

    @Override
    public final ExprType type()
    {
      return ExprType.STRING;
    }

    @Override
    public final boolean isNull()
    {
      return Strings.isNullOrEmpty(value);
    }

    @Override
    public final int asInt()
    {
      return Integer.parseInt(value);
    }

    @Override
    public final long asLong()
    {
      return Long.parseLong(value);
    }

    @Override
    public final double asDouble()
    {
      return Double.parseDouble(value);
    }

    @Override
    public final boolean asBoolean()
    {
      return Evals.asBoolean(value);
    }

    @Override
    public final ExprEval castTo(ExprType castTo)
    {
      switch (castTo) {
        case DOUBLE:
          return ExprEval.of(asDouble());
        case LONG:
          return ExprEval.of(asLong());
        case STRING:
          return this;
      }
      throw new IAE("invalid type " + castTo);
    }

    @Override
    public Expr toExpr()
    {
      return new StringExpr(value);
    }
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace AgoWeb.Views.Celula
{
    public partial class CalcularNotas : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CarregarDDLMes();
                CarregarGrid(new WsAgo.AvaliacaoCelula { Mes = new WsAgo.Mes { ID = Convert.ToInt32(ddlMeses.SelectedValue) } });
            }
        }

        private void CarregarDDLMes()
        {
            try
            {
                AgoWeb.WsAgo.ServiceAgo serv = new AgoWeb.WsAgo.ServiceAgo();
                ddlMeses.DataSource = serv.ObterMeses();
                ddlMeses.DataTextField = "Nome";
                ddlMeses.DataValueField = "ID";
                ddlMeses.DataBind();
                ddlMeses.SelectedIndex = 1;
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('Erro ao carregar Listagem dos meses!');", true);
            }
        }

        private void CarregarGrid(WsAgo.AvaliacaoCelula avaliacaoCelula)
        {
            try
            {
                AgoWeb.WsAgo.ServiceAgo serv = new AgoWeb.WsAgo.ServiceAgo();
                WsAgo.AvaliacaoCelula[] lista = null;
                lista = serv.ObterAvaliacoesCelulaPorMesEOuNome(avaliacaoCelula.Mes, avaliacaoCelula.Supervisao != null ? avaliacaoCelula.Supervisao.Nome : string.Empty);

                if (lista.Length > 0)
                {
                    DataTable dt = new DataTable();
                    dt.Columns.Add("ID");
                    dt.Columns.Add("Nome");
                    dt.Columns.Add("Mes");
                    dt.Columns.Add("Valor");

                    for (int i = 0; i < lista.Length; i++)
                    {
                        dt.Rows.Add(lista[i].ID, lista[i].Supervisao.Nome, lista[i].Mes.Nome, lista[i].Valor);
                    }

                    gridCelula.DataKeyNames = new string[] { "ID" };
                    gridCelula.DataSource = dt;
                    gridCelula.DataBind();
                    pnlGrid.Visible = true;
                    litNaoHaResultados.Visible = false;
                }
                else
                {
                    gridCelula.DataBind();
                    litNaoHaResultados.Visible = true;
                }
            }
            catch (Exception ex)
            {
                Session["Erro"] = ex.Message;
                Response.Redirect("~/Views/Erro.aspx");
            }
        }

        protected void gridTabletsGRE_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridCelula.PageIndex = e.NewPageIndex;
            CarregarGrid(new WsAgo.AvaliacaoCelula { Mes = new WsAgo.Mes { ID = Convert.ToInt32(ddlMeses.SelectedValue) } });
        }

        protected void btnLimpar_Click(object sender, EventArgs e)
        {
            txtNomeCelula.Text = string.Empty;
            CarregarGrid(new WsAgo.AvaliacaoCelula { Mes = new WsAgo.Mes { ID = Convert.ToInt32(ddlMeses.SelectedValue) } });
        }

        protected void btnFiltrar_Click(object sender, EventArgs e)
        {
            WsAgo.AvaliacaoCelula c = new WsAgo.AvaliacaoCelula();
            c.Supervisao = new WsAgo.Supervisao { Nome = txtNomeCelula.Text };
            c.Mes = new WsAgo.Mes { ID = Convert.ToInt32(ddlMeses.SelectedValue) };
            CarregarGrid(c);
        }

        protected void btCalcularNotas_Click(object sender, EventArgs e)
        {
            try
            {
                WsAgo.Multiplicador multiplicador = null;
                AgoWeb.WsAgo.ServiceAgo serv = new AgoWeb.WsAgo.ServiceAgo();
                var avaliacaoCelula = serv.ConsultarUmaAvaliacaoCelula(Convert.ToInt32(gridCelula.SelectedDataKey.Value));
                multiplicador = new WsAgo.Multiplicador { Supervisor = avaliacaoCelula.Supervisao };

                Calcular(multiplicador);
            }
            catch (Exception ex)
            {
                Session["Erro"] = ex.Message;
                Response.Redirect("~/Views/Erro.aspx");
            }
        }

        private void Calcular(WsAgo.Multiplicador multiplicador)
        {
            try
            {
                AgoWeb.WsAgo.ServiceAgo serv = new AgoWeb.WsAgo.ServiceAgo();
                int retorno = 0;
                if (multiplicador != null)
                {
                    retorno = serv.CalcularNotas(multiplicador, Convert.ToInt32(ddlMeses.SelectedValue));
                }
                else
                {
                    retorno = serv.CalcularTodasNotas(Convert.ToInt32(ddlMeses.SelectedValue));
                }
                if (retorno == 1)
                {
                    //CarregarGrid(new WsAgo.AvaliacaoCelula { Mes = new WsAgo.Mes { ID = Convert.ToInt32(ddlMeses.SelectedValue) } });
                    btCalcularNotas.Visible = false;
                    btCalcularNotasTodasCelulas.Visible = true;
                    gridCelula.SelectedIndex = -1;
                    //gridCelula.Columns[0].Visible = false;
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('Notas calculadas com sucesso!');", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('Erro ao calcular as notas: ');", true);
                }
            }
            catch (Exception ex)
            {
                Session["Erro"] = ex.Message;
                Response.Redirect("~/Views/Erro.aspx");
            }
        }

        protected void btCalcularNotasTodasCelulas_Click(object sender, EventArgs e)
        {
            string confirmValue = Request.Form["confirma"].Split(',').Last();
            if (confirmValue.Equals("Sim"))
            {
                try
                {
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('Notas calculadas com sucesso!');", true);
                    Calcular(null);
                }
                catch (Exception ex)
                {
                    ScriptManager.RegisterStartupScript(this, typeof(Page), "alert", "alert('Erro ao calcular as notas: '" + ex.Message + ");", true);
                }
            }
        }

        protected void gridCelula_SelectedIndexChanged(object sender, EventArgs e)
        {
            btCalcularNotas.Visible = true;
            btCalcularNotasTodasCelulas.Visible = false;
        }
    }
}


text:
import React, { FunctionComponent } from 'react'
import styled, { css } from 'styled-components'
import { DARK_BUTTON_COLOR, DARK_COLOR_2, LIGHT_BUTTON_COLOR, LIGHT_COLOR_2 } from '../../colors'
import { Theme } from '../../models/types'

interface ButtonProps {
  color?: 'red' | 'green' | 'contrast'
  isLarge?: boolean
  onClick?: () => void,
  theme?: Theme
}

const colorToCss = (color: ButtonProps['color'], theme: Theme) => {
  switch (color) {
    case 'red':
      return css`
        background-color: #f44336;
        color: #fff;

        &:hover,
        &:focus {
          background-color: #ff7961;
        }
      `
    case 'green':
      return css`
        background-color: #4caf50;
        color: #fff;

        &:hover,
        &:focus {
          background-color: #80e27e;
        }
      `
    case 'contrast':
      return css`
        background-color: ${theme === 'dark' ? DARK_COLOR_2 : LIGHT_COLOR_2};
        color: #c5830d;

        &:hover,
        &:focus {
          background-color: ${theme === 'dark' ? DARK_COLOR_2 : '#DDD'};
        }
      `
  }

  if (theme === 'dark') {
    return css`
      background-color: ${DARK_BUTTON_COLOR};
      color: ${LIGHT_BUTTON_COLOR};

      &:hover,
      &:focus {
        background-color: #212121;
      }
    `
  } else {
    return css`
      background-color: ${LIGHT_BUTTON_COLOR};
      color: ${DARK_BUTTON_COLOR};

      &:hover,
      &:focus {
        background-color: #dddddd;
      }
    `
  }

}

export const StyledButton = styled.button<ButtonProps>`
  font-family: inherit;
  font-size: inherit;
  border: 1px solid rgba(0, 0, 0, 0.05);
  border-radius: 0;
  padding-top: 1em;
  padding-bottom: 1em;
  transition: background-color 0.15s ease-in-out, opacity 0.15s ease-in-out;
  ${({ color, theme }) => colorToCss(color, theme)}
  ${({ isLarge }) =>
    isLarge &&
    css`
      grid-column-end: span 2;
    `}

  position: relative;
  overflow: hidden;
  transform: translate3d(0, 0, 0);

  &:focus {
    outline: 0;
  }

  :after {
    content: '';
    display: block;
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    pointer-events: none;
    background-image: radial-gradient(circle, #fff 10%, transparent 10.01%);
    background-repeat: no-repeat;
    background-position: 50%;
    transform: scale(10, 10);
    opacity: 0;
    transition: transform 0.3s, opacity 1s;
  }

  :active:after {
    transform: scale(0, 0);
    opacity: 0.2;
    transition: 0s;
  }
`

export const Button: FunctionComponent<ButtonProps> = ({ children, color, isLarge, onClick, theme = 'dark' }) => {
  return (
    <StyledButton color={color} theme={theme} isLarge={isLarge} onClick={onClick}>
      {children}
    </StyledButton>
  )
}

export default Button


text:
![](http://cdn.flaticon.com/png/256/33311.png)
# Gauze

Translating filtering & sorting params to AR scopes can be teadious and doesn't belong in your controllers...

Enter **Gauze**

Gauze allows you to build very simple service objects to be called from your controllers and passed the resource & params.

Read on below to see how it works.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'gauze'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install gauze

## Usage

Create a class that your controller can find.
Define filters & sorters using the Gauze DSL.

The filter method accepts 4 arguments.

`filter :param_key, :column_name, :arel_method, :preprocessor`

* `:param_key` - The key to look for when params are passed in.
* `:column_name` - The name of the column that exists on `ActiveRecord::Base.arel_table`
* `:arel_method` - The AREL method to use in the `where` stanza.
* `:preprocessor` - (Optional) Takes a block to make an changes to the value before its passed into the AREL method.

```ruby
  class EventFilters < Gauze::Base
    filter :start_range, :created_at, :gteq, -> val {Chronic.parse(val)}
    filter :end_range, :created_at, :lteq, -> val {Chronic.parse(val)}
  end
```

Then in your controller:
```ruby
  class EventsController < ActionController::Base
    def index
      @events = EventFilters.build(Event, params)
      render json: @events
    end
  end
```

The sorter method accepts 2 arguments.

`sorter :param_key, :column_name`

```ruby
  class EventFilters < Gauze::Base
    sorter :event_name, :name
  end
```

Because **Gauze** uses AREL to construct queries, you can use `.build` just like any other scope. You can pass relational objects & chain more relations as you need.
```ruby
def index
  @events = EventFilters.build(current_user.events, params).order(created_at: :desc).where(name: "Football Game")
  render json: @events
end
```

### Using Joins

It is possible to filter & sort across joined tables.

To start, you need to let **Gauze** know that you are going to make use of a join.
Simply add the `needs` method to your gauze classes.

```ruby
  class CustomerFilters < Gauze::Base
    needs :person
  end
```

This can also be a hash or array, a-la activerecord:
```ruby
  needs person: :location, orders: {transaction: :charge}
```

```ruby
  needs :person, :location
```

After you have all of your gauze needs met, you simply use a hash style syntax to filter across the join.
```ruby
  class CustomerFilters < Gauze::Base
    needs :person
    filter :name, {person: :last_name}, :matches, -> val {"%#{val}%"}
    sorter :last_name, {person: :last_name}
  end
```

## TO-DO
- [ ] Write tests.
- [ ] Add controller hooks.

## Contributing

1. Fork it ( https://github.com/TheKidCoder/gauze/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
img: https://www.gleif.org/assets/build/img/logo/gleif-logo-new.svg
title: Global Legal Entity Identifier Foundation
url: https://www.gleif.org
--- DescriptionText.md
--- AcknowledgementText.md
The implementation and use of Legal Entity Identifier (LEI) is supported by Global Legal Entity Identifier Foundation [https://www.gleif.org](https://www.gleif.org).


text:
/* @flow */
/*
Contains techniques from koa-static.
https://github.com/koajs/static
*/

import type { KoaType, KoaMiddlewareType } from "./flow/koa-types";
import type { KoaSendOptionsType } from "koa-send";
import send from "koa-send";
import path from "path";

export default function(root: string, opts?: KoaSendOptionsType = {}) : KoaMiddlewareType {
  opts.root = path.resolve(root);
  if (opts.index !== false) opts.index = opts.index || 'index.html';

  return async function(context, next) {
    if (opts.defer) {
      await next();
    }

    if (context.method !== 'HEAD' && context.method !== 'GET') return;

    // response is already handled
    if (context.body != null || context.status != 404) return;

    await send(context, context.path, opts);

    if (!opts.defer) {
      await next();
    }
  };
};


text:
package vn.edu.vnu.uet.nlp.segmenter.experiments;

import java.io.BufferedWriter;
import java.io.IOException;
import java.text.Normalizer;
import java.text.Normalizer.Form;
import java.util.ArrayList;
import java.util.List;

import vn.edu.vnu.uet.nlp.segmenter.SegmentationSystem;
import vn.edu.vnu.uet.nlp.tokenizer.Tokenizer;
import vn.edu.vnu.uet.nlp.utils.FileUtils;
import vn.edu.vnu.uet.nlp.utils.OldLogging;

/**
 * Demo: segmentation for text in file.
 *
 * @author tuanphong94
 *
 */
public class Segment {

	public static void main(String[] args) throws IOException {
		String filename = "/home/tuanphong94/workspace/TPSegmenter/raw/text.txt";

		List<String> dataLines = FileUtils.readFile(filename);

		OldLogging.info("loading model...");
		SegmentationSystem machine = null;
		try {
			machine = new SegmentationSystem("models");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		OldLogging.info("segmenting...");
		List<String> tokens = new ArrayList<String>();
		List<String> sentences = new ArrayList<String>();

		int numTokens = 0;
		int numSentences = 0;

		String outfile = filename.substring(0, filename.lastIndexOf('.')) + ".seg";
		BufferedWriter bw = FileUtils.newUTF8BufferedWriterFromNewFile(outfile);

		long start_time = System.nanoTime();
		for (String line : dataLines) {
			if (line.isEmpty() || line == null)
				continue;
			tokens = Tokenizer.tokenize(Normalizer.normalize(line, Form.NFC));
			sentences = Tokenizer.joinSentences(tokens);

			for (String sentence : sentences) {
				System.out.println(machine.segment(sentence));
				bw.write(machine.segment(sentence));
				bw.newLine();
				bw.flush();
			}

			numTokens += tokens.size();
			numSentences += sentences.size();

			tokens.clear();
			sentences.clear();
		}
		long end_time = System.nanoTime();

		bw.close();

		double difference = (end_time - start_time) / 1e9;

		OldLogging.info("Tokens: " + numTokens);
		OldLogging.info("Sentences: " + numSentences);
		OldLogging.info("Time: " + difference + " seconds");
		OldLogging.info("Rate: " + numTokens / difference + " tokens/sec");
	}

}


text:
package org.n52.sos.encode.json;

import org.n52.sos.exception.ows.NoApplicableCodeException;

/**
 * TODO JavaDoc
 *
 * @author Christian Autermann <c.autermann@52north.org>
 *
 * @since 4.0.0
 */
public class JSONEncodingException extends NoApplicableCodeException {
    public JSONEncodingException() {
    }

    public JSONEncodingException(String message) {
        withMessage(message);
    }

    public JSONEncodingException(String message, Throwable cause) {
        withMessage(message).causedBy(cause);
    }

    public JSONEncodingException(Throwable cause) {
        causedBy(cause);
    }
}


text:
<#
    .SYNOPSIS
       Add a synopsis here to explain the PSScript.

    .Description
        Give a description of the Script.

#>
Param(

)
$ErrorActionPreference = [System.Management.Automation.ActionPreference]::Stop
$CompletedParameters = Write-StartingMessage -CommandName Get-AnomalousLogin

$GlobalVars = Get-BatchAutomationVariable -Prefix 'zzGlobal' `
                                          -Name 'SubscriptionName',
                                                'SubscriptionAccessCredentialName'

$OMSVars = Get-BatchAutomationVariable -Prefix 'LogAnalytics' `
                                       -Name 'WorkspaceId',
                                             'ResourceGroupName'

$SubscriptionAccessCredential = Get-AutomationPSCredential -Name $GlobalVars.SubscriptionAccessCredentialName
$OMSCred = Get-AutomationPSCredential -Name $OMSVars.WorkspaceId
Try
{
    Connect-AzureRmAccount -Credential $SubscriptionAccessCredential `
                           -SubscriptionName $GlobalVars.SubscriptionName

    $LastSaveDate = Get-AutomationVariable -Name 'WindowsLoginGrouping-LastSaveDate'
    $CurrentDate = Get-Date
    $StdDevSearchResult = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $OMSVars.ResourceGroupName `
                                                                      -WorkspaceName $OMSVars.WorkspaceId `
                                                                      -Query 'Type=WindowsLoginAggregation_CL | measure stddev(Value_d), avg(Value_d) by Computer,Account_s,EventID_d' `
                                                                      -Start (Get-date).AddDays(-7) -End $CurrentDate -Top 5000

    $LastCount = Get-AzureRmOperationalInsightsSearchResults -ResourceGroupName $OMSVars.ResourceGroupName `
                                                                      -WorkspaceName $OMSVars.WorkspaceId `
                                                                      -Query 'Type=SecurityEvent (EventID=4625) | measure count() by Computer,Account,EventID' `
                                                                      -Start (Get-date).AddMinutes(-15) -End $CurrentDate -Top 5000
    $HT = @{}
    Foreach($Result in ($StdDevSearchResult.Value | ConvertFrom-JSON))
    {
        $HT.Add("$($Result.Account_s):$($Result.Computer):$($Result.EventID_d -as [int])", ($Result.'avg(Value_d)' + $Result.'stddev(Value_d)'))
    }

    Foreach($Result in ($LastCount.Value | ConvertFrom-JSON))
    {
        $Key = "$($Result.Account):$($Result.Computer):$($Result.EventID)"
        if($HT.ContainsKey($Key))
        {
            $Upperbound = $HT.$Key
            if($Result.AggregatedValue -gt $Upperbound)
            {
                #Block Result
                $VMName = $Result.Computer
                $VMObj = Find-AzureRmResource -ResourceNameContains $VMName -ResourceType 'Microsoft.Compute/virtualMachines'
                if($VMObj)
                {
                    $VirtualMachine = Get-AzureRmVM -ResourceGroupName $VMObj.ResourceGroupName -Name $VMObj.Name

                    Foreach($NetworkInterfaceId in $VirtualMachine.NetworkInterfaceIDs)
                    {
                        $NetworkInterface = Get-AzureRmResource -ResourceId $NetworkInterfaceId
                        Foreach($NetworkSecurityGroupId in $NetworkInterface.Properties.networkSecurityGroup)
                        {
                            $NetworkSecurityGroup = Get-AzureRMResource -ResourceId $NetworkSecurityGroupId.id
                            $NSG = Get-AzureRmNetworkSecurityGroup -Name $NetworkSecurityGroup.Name -ResourceGroupName $NetworkSecurityGroup.ResourceGroupName
                            $NSG | Add-AzureRmNetworkSecurityRuleConfig -Name "BlockIPAddress" `
                                                                        -Protocol * `
                                                                        -SourcePortRange * `
                                                                        -DestinationPortRange * `
                                                                        -SourceAddressPrefix 40.78.108.1 `
                                                                        -DestinationAddressPrefix * `
                                                                        -Priority 998 `
                                                                        -Access Deny `
                                                                        -Direction Inbound
                            $nsg | Set-AzureRmNetworkSecurityGroup
                        }
                    }#>
                }
            }
        }

    }
    if($SearchResult.Value.Count -gt 0)
    {
        Write-LogAnalyticsLogEntry -WorkspaceId $OMSVars.WorkspaceId `
                                   -Key $OMSCred.GetNetworkCredential().Password `
                                   -Data ($SearchResult.Value | ConvertFrom-Json) `
                                   -LogType 'WindowsLogin_CL' `
                                   -TimeStampField 'TimeGenerated'
    }

    Set-AutomationVariable -Name 'WindowsLoginGrouping-LastSaveDate' -Value $CurrentDate
}
Catch
{
    $Exception = $_
    $ExceptionInfo = Get-ExceptionInfo -Exception $Exception
    Switch ($ExceptionInfo.FullyQualifiedErrorId)
    {
        Default
        {
            Write-Exception $Exception -Stream Warning
        }
    }
}

Write-CompletedMessage @CompletedParameters


text:
require('./example/playlist')
require('./another_example/playlist')


text:
#Mel_Links img{
  height: 50px; /*Size of the images*/

}

#Mel_Links li{
  float: right;
  display: inline-block; /*This makes the list horizontal rather than vertical with bullet points*/
  position: relative;
  padding: 10px;  /*This is how much space is in between each list item, but I don't understand how it is different than the padding for Mel_Links a */
}

.flower{
	height: 300px;
	margin: 8em auto 5em;
	border: 150px;
	text-align: center;
	width: 900px;
	position: relative;

}

body{
	background: url("Pics/stripes.png");
	margin:0;
	padding: 0;
}

h3 a{
	color: #F9CFF2;
	font-family: 'pacienciaregular';
	font-size: 30px;
	letter-spacing: 10px;
	text-decoration: none;
}

footer{
  height: 70px;
  padding: 20px 10px;
  width:100%;
  margin-bottom: 20px;
}

footer ul{
  margin-right: 10px;

}


text:
<LANG>_INCLUDE_WHAT_YOU_USE
---------------------------

This property is implemented only when ``<LANG>`` is ``C`` or ``CXX``.

Specify a :ref:`;-list <CMake Language Lists>` containing a command
line for the ``include-what-you-use`` tool.  The :ref:`Makefile Generators`
and the :generator:`Ninja` generator will run this tool along with the
compiler and report a warning if the tool reports any problems.

This property is initialized by the value of
the :variable:`CMAKE_<LANG>_INCLUDE_WHAT_YOU_USE` variable if it is set
when a target is created.


text:
require 'spec_helper'

describe SirenCall::Entity do
  let(:hash) do
    {
      "class" => [ "order" ],
      "properties" => {
          "orderNumber" => 42,
          "itemCount" => 3,
          "status" => "pending"
      },
      "entities" => [
        {
          "class" => [ "items", "collection" ],
          "rel" => [ "http://x.io/rels/order-items" ],
          "href" => "http://api.x.io/orders/42/items"
        },
        {
          "class" => [ "info", "customer" ],
          "rel" => [ "http://x.io/rels/customer" ],
          "properties" => {
            "customerId" => "pj123",
            "name" => "Peter Joseph"
          },
          "links" => [
            { "rel" => [ "self" ], "href" => "http://api.x.io/customers/pj123" }
          ]
        }
      ]
    }
  end

  describe ".parse" do
    context "passing a basic entity" do

      it "loads in the class" do
        expect(described_class.parse(hash).classes).to eql ["order"]
      end

      it "loads in the properties" do
        expect(described_class.parse(hash).properties).to eql("orderNumber" => 42, "itemCount" => 3, "status" => "pending")
      end

      it "loads in the entities" do
        expect(described_class.parse(hash).entities).to have(2).entities
      end
    end
  end

  describe "#entities_by_class" do
    subject(:entity) { described_class.parse(hash) }

    it "finds the items class" do
      expect(entity.entities_by_class("items")).to have(1).entity
    end

    it "returns empty array when nothing found" do
      expect(entity.entities_by_class("item")).to have(0).entities
    end
  end
end


text:
package org.apache.tajo.engine.planner.physical;

import org.apache.hadoop.fs.Path;
import org.apache.tajo.LocalTajoTestingUtility;
import org.apache.tajo.TajoTestingCluster;
import org.apache.tajo.storage.fragment.FileFragment;
import org.apache.tajo.worker.TaskAttemptContext;
import org.apache.tajo.algebra.Expr;
import org.apache.tajo.catalog.*;
import org.apache.tajo.catalog.proto.CatalogProtos.StoreType;
import org.apache.tajo.common.TajoDataTypes.Type;
import org.apache.tajo.conf.TajoConf;
import org.apache.tajo.datum.Datum;
import org.apache.tajo.datum.DatumFactory;
import org.apache.tajo.engine.parser.SQLAnalyzer;
import org.apache.tajo.engine.planner.*;
import org.apache.tajo.engine.planner.enforce.Enforcer;
import org.apache.tajo.engine.planner.logical.LogicalNode;
import org.apache.tajo.storage.*;
import org.apache.tajo.util.CommonTestingUtil;
import org.apache.tajo.util.TUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

public class TestHashSemiJoinExec {
  private TajoConf conf;
  private final String TEST_PATH = "target/test-data/TestHashJoinExec";
  private TajoTestingCluster util;
  private CatalogService catalog;
  private SQLAnalyzer analyzer;
  private LogicalPlanner planner;
  private LogicalOptimizer optimizer;
  private AbstractStorageManager sm;
  private Path testDir;

  private TableDesc employee;
  private TableDesc people;

  @Before
  public void setUp() throws Exception {
    util = new TajoTestingCluster();
    util.initTestDir();
    catalog = util.startCatalogCluster().getCatalog();
    testDir = CommonTestingUtil.getTestDir(TEST_PATH);
    conf = util.getConfiguration();
    sm = StorageManagerFactory.getStorageManager(conf, testDir);

    Schema employeeSchema = new Schema();
    employeeSchema.addColumn("managerId", Type.INT4);
    employeeSchema.addColumn("empId", Type.INT4);
    employeeSchema.addColumn("memId", Type.INT4);
    employeeSchema.addColumn("deptName", Type.TEXT);

    TableMeta employeeMeta = CatalogUtil.newTableMeta(StoreType.CSV);
    Path employeePath = new Path(testDir, "employee.csv");
    Appender appender = StorageManagerFactory.getStorageManager(conf).getAppender(employeeMeta, employeeSchema,
        employeePath);
    appender.init();
    Tuple tuple = new VTuple(employeeSchema.getColumnNum());

    for (int i = 0; i < 10; i++) {
      tuple.put(new Datum[] {
          DatumFactory.createInt4(i),
          DatumFactory.createInt4(i), // empid [0-9]
          DatumFactory.createInt4(10 + i),
          DatumFactory.createText("dept_" + i) });
      appender.addTuple(tuple);
    }

    appender.flush();
    appender.close();
    employee = CatalogUtil.newTableDesc("employee", employeeSchema, employeeMeta, employeePath);
    catalog.addTable(employee);

    Schema peopleSchema = new Schema();
    peopleSchema.addColumn("empId", Type.INT4);
    peopleSchema.addColumn("fk_memId", Type.INT4);
    peopleSchema.addColumn("name", Type.TEXT);
    peopleSchema.addColumn("age", Type.INT4);
    TableMeta peopleMeta = CatalogUtil.newTableMeta(StoreType.CSV);
    Path peoplePath = new Path(testDir, "people.csv");
    appender = StorageManagerFactory.getStorageManager(conf).getAppender(peopleMeta, peopleSchema, peoplePath);
    appender.init();
    tuple = new VTuple(peopleSchema.getColumnNum());
    // make 27 tuples
    for (int i = 1; i < 10; i += 2) {
      // make three duplicated tuples for each tuples
      for (int j = 0; j < 3; j++) {
        tuple.put(new Datum[] {
            DatumFactory.createInt4(i), // empid [1, 3, 5, 7, 9]
            DatumFactory.createInt4(10 + i),
            DatumFactory.createText("name_" + i),
            DatumFactory.createInt4(30 + i) });
        appender.addTuple(tuple);
      }
    }

    appender.flush();
    appender.close();

    people = CatalogUtil.newTableDesc("people", peopleSchema, peopleMeta, peoplePath);
    catalog.addTable(people);
    analyzer = new SQLAnalyzer();
    planner = new LogicalPlanner(catalog);
    optimizer = new LogicalOptimizer(conf);
  }

  @After
  public void tearDown() throws Exception {
    util.shutdownCatalogCluster();
  }

  // relation descriptions
  // employee (managerid, empid, memid, deptname)
  // people (empid, fk_memid, name, age)

  String[] QUERIES = {
      "select managerId, e.empId, deptName, e.memId from employee as e, people as p where e.empId = p.empId"
  };

  @Test
  public final void testHashSemiJoin() throws IOException, PlanningException {
    FileFragment[] empFrags = StorageManager.splitNG(conf, "e", employee.getMeta(), employee.getPath(),
        Integer.MAX_VALUE);
    FileFragment[] peopleFrags = StorageManager.splitNG(conf, "p", people.getMeta(), people.getPath(),
        Integer.MAX_VALUE);

    FileFragment[] merged = TUtil.concat(empFrags, peopleFrags);

    Path workDir = CommonTestingUtil.getTestDir("target/test-data/testHashSemiJoin");
    TaskAttemptContext ctx = new TaskAttemptContext(conf,
        LocalTajoTestingUtility.newQueryUnitAttemptId(), merged, workDir);
    ctx.setEnforcer(new Enforcer());
    Expr expr = analyzer.parse(QUERIES[0]);
    LogicalPlan plan = planner.createPlan(expr);
    optimizer.optimize(plan);
    LogicalNode rootNode = plan.getRootBlock().getRoot();

    PhysicalPlanner phyPlanner = new PhysicalPlannerImpl(conf, sm);
    PhysicalExec exec = phyPlanner.createPlan(ctx, rootNode);

    // replace an equal join with an hash anti join.
    if (exec instanceof MergeJoinExec) {
      MergeJoinExec join = (MergeJoinExec) exec;
      ExternalSortExec sortLeftChild = (ExternalSortExec) join.getLeftChild();
      ExternalSortExec sortRightChild = (ExternalSortExec) join.getRightChild();
      SeqScanExec scanLeftChild = (SeqScanExec) sortLeftChild.getChild();
      SeqScanExec scanRightChild = (SeqScanExec) sortRightChild.getChild();

      // 'people' should be outer table. So, the below code guarantees that people becomes the outer table.
      if (scanLeftChild.getTableName().equals("people")) {
        exec = new HashLeftSemiJoinExec(ctx, join.getPlan(), scanRightChild, scanLeftChild);
      } else {
        exec = new HashLeftSemiJoinExec(ctx, join.getPlan(), scanLeftChild, scanRightChild);
      }
    } else if (exec instanceof HashJoinExec) {
      HashJoinExec join = (HashJoinExec) exec;
      SeqScanExec scanLeftChild = (SeqScanExec) join.getLeftChild();

      // 'people' should be outer table. So, the below code guarantees that people becomes the outer table.
      if (scanLeftChild.getTableName().equals("people")) {
        exec = new HashLeftSemiJoinExec(ctx, join.getPlan(), join.getRightChild(), join.getLeftChild());
      } else {
        exec = new HashLeftSemiJoinExec(ctx, join.getPlan(), join.getLeftChild(), join.getRightChild());
      }
    }

    Tuple tuple;
    int count = 0;
    int i = 1;
    exec.init();
    // expect result without duplicated tuples.
    while ((tuple = exec.next()) != null) {
      count++;
      assertTrue(i == tuple.get(0).asInt4());
      assertTrue(i == tuple.get(1).asInt4());
      assertTrue(("dept_" + i).equals(tuple.get(2).asChars()));
      assertTrue(10 + i == tuple.get(3).asInt4());

      i += 2;
    }
    exec.close();
    assertEquals(5 , count); // the expected result: [1, 3, 5, 7, 9]
  }
}


text:
class ChromeBrowserState;

namespace bookmarks {
class ManagedBookmarkService;
}

// Singleton that owns all ManagedBookmarkService and associates them with
// ChromeBrowserState.
class ManagedBookmarkServiceFactory : public BrowserStateKeyedServiceFactory {
 public:
  static bookmarks::ManagedBookmarkService* GetForBrowserState(
      ChromeBrowserState* browser_state);

  static ManagedBookmarkServiceFactory* GetInstance();

  ManagedBookmarkServiceFactory(const ManagedBookmarkServiceFactory&) = delete;
  ManagedBookmarkServiceFactory& operator=(
      const ManagedBookmarkServiceFactory&) = delete;

 private:
  friend class base::NoDestructor<ManagedBookmarkServiceFactory>;

  ManagedBookmarkServiceFactory();
  ~ManagedBookmarkServiceFactory() override;

  // BrowserStateKeyedServiceFactory implementation.
  std::unique_ptr<KeyedService> BuildServiceInstanceFor(
      web::BrowserState* context) const override;
  bool ServiceIsNULLWhileTesting() const override;
};

#endif  // IOS_CHROME_BROWSER_BOOKMARKS_MANAGED_BOOKMARK_SERVICE_FACTORY_H_


text:
target/debug/tmux_min_attacher: src/main.rs
	cargo build

target/release/tmux_min_attacher: src/main.rs
	cargo build --release

run: tmux_min_attacher
	cargo run

test:
	cargo test

clean:
	git clean -fdx

install: target/release/tmux_min_attacher
	cp $< ~/bin


text:
namespace blink {

template <class K>
class AsyncOperationMap final {
    DISALLOW_NEW_EXCEPT_PLACEMENT_NEW();
public:
    using MapType = WillBeHeapHashMap<K, int>;
    explicit AsyncOperationMap(V8DebuggerAgent* debuggerAgent)
        : m_debuggerAgent(debuggerAgent)
    {
    }

    ~AsyncOperationMap()
    {
        // Verify that this object has been explicitly disposed.
        ASSERT(hasBeenDisposed());
    }

#if ENABLE(ASSERT)
    bool hasBeenDisposed() const
    {
        return !m_debuggerAgent;
    }
#endif

    void dispose()
    {
        clear();
        m_debuggerAgent = nullptr;
    }

    void clear()
    {
        ASSERT(m_debuggerAgent);
        for (auto it : m_asyncOperations)
            m_debuggerAgent->traceAsyncOperationCompleted(it.value);
        m_asyncOperations.clear();
    }

    void set(typename MapType::KeyPeekInType key, int operationId)
    {
        m_asyncOperations.set(key, operationId);
    }

    bool contains(typename MapType::KeyPeekInType key) const
    {
        return m_asyncOperations.contains(key);
    }

    int get(typename MapType::KeyPeekInType key) const
    {
        return m_asyncOperations.get(key);
    }

    void remove(typename MapType::KeyPeekInType key)
    {
        ASSERT(m_debuggerAgent);
        int operationId = m_asyncOperations.take(key);
        if (operationId)
            m_debuggerAgent->traceAsyncOperationCompleted(operationId);
    }

    DEFINE_INLINE_TRACE()
    {
        visitor->trace(m_asyncOperations);
    }

private:
    V8DebuggerAgent* m_debuggerAgent;
    MapType m_asyncOperations;
};

} // namespace blink

#endif // AsyncOperationMap_h


text:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends CI_Controller
{
	function __construct()
	{
		parent::__construct();

		$this->load->library('form_validation');
		$this->load->helper('security');
		$this->load->library('tank_auth');
		$this->lang->load('tank_auth');

	}

	function index()
	{
		if ($message = $this->session->flashdata('message')) {
			$this->lc_global->data_output(array('auth/general_message'), array('message' => $message));
		} else {
			// redirect('/auth/login/');
			_ajax_json(array('redirect' => site_url('auth/login')));
		}
	}

	/**
	 * Login user on the site
	 *
	 * @return void
	 */
	function login()
	{
		// _show($_SESSION);
		// _show($_COOKIE);
		// die();
		if ($this->tank_auth->is_logged_in()) {									// logged in
			// redirect('');
			_ajax_json(array('redirect' => site_url('')));

		} elseif ($this->tank_auth->is_logged_in(FALSE)) {						// logged in, not activated
			// redirect('/auth/send_again/');
			_ajax_json(array('redirect' => site_url('auth/send_again')));

		} else {

			$data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND
					$this->config->item('use_username', 'tank_auth'));
			$data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');

			$this->form_validation->set_rules('login', 'Login', 'trim|required|xss_clean');
			$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
			$this->form_validation->set_rules('remember', 'Remember me', 'integer');

			// Get login for counting attempts to login
			if ($this->config->item('login_count_attempts', 'tank_auth') AND
					($login = $this->input->post('login'))) {
				$login = $this->security->xss_clean($login);
			} else {
				$login = '';
			}

			$data['use_recaptcha'] = $this->config->item('use_recaptcha', 'tank_auth');
			if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
				if ($data['use_recaptcha'])
					$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
				else
					$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
			}
			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if ($this->tank_auth->login(
						$this->form_validation->set_value('login'),
						$this->form_validation->set_value('password'),
						$this->form_validation->set_value('remember'),
						$data['login_by_username'],
						$data['login_by_email'])) {								// success
					// redirect('/auth/profile_check/');
					_ajax_json(array('redirect' => site_url('auth/profile_check')));

				} else {
					$errors = $this->tank_auth->get_error_message();
					if (isset($errors['banned'])) {								// banned user
						$this->_show_message($this->lang->line('auth_message_banned').' '.$errors['banned']);

					} elseif (isset($errors['not_activated'])) {				// not activated user
						// redirect('/auth/send_again/');
						_ajax_json(array('redirect' => site_url('auth/send_again')));

					} else {													// fail
						foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
					}
				}
			}
			$data['show_captcha'] = FALSE;
			if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
				$data['show_captcha'] = TRUE;
				if ($data['use_recaptcha']) {
					$data['recaptcha_html'] = $this->_create_recaptcha();
				} else {
					$data['captcha_html'] = $this->_create_captcha();
				}
			}
			$data['page_title'] = __('Sign In');
			$this->lc_global->data_output(array('auth/header', 'auth/login_form', 'auth/footer'), $data);

		}
	}

	/**
	 * Logout user
	 *
	 * @return void
	 */
	function logout()
	{
		$this->tank_auth->logout();

		$this->_show_message($this->lang->line('auth_message_logged_out'));
	}

	/**
	 * Register user on the site
	 *
	 * @return void
	 */
	function register()
	{
		if ($this->tank_auth->is_logged_in()) {									// logged in
			// redirect('');
			_ajax_json(array('redirect' => site_url('')));

		} elseif ($this->tank_auth->is_logged_in(FALSE)) {						// logged in, not activated
			// redirect('/auth/send_again/');
			_ajax_json(array('redirect' => site_url('auth/send_again')));

		} elseif (!$this->config->item('allow_registration', 'tank_auth')) {	// registration is off
			$this->_show_message($this->lang->line('auth_message_registration_disabled'));

		} else {
			$use_username = $this->config->item('use_username', 'tank_auth');
			if ($use_username) {
				$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->config->item('username_min_length', 'tank_auth').']|max_length['.$this->config->item('username_max_length', 'tank_auth').']|alpha_dash');
			}
			$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
			$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']');
			$this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');

			$captcha_registration	= $this->config->item('captcha_registration', 'tank_auth');
			$use_recaptcha			= $this->config->item('use_recaptcha', 'tank_auth');
			if ($captcha_registration) {
				if ($use_recaptcha) {
					$this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
				} else {
					$this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
				}
			}
			$data['errors'] = array();

			$email_activation = $this->config->item('email_activation', 'tank_auth');

			if ($this->form_validation->run()) {								// validation ok
				if (!is_null($data = $this->tank_auth->create_user(
						$use_username ? $this->form_validation->set_value('username') : '',
						$this->form_validation->set_value('email'),
						$this->form_validation->set_value('password'),
						$email_activation))) {									// success

					$data['site_name'] = $this->config->item('website_name', 'tank_auth');

					if ($email_activation) {									// send "activate" email
						$data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;

						$this->_send_email('activate', $data['email'], $data);

						unset($data['password']); // Clear password (just for any case)

						$this->_show_message($this->lang->line('auth_message_registration_completed_1'));

					} else {
						if ($this->config->item('email_account_details', 'tank_auth')) {	// send "welcome" email

							$this->_send_email('welcome', $data['email'], $data);
						}
						unset($data['password']); // Clear password (just for any case)

						$this->_show_message($this->lang->line('auth_message_registration_completed_2').' '.anchor('/auth/login/', 'Login'));
					}
				} else {
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			if ($captcha_registration) {
				if ($use_recaptcha) {
					$data['recaptcha_html'] = $this->_create_recaptcha();
				} else {
					$data['captcha_html'] = $this->_create_captcha();
				}
			}
			$data['use_username'] = $use_username;
			$data['captcha_registration'] = $captcha_registration;
			$data['use_recaptcha'] = $use_recaptcha;
			$this->lc_global->data_output(array('auth/register_form'), $data);
		}
	}

	/**
	 * Send activation email again, to the same or new email address
	 *
	 * @return void
	 */
	function send_again()
	{
		if (!$this->tank_auth->is_logged_in(FALSE)) {							// not logged in or activated
			redirect('/auth/login/');

		} else {
			$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');

			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if (!is_null($data = $this->tank_auth->change_email(
						$this->form_validation->set_value('email')))) {			// success

					$data['site_name']	= $this->config->item('website_name', 'tank_auth');
					$data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;

					$this->_send_email('activate', $data['email'], $data);

					$this->_show_message(sprintf($this->lang->line('auth_message_activation_email_sent'), $data['email']));

				} else {
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			$this->lc_global->data_output(array('auth/send_again_form'), $data);
		}
	}

	/**
	 * Activate user account.
	 * User is verified by user_id and authentication code in the URL.
	 * Can be called by clicking on link in mail.
	 *
	 * @return void
	 */
	function activate()
	{
		$user_id		= $this->uri->segment(3);
		$new_email_key	= $this->uri->segment(4);

		// Activate user
		if ($this->tank_auth->activate_user($user_id, $new_email_key)) {		// success
			$this->tank_auth->logout();
			$this->_show_message($this->lang->line('auth_message_activation_completed').' '.anchor('/auth/login/', 'Login'));

		} else {																// fail
			$this->_show_message($this->lang->line('auth_message_activation_failed'));
		}
	}

	/**
	 * Generate reset code (to change password) and send it to user
	 *
	 * @return void
	 */
	function forgot_password()
	{
		if ($this->tank_auth->is_logged_in()) {									// logged in
			// redirect('');
			_ajax_json(array('redirect' => site_url('')));

		} elseif ($this->tank_auth->is_logged_in(FALSE)) {						// logged in, not activated
			// redirect('/auth/send_again/');
			_ajax_json(array('redirect' => site_url('auth/send_again')));

		} else {
			$this->form_validation->set_rules('login', 'Email or login', 'trim|required|xss_clean');

			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if (!is_null($data = $this->tank_auth->forgot_password(
						$this->form_validation->set_value('login')))) {

					$data['site_name'] = $this->config->item('website_name', 'tank_auth');

					// Send email with password activation link
					$this->_send_email('forgot_password', $data['email'], $data);

					$this->_show_message($this->lang->line('auth_message_new_password_sent'));

				} else {
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			$data['page_title'] = __('Reset Password');

			$this->lc_global->data_output(array('auth/header', 'auth/forgot_password_form', 'auth/footer'), $data);
		}
	}

	//super admin resetting another user's password to a random string
	function lc_reset_user_password()
	{
		if ($this->tank_auth->is_logged_in()) {									// logged in
			$this->load->model('User');

			$loggedInUserId = $this->tank_auth->get_user_id();
			$profile = $this->User->get_user_profile($loggedInUserId);
			$loggedInUserRole = $profile->userRoleId;

			if ($loggedInUserRole == UR_SUPER_ADMIN) {
				// echo '<br/>Super Admin Logged In';

				if (!is_null($data = $this->tank_auth->forgot_password($this->session->flashdata('login')))) {
					$data['site_name'] = $this->config->item('website_name', 'tank_auth');
					$this->_send_email('other_user_reset_password', $data['email'], $data);
					_ajax_json(array('success' => true));
				}
				else {
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
					_ajax_json(array('failure' => true, 'errors' => $data['errors']));
				}
			}
			else {
				_ajax_json(array('failure' => true, 'popup' => 'permission_denied', 'msg' => 'reset user passwords'));
			}

		} elseif ($this->tank_auth->is_logged_in(FALSE)) {						// logged in, not activated
			redirect('/auth/send_again/');

		}
	}

	/**
	 * Replace user password (forgotten) with a new one (set by user).
	 * User is verified by user_id and authentication code in the URL.
	 * Can be called by clicking on link in mail.
	 *
	 * @return void
	 */
	function reset_password()
	{
		$user_id		= $this->uri->segment(3);
		$new_pass_key	= $this->uri->segment(4);

		$this->form_validation->set_rules('new_password', 'New Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']|alpha_dash');
		$this->form_validation->set_rules('confirm_new_password', 'Confirm new Password', 'trim|required|xss_clean|matches[new_password]');

		$data['errors'] = array();

		if ($this->form_validation->run()) {								// validation ok
			if (!is_null($data = $this->tank_auth->reset_password(
					$user_id, $new_pass_key,
					$this->form_validation->set_value('new_password')))) {	// success

				$data['site_name'] = $this->config->item('website_name', 'tank_auth');

				// Send email with new password
				$this->_send_email('reset_password', $data['email'], $data);

				$this->_show_message($this->lang->line('auth_message_new_password_activated').' '.anchor('/auth/login/', 'Login'));

			} else {														// fail
				$this->_show_message($this->lang->line('auth_message_new_password_failed'));
			}
		} else {
			// Try to activate user by password key (if not activated yet)
			if ($this->config->item('email_activation', 'tank_auth')) {
				$this->tank_auth->activate_user($user_id, $new_pass_key, FALSE);
			}

			if (!$this->tank_auth->can_reset_password($user_id, $new_pass_key)) {
				$this->_show_message($this->lang->line('auth_message_new_password_failed'));
			}
		}
		$this->lc_global->data_output(array('auth/reset_password_form'), $data);
	}

	/**
	 * Change user password
	 *
	 * @return void
	 */
	function change_password()
	{
		if (!$this->tank_auth->is_logged_in()) {								// not logged in or not activated
			// redirect('/auth/login/');
			_ajax_json(array('redirect' => site_url('auth/login')));

		} else {
			$this->form_validation->set_rules('old_password', 'Old Password', 'trim|required|xss_clean');
			$this->form_validation->set_rules('new_password', 'New Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']|alpha_dash');
			$this->form_validation->set_rules('confirm_new_password', 'Confirm new Password', 'trim|required|xss_clean|matches[new_password]');

			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if ($this->tank_auth->change_password(
						$this->form_validation->set_value('old_password'),
						$this->form_validation->set_value('new_password'))) {	// success
					//$this->_show_message($this->lang->line('auth_message_password_changed'));
					$this->load->model('User');
					$this->User->changed_password($this->tank_auth->get_user_id());
					// redirect('/auth/profile_check');
					_ajax_json(array('redirect' => site_url('auth/profile_check')));

				} else {														// fail
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			$this->lc_global->data_output(array('auth/change_password_form'), $data);
		}
	}

	/**
	 * Change user email
	 *
	 * @return void
	 */
	function change_email()
	{
		if (!$this->tank_auth->is_logged_in()) {								// not logged in or not activated
			// redirect('/auth/login/');
			_ajax_json(array('redirect' => site_url('auth/login')));

		} else {
			$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
			$this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');

			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if (!is_null($data = $this->tank_auth->set_new_email(
						$this->form_validation->set_value('email'),
						$this->form_validation->set_value('password')))) {			// success

					$data['site_name'] = $this->config->item('website_name', 'tank_auth');

					// Send email with new email address and its activation link
					$this->_send_email('change_email', $data['new_email'], $data);

					$this->_show_message(sprintf($this->lang->line('auth_message_new_email_sent'), $data['new_email']));

				} else {
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			$this->lc_global->data_output(array('auth/change_email_form'), $data);
		}
	}

	/**
	 * Replace user email with a new one.
	 * User is verified by user_id and authentication code in the URL.
	 * Can be called by clicking on link in mail.
	 *
	 * @return void
	 */
	function reset_email()
	{
		$user_id		= $this->uri->segment(3);
		$new_email_key	= $this->uri->segment(4);

		// Reset email
		if ($this->tank_auth->activate_new_email($user_id, $new_email_key)) {	// success
			$this->tank_auth->logout();
			$this->_show_message($this->lang->line('auth_message_new_email_activated').' '.anchor('/auth/login/', 'Login'));

		} else {																// fail
			$this->_show_message($this->lang->line('auth_message_new_email_failed'));
		}
	}

	/**
	 * Delete user from the site (only when user is logged in)
	 *
	 * @return void
	 */
	function unregister()
	{
		if (!$this->tank_auth->is_logged_in()) {								// not logged in or not activated
			// redirect('/auth/login/');
			_ajax_json(array('redirect' => site_url('auth/login')));

		} else {
			$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');

			$data['errors'] = array();

			if ($this->form_validation->run()) {								// validation ok
				if ($this->tank_auth->delete_user(
						$this->form_validation->set_value('password'))) {		// success
					$this->_show_message($this->lang->line('auth_message_unregistered'));

				} else {														// fail
					$errors = $this->tank_auth->get_error_message();
					foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
				}
			}
			$this->lc_global->data_output(array('auth/unregister_form'), $data);
		}
	}

	/**
	 * Show info message
	 *
	 * @param	string
	 * @return	void
	 */
	function _show_message($message)
	{
		$this->session->set_flashdata('message', $message);
		// redirect('/auth/');
		_ajax_json(array('redirect' => site_url('auth')));
	}

	/**
	 * Send email message of given type (activate, forgot_password, etc.)
	 *
	 * @param	string
	 * @param	string
	 * @param	array
	 * @return	void
	 */
	// i think i dont need this anymore...
	// function _send_email($type, $email, &$data)
	// {
	// 	/*
	// 	Expects parameter:
	// 		$email = array(
	// 			'emailToAddress'=> a valid email address,
	// 			'emailToName' => a string of the recipiants name
	// 			'emailFromAddress'=> a valid email address,
	// 			'emailFromName' => a string of the senders name
	// 			'emailSubject'=> string of the subject,
	// 			'emailBody' => string of the body (can be html)
	// 			//can add attachment/bcc/cc etc later
	// 		)
	// 	*/
	// 	$this->load->library('lc');

	// 	$emailObj = array(
	// 		'emailToAddress'=> $email,
	// 		'emailToName' => $email,
	// 		'emailFromAddress' => $this->config->item('webmaster_email', 'tank_auth'),
	// 		'emailFromName' => $this->config->item('website_name', 'tank_auth'),
	// 		'emailSubject'=> sprintf($this->lang->line('auth_subject_'.$type), $this->config->item('website_name', 'tank_auth')),
	// 		'emailBody' => $this->load->view('email/'.$type.'-html', $data, TRUE)
	// 		//can add attachment/bcc/cc etc later
	// 	);

	// 	$this->lc->send_email($emailObj);

	// 	/*
	// 	$this->load->library('email');
	// 	$this->email->from($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
	// 	$this->email->reply_to($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
	// 	$this->email->to($email);
	// 	$this->email->subject(sprintf($this->lang->line('auth_subject_'.$type), $this->config->item('website_name', 'tank_auth')));
	// 	$this->email->message($this->load->view('email/'.$type.'-html', $data, TRUE));
	// 	$this->email->set_alt_message($this->load->view('email/'.$type.'-txt', $data, TRUE));
	// 	$this->email->send();
	// 	*/
	// }

	/**
	 * Create CAPTCHA image to verify user as a human
	 *
	 * @return	string
	 */
	function _create_captcha()
	{
		$this->load->helper('captcha');

		$cap = create_captcha(array(
			'img_path'		=> './'.$this->config->item('captcha_path', 'tank_auth'),
			'img_url'		=> base_url().$this->config->item('captcha_path', 'tank_auth'),
			'font_path'		=> './'.$this->config->item('captcha_fonts_path', 'tank_auth'),
			'font_size'		=> $this->config->item('captcha_font_size', 'tank_auth'),
			'img_width'		=> $this->config->item('captcha_width', 'tank_auth'),
			'img_height'	=> $this->config->item('captcha_height', 'tank_auth'),
			'show_grid'		=> $this->config->item('captcha_grid', 'tank_auth'),
			'expiration'	=> $this->config->item('captcha_expire', 'tank_auth'),
		));

		// Save captcha params in session
		$this->session->set_flashdata(array(
				'captcha_word' => $cap['word'],
				'captcha_time' => $cap['time'],
		));

		return $cap['image'];
	}

	/**
	 * Callback function. Check if CAPTCHA test is passed.
	 *
	 * @param	string
	 * @return	bool
	 */
	function _check_captcha($code)
	{
		$time = $this->session->flashdata('captcha_time');
		$word = $this->session->flashdata('captcha_word');

		list($usec, $sec) = explode(" ", microtime());
		$now = ((float)$usec + (float)$sec);

		if ($now - $time > $this->config->item('captcha_expire', 'tank_auth')) {
			$this->form_validation->set_message('_check_captcha', $this->lang->line('auth_captcha_expired'));
			return FALSE;

		} elseif (($this->config->item('captcha_case_sensitive', 'tank_auth') AND
				$code != $word) OR
				strtolower($code) != strtolower($word)) {
			$this->form_validation->set_message('_check_captcha', $this->lang->line('auth_incorrect_captcha'));
			return FALSE;
		}
		return TRUE;
	}

	/**
	 * Create reCAPTCHA JS and non-JS HTML to verify user as a human
	 *
	 * @return	string
	 */
	function _create_recaptcha()
	{
		$this->load->helper('recaptcha');

		// Add custom theme so we can get only image
		$options = "<script>var RecaptchaOptions = {theme: 'custom', custom_theme_widget: 'recaptcha_widget'};</script>\n";

		// Get reCAPTCHA JS and non-JS HTML
		$html = recaptcha_get_html($this->config->item('recaptcha_public_key', 'tank_auth'));

		return $options.$html;
	}

	/**
	 * Callback function. Check if reCAPTCHA test is passed.
	 *
	 * @return	bool
	 */
	function _check_recaptcha()
	{
		$this->load->helper('recaptcha');

		$resp = recaptcha_check_answer($this->config->item('recaptcha_private_key', 'tank_auth'),
				$_SERVER['REMOTE_ADDR'],
				$_POST['recaptcha_challenge_field'],
				$_POST['recaptcha_response_field']);

		if (!$resp->is_valid) {
			$this->form_validation->set_message('_check_recaptcha', $this->lang->line('auth_incorrect_captcha'));
			return FALSE;
		}
		return TRUE;
	}

	function profile_check(){

      if ($this->tank_auth->is_logged_in()) {                                 // logged in
        $id = $this->tank_auth->get_user_id();

        if ($this->tank_auth->is_first_login($id)) {
        	//first login, prompt for update password
            // redirect('/auth/change_password');
            _ajax_json(array('redirect' => site_url('auth/change_password')));
        }
        elseif ($this->tank_auth->is_profile_empty($id)){
        	//not first login, but profile is empty
            // redirect('/crm/update_profile');
            _ajax_json(array('redirect' => site_url('crm/update_profile')));

        }
        else {
            //not first login, profile not empty;
            // redirect('');
            _ajax_json(array('redirect' => site_url()));
        }

      } elseif ($this->tank_auth->is_logged_in(FALSE)) {                      // logged in, not activated
          // redirect('/auth/send_again/');
      	_ajax_json(array('redirect' => site_url('auth/send_again')));
      } else {                                                                // not logged in
          // redirect('/auth/login/');
        _ajax_json(array('redirect' => site_url('auth/login')));
      }
  }

}

/* End of file auth.php */
/* Location: ./application/controllers/auth.php */