text:
@interface LNChartAction()
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger numberOfItems;
@property (nonatomic, assign) NSInteger currentItemIndex;                   //当前item的下标
@property (nonatomic, assign) NSInteger previousItemIndex;
@property (nonatomic, assign) NSTimeInterval startTime;
@property (nonatomic, assign) NSTimeInterval lastTime;
@property (nonatomic, assign) NSTimeInterval toggleTime;                    //切换时间
@property (nonatomic, assign) NSTimeInterval scrollDuration;                //持续的时间
@property (nonatomic, assign) CGFloat toggle;                               //切换
@property (nonatomic, assign) CGFloat startOffset;                          //开始的
@property (nonatomic, assign) CGFloat endOffset;                            //结束的偏移量
@property (nonatomic, assign) CGFloat scrollSpeed;                          //滑动的速度
@property (nonatomic, assign) CGFloat startVelocity;                        //开始的速率
@property (nonatomic, assign) CGFloat decelerationRate;                     //减速的速率
@property (nonatomic, assign) CGFloat bounceDistance;                       //回弹的距离
@property (nonatomic, assign) CGFloat scrollOffset;                         //滑动的偏移量
@property (nonatomic, assign) CGFloat previousTranslation;                  //位置信息
@end

@implementation LNChartAction

+ (instancetype)setupWithData:(LNChartData *)data {
    LNChartAction *animator = [[LNChartAction alloc]init];
    animator.data = data;
    return animator;
}
//动画参数
- (void)setupDefaultValue {
    _scrollSpeed = 1.0;
    _decelerationRate = 0.95;
    _numberOfItems = self.data.dataSets.count;
    _bounceDistance = self.data.valCount / 4;   //弹跳的距离
}

#pragma mark UIPinchGestureRecognizer

- (void)animationWithLongPressGestureRecognizer:(UILongPressGestureRecognizer *)longPress
                                           view:(UIView *)view
                                      chartTyoe:(NSInteger)type {

    CGPoint point = [longPress locationInView:view];
    switch (longPress.state) {
        case UIGestureRecognizerStateBegan:
            self.data.highlighter.highlight = YES;
            [self computeHighlightPoint:point type:type];
            break;
        case UIGestureRecognizerStateChanged:
            [self computeHighlightPoint:point type:type];
            break;
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:
            self.data.highlighter.highlight = NO;
            self.data.highlighter.touchPoint = point;
            break;
        default:
            break;
    }

    if (self.animatorBlock) {
        self.animatorBlock(LNChartActionType_LongPress, longPress, NO);
    }
}

- (void)computeHighlightPoint:(CGPoint)point type:(NSInteger)type {
    if (point.x < self.data.viewHandler.contentLeft ||
        point.x > self.data.viewHandler.contentRight) {
        return;
    }
    CGFloat volumeWidth = self.data.candleSet.candleW;
    switch (type) {
        case 0:
            volumeWidth = self.data.viewHandler.contentWidth / self.data.valCount;
            break;
        case 1:
            if (((LNDataSet *)self.data.dataSets.firstObject).preClosePx > 0) {
                volumeWidth = self.data.viewHandler.contentWidth / self.data.valCount;
            }
            break;
        default:
            break;
    }
    self.data.highlighter.index = (NSInteger)((point.x - self.data.viewHandler.contentLeft) / volumeWidth);
    self.data.highlighter.touchPoint = point;
    self.data.highlighter.index += self.data.lastStart;
    if (self.data.highlighter.index > self.data.dataSets.count - 1) {
        self.data.highlighter.index = self.data.dataSets.count - 1;
    }
}

#pragma mark UIPinchGestureRecognizer

static NSInteger temp;
static NSInteger lastYValCount;
- (void)animationWithPinchGestureRecognizer:(UIPinchGestureRecognizer *)pinch view:(UIView *)view {
    if (pinch.state == UIGestureRecognizerStateBegan) {
        lastYValCount = self.data.valCount;
        temp = 0;
    }
    CGFloat candleW = self.data.candleSet.candleW * pinch.scale;
    if (candleW > self.data.candleSet.candleMaxW ||
        candleW < self.data.candleSet.candleMinW) {
        return;
    }
    self.data.candleSet.candleW = candleW;
    CGFloat valCount = self.data.viewHandler.contentWidth / self.data.candleSet.candleW;
    NSInteger offset = floor(valCount) - lastYValCount;
    self.data.valCount = floor(valCount);

    if (offset % 2 != 0) {
        //左右各加一次
        if (temp % 2 == 0) {
            NSInteger num = 1;
            if (offset < 0) {
                num = -1;
            }
            self.data.lastStart -= num;
        }
        temp++;
    }

    if (self.data.valCount < self.data.dataSets.count) {
        self.data.lastStart -= offset/2;
        self.data.lastEnd = self.data.lastStart + self.data.valCount;
    }
    else {
        self.data.lastStart = 0;
        self.data.lastEnd = self.data.dataSets.count;
    }
    lastYValCount = self.data.valCount;
    if (self.animatorBlock) {
        self.animatorBlock(LNChartActionType_Pinch, nil, NO);
    }
    pinch.scale = 1.0f;
    [self setupDefaultValue];  //重新设置回弹距离
}

#pragma mark UIPanGestureRecognizer

- (void)animationWithPanGestureRecognizer:(UIPanGestureRecognizer *)pan view:(UIView *)view {
    switch (pan.state) {
        case UIGestureRecognizerStateBegan: {
            _dragging = YES;
            _scrolling = NO;
            _decelerating = NO;
            _scrollOffset = self.data.lastStart;
            _previousTranslation = [pan translationInView:view].x;
        }
            break;
        case UIGestureRecognizerStateChanged: {
            //坐标系中X的值 向左 为 负 向右为 正
            CGFloat velocity = [pan velocityInView:view].x;
            //坐标系中的像素/秒的速度
            CGFloat translation = [pan translationInView:view].x;
            //因子 滑动的速度
            CGFloat factor = 0.5;
            //开始的速率
            _startVelocity = -velocity * factor * _scrollSpeed / self.data.candleSet.candleW;
            //偏移量
            _scrollOffset -= (translation - _previousTranslation) / self.data.candleSet.candleW;
            _previousTranslation = translation;
            [self didScroll];
        }
            break;
        case UIGestureRecognizerStateEnded:
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateFailed: {
            _dragging = NO;
            //判断是否可以减速
            if ([self shouldDecelerate]) {
                [self startDecelerating];
            }
            //如果不在减速过程中
            if (!_decelerating) {
                if ((fabs(_scrollOffset - [self clampedOffset:_scrollOffset]) > FLOAT_ERROR_MARGIN)) {
                    if (fabs(_scrollOffset - self.currentItemIndex) < FLOAT_ERROR_MARGIN) {
                        [self scrollToItemAtIndex:self.currentItemIndex duration:0.01];
                    }
                    else if ([self shouldScroll]) {
                        NSInteger direction = (int)(_startVelocity / fabs(_startVelocity));
                        [self scrollToItemAtIndex:self.currentItemIndex + direction animated:YES];
                    }
                    else {
                        [self scrollToItemAtIndex:self.currentItemIndex animated:YES];
                    }
                }
            }

            //请求加载更多数据
            if (self.data.loadMoreType == ChartLoadMoreType_Start) {
                self.data.loadMoreType = ChartLoadMoreType_Loading;
                if (self.animatorBlock) {
                    self.animatorBlock(LNChartActionType_LeftAction,nil,NO);
                }
            }
        }
            break;
        case UIGestureRecognizerStatePossible:
            break;
    }
}

#pragma mark - Animation

- (void)startAnimation {
    if (!_timer) {
        self.timer = [NSTimer timerWithTimeInterval:1.0/60.0
                                             target:self
                                           selector:@selector(step:)
                                           userInfo:nil
                                            repeats:YES];

        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:UITrackingRunLoopMode];
    }
}

- (void)stopAnimation {
    [_timer invalidate];
    _timer = nil;
    _dragging = NO;
    _scrolling = NO;
    _decelerating = NO;
    if (self.animatorBlock) {
        self.animatorBlock(LNChartActionType_Pan, nil, YES);
    }
}

- (void)step:(NSTimer *)step {
    //可能系统会跳过帧数,时间差值会有变化 这里进行判断
    NSTimeInterval currentTime = CACurrentMediaTime();
    double delta = currentTime - _lastTime;
    _lastTime = currentTime;

    //正在滑动中 -- 加速回弹
    if (_scrolling && !_dragging) {
        NSTimeInterval time = MIN(1.0, (currentTime - _startTime) / _scrollDuration);
        //按一定公式计算得到速率
        delta = [self easeInOut:time];
        //最后滑动的偏移量
        _scrollOffset = _startOffset + (_endOffset - _startOffset) * delta;

        [self didScroll];
        if (time >= 1.0) {
            _scrolling = NO;
        }
    } //正在减速中 -- 减速
    else if (_decelerating) {
        //持续时间
        CGFloat time = MIN(_scrollDuration, currentTime - _startTime);
        //加速度
        CGFloat acceleration = -_startVelocity/_scrollDuration;
        //距离  pow 的2次方
        CGFloat distance = _startVelocity * time + 0.5 * acceleration * pow(time, 2.0);
        //最后滑动的偏移量
        _scrollOffset = _startOffset + distance;
        [self didScroll];

        //动画时间超过最大,设置已停止减速
        if (fabs(time - _scrollDuration) < FLOAT_ERROR_MARGIN) {
            _decelerating = NO;
            if ((fabs(_scrollOffset - [self clampedOffset:_scrollOffset]) > FLOAT_ERROR_MARGIN)) {
                if (fabs(_scrollOffset - self.currentItemIndex) < FLOAT_ERROR_MARGIN) {
                    [self scrollToItemAtIndex:self.currentItemIndex duration:0.01];
                }
                else {
                    [self scrollToItemAtIndex:self.currentItemIndex animated:YES];
                }
            }
            else { //四舍五入整数值  round
                CGFloat difference = round(_scrollOffset) - _scrollOffset;
                if (difference > 0.5) {
                    difference = difference - 1.0;
                }
                else if (difference < -0.5) {
                    difference = 1.0 + difference;
                }
                _toggleTime = currentTime - MAX_TOGGLE_DURATION * fabs(difference);
                _toggle = MAX(-1.0, MIN(1.0, -difference));
            }
        }
    } //时间间隔的问题
    else if (fabs(_toggle) > FLOAT_ERROR_MARGIN) {
        //持续的时间
        NSTimeInterval toggleDuration = _startVelocity? MIN(1.0, MAX(0.0, 1.0 / fabs(_startVelocity))): 1.0;
        toggleDuration = MIN_TOGGLE_DURATION + (MAX_TOGGLE_DURATION - MIN_TOGGLE_DURATION) * toggleDuration;
        NSTimeInterval time = MIN(1.0, (currentTime - _toggleTime) / toggleDuration);
        delta = [self easeInOut:time];
        _toggle = (_toggle < 0.0)? (delta - 1.0): (1.0 - delta);
        [self didScroll];
    }
    else {
        [self stopAnimation];
    }
    //floor() 向下取整 ceil() 向上取整
}

//开始减速
- (void)startDecelerating {
    CGFloat distance = [self decelerationDistance];
    _startOffset = _scrollOffset;
    _endOffset = _startOffset + distance;

    if (_numberOfItems > self.data.valCount) {
        _endOffset = MAX(-_bounceDistance, MIN(_numberOfItems - self.data.valCount + _bounceDistance, _endOffset));
    } else {
        //最大显示数比数据量大时
        _endOffset = MAX(-_bounceDistance, MIN(_bounceDistance, _endOffset));
    }

    distance = _endOffset - _startOffset;

    _startTime = CACurrentMediaTime();
    _scrollDuration = fabs(distance) / fabs(0.5 * _startVelocity);

    if (distance != 0.0) {
        _decelerating = YES;
        [self startAnimation];
    }
}

//开始滑动,加减速运动
- (void)didScroll {
    CGFloat min = -_bounceDistance;
    CGFloat max = 0;
    if (_numberOfItems > self.data.valCount) {
        max = MAX(_numberOfItems - self.data.valCount, 0.0) + _bounceDistance;
    } else {
        max = MAX(0, 0.0) + _bounceDistance;
    }

    if (_scrollOffset < min) {
        _scrollOffset = min;
        _startVelocity = 0.0;
        //左拉加載更多数据Block回調
        if (self.data.loadMoreType == ChartLoadMoreType_Normal) {
            self.data.loadMoreType = ChartLoadMoreType_Start;
        }
    }
    else if (_scrollOffset > max) {
        _scrollOffset = max;
        _startVelocity = 0.0;
    }

    //check if index has changed
    NSInteger difference = [self minScrollDistanceFromIndex:self.currentItemIndex toIndex:self.previousItemIndex];
    if (difference) {
        //节点时间
        _toggleTime = CACurrentMediaTime();
        //节点距离
        _toggle = MAX(-1, MIN(1, difference));
        [self startAnimation];
    }
    if ([self.data hasEmptyNum]) {
        [self.data resetDataSetsAfterAnimation];
    }
    NSInteger offset = 0;
    if (_scrollOffset < 0) {
        offset = _scrollOffset;
        self.data.emptyStartNum = labs(offset);
        [self.data addEmptyCandleWhenAnimation:labs(offset)];
    }
    else if (_scrollOffset > self.data.dataSets.count - self.data.valCount){
        offset = _scrollOffset - (self.data.dataSets.count - self.data.valCount);
        self.data.emptyEndNum = labs(offset);
    }

    self.data.lastStart = _scrollOffset;
    self.data.lastEnd = self.data.lastStart + self.data.valCount;
    _previousItemIndex = self.currentItemIndex;

    if (self.animatorBlock) {
        self.animatorBlock(LNChartActionType_Pan, nil, NO);
    }
}

- (void)setScrollOffset:(CGFloat)scrollOffset {
    _scrolling = NO;
    _decelerating = NO;
    _startOffset = scrollOffset;
    _endOffset = scrollOffset;
    if (fabs(_scrollOffset - scrollOffset) > 0.0) {
        _scrollOffset = scrollOffset;
        [self didScroll];
    }
}

- (void)setCurrentItemIndex:(NSInteger)currentItemIndex {
    [self setScrollOffset:currentItemIndex];
}

- (NSInteger)currentItemIndex {
    return [self clampedIndex:round(_scrollOffset)];
}

- (NSInteger)clampedIndex:(NSInteger)index {
    if (_numberOfItems == 0) {
        return -1;
    } else {
        if (_numberOfItems > self.data.valCount) {
            return MIN(MAX(0, index), MAX(0, _numberOfItems - self.data.valCount));
        } else {
            return MIN(MAX(0, index), MAX(0, 0));
        }
    }
}

- (void)scrollByOffset:(CGFloat)offset duration:(NSTimeInterval)duration {
    if (duration > 0.0) {
        _decelerating = NO;
        _scrolling = YES;
        _startTime = CACurrentMediaTime();
        _startOffset = _scrollOffset;
        _scrollDuration = duration;
        _endOffset = _startOffset + offset;
        _endOffset = [self clampedOffset:_endOffset];
        [self startAnimation];
    } else {
        self.scrollOffset += offset;
    }
}

- (void)scrollToOffset:(CGFloat)offset duration:(NSTimeInterval)duration {
    [self scrollByOffset:[self minScrollDistanceFromOffset:_scrollOffset toOffset:offset] duration:duration];
}

- (CGFloat)minScrollDistanceFromOffset:(CGFloat)fromOffset toOffset:(CGFloat)toOffset {
    CGFloat directDistance = toOffset - fromOffset;
    return directDistance;
}

- (NSInteger)minScrollDistanceFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    NSInteger directDistance = toIndex - fromIndex;
    return directDistance;
}

- (void)scrollToItemAtIndex:(NSInteger)index duration:(NSTimeInterval)duration {
    [self scrollToOffset:index duration:duration];
}

- (void)scrollToItemAtIndex:(NSInteger)index animated:(BOOL)animated {
    [self scrollToItemAtIndex:index duration:animated? SCROLL_DURATION: 0];
}

//计算偏移量
- (CGFloat)clampedOffset:(CGFloat)offset {
    if (_numberOfItems == 0) {
        return -1.0;
    } else {
        if (_numberOfItems > self.data.valCount) {
            //最大lastStart 的最大值
            return MIN(MAX(0.0, offset), MAX(0.0, (CGFloat)_numberOfItems - self.data.valCount));
        } else {
            return MIN(MAX(0.0, offset), MAX(0.0, 0));
        }
    }
}

//是否开始减速
- (BOOL)shouldDecelerate {
    return (fabs(_startVelocity) > SCROLL_SPEED_THRESHOLD) &&
    (fabs([self decelerationDistance]) > DECELERATE_THRESHOLD);
}

//衰减的距离
- (CGFloat)decelerationDistance {
    //加速度
    CGFloat acceleration = -_startVelocity * DECELERATION_MULTIPLIER * (1.0 - _decelerationRate);
    return -pow(_startVelocity, 2.0) / (2.0 * acceleration);
}

//是否开始滑动
- (BOOL)shouldScroll {
    return (fabs(_startVelocity) > SCROLL_SPEED_THRESHOLD) &&
    (fabs(_scrollOffset - self.currentItemIndex) > SCROLL_DISTANCE_THRESHOLD);
}

//减缓时间
- (CGFloat)easeInOut:(CGFloat)time {
    return (time < 0.5)? 0.5 * pow(time * 2.0, 3.0): 0.5 * pow(time * 2.0 - 2.0, 3.0) + 1.0;
}

//减缓时间
- (CGFloat)circularEaseOut:(CGFloat)time {
    return sqrt((2 - time) * time);
}

@end


text:
from django.core.management.base import BaseCommand, CommandError
from django.core.exceptions import ObjectDoesNotExist
from atados_core.models import Project, Address, City, State
from optparse import make_option
import csv
import time
import unicodedata

class Command(BaseCommand):
  help = 'Update city names from CSV. CSV format is: state_code,city_name'
  option_list = BaseCommand.option_list + (
    make_option(
      "-f",
      "--file",
      dest = "filename",
      help = "specify csv file",
      metavar = "FILE"
    ),
  )

  def handle(self, *args, **options):
    if options['filename'] == None :
      raise CommandError("Option `--file=...` must be specified.")

    with open(options['filename'], 'rb') as f:
      reader = csv.reader(f)
      not_found = []

      # Fix incorrect cities
      print "Fixing possibly wrong city names..."
      self.update_possibly_incorrect()

      # Update from CSV
      for row in reader:
        state_code = row[0]
        city_name = row[1]
        city_name_without_accents = remove_accents(city_name.decode('utf8'))

        print "Trying to update city {}, {}...".format(city_name, state_code)

        try:
          city = City.objects.get(name__iexact=city_name_without_accents, state__code=state_code)
          if city_name == city_name_without_accents:
            print "[...] Already updated."
          else:
            city.name = city_name
            city.save()
            print "[...] Updated."
        except ObjectDoesNotExist:
          # In case city is not found, is it because it has already been updated?
          try:
            city = City.objects.get(name__iexact=city_name, state__code=state_code)
            print "[...] Already updated."
          except ObjectDoesNotExist:
            not_found.append([city_name, state_code])
            print "[...] Not found"
            pass
          pass

      # Create not found
      print "Creating not found cities"
      for c in not_found:
        state = State.objects.get(code=c[1])
        city = City(name=c[0], state=state)
        city.save()
        print "Created {}, {}".format(c[0], c[1])

  def update_possibly_incorrect(self):
    """ This fixed cities which do not match the csv """
    update = {
        'Santa Rosa, AC': 'Santa Rosa do Purus',
        'Olho D Agua Grande, AL': 'Olho d\'Agua Grande',
        'Agua Branca do Amapari, AP': 'Pedra Branca do Amapari',
        'Dias D Avila, BA': 'Dias d\'Avila',
        'Muquem do Sao Francisco, BA': 'Muquem de Sao Francisco',
        'Santa Terezinha, BA': 'Santa Teresinha',
        'Sao Roque do Cannaa, ES': 'Sao Roque do Canaa',
        'Campo Limpo, GO': 'Campo Limpo de Goias',
        'Buritirama, MA': 'Buritirana',
        'Pindare Mirim, MA': 'Pindare-Mirim',
        'Santo Amaro, MA': 'Santo Amaro do Maranhao',
        'Amparo da Serra, MG': 'Amparo do Serra',
        'Dona Euzebia, MG': 'Dona Eusebia',
        'Gouvea, MG': 'Gouveia',
        'Itabirinha de Mantena, MG': 'Itabirinha',
        'Limeira D\'oeste, MG': 'Limeira do Oeste',
        'Queluzita, MG': 'Queluzito',
        'Santa Rita do Ibitipoca, MG': 'Santa Rita de Ibitipoca',
        'Sao Tome das Letras, MG': 'Sao Thome das Letras',
        'Sem Peixe, MG': 'Sem-Peixe',
        'Passa Vinte, MG': 'Passa-Vinte',
        'Bataipora, MS': 'Bataypora',
        'Figueiropolis D Oeste, MT': 'Figueiropolis D\'Oeste',
        'Santa Rita, MT': 'Santa Rita do Trivelato',
        'Serra Nova, MT': 'Serra Nova Dourada',
        'Cachoeira de Piria, PA': 'Cachoeira do Piria,',
        'Santa Cecilia de Umbuzeiro, PB': 'Santa Cecilia',
        'Sao Domingos de Pombal, PB': 'Sao Domingos',
        'Belem de Sao Francisco, PE': 'Belem do Sao Francisco',
        'Itamaraca, PE': 'Ilha de Itamaraca',
        'Lagoa do Itaenga, PE': 'Lagoa de Itaenga',
        'Bela Vista do Caroba, PR': 'Bela Vista da Caroba',
        'Perola do Oeste, PR': 'Perola d\'Oeste',
        'Pinhal do Sao Bento, PR': 'Pinhal de Sao Bento',
        'Parati, RJ': 'Paraty',
        'Trajano de Morais, RJ': 'Trajano de Moraes',
        'Armacao de Buzios, RJ': 'Armacao dos Buzios',
        'Jundia de Cima, RN': 'Jundia',
        'Alta Floresta do Oeste, RO': 'Alta Floresta d\'Oeste',
        'Alvorada do Oeste, RO': 'Alvorada d\'Oeste',
        'Santa Luzia do Oeste, RO': 'Santa Luzia d\'Oeste',
        'Almirante Tamandare, RS': 'Almirante Tamandare do Sul',
        'Doutor Bozano, RS': 'Bozano',
        'Canudos, RS': 'Canudos do Vale',
        'Capao Bonito, RS': 'Capao Bonito do Sul',
        'Lagoa Bonita, RS': 'Lagoa Bonita do Sul',
        'Xingu, RS': 'Novo Xingu',
        'Santa Cecilia, RS': 'Santa Cecilia do Sul',
        'Santana do Livramento, RS': 'Sant\'Ana do Livramento',
        'Sao Jose, RS': 'Sao Jose do Sul',
        'Sao Pedro, RS': 'Sao Pedro das Missoes',
        'Presidente Castelo Branco, SC': 'Presidente Castello Branco',
        'Sao Miguel D\'oeste, SC': 'Sao Miguel do Oeste',
        'Mogi-guacu, SP': 'Mogi Guacu',
        'Mogi-mirim, SP': 'Mogi Mirim',
        'Sao Valerio da Natividade, TO': 'Sao Valerio',
        'Chapada da Areia, TO': 'Chapada de Areia',
        'Couto de Magalhaes, TO': 'Couto Magalhaes',
        }
    for key, value in update.iteritems():
      info = key.split(', ')
      try:
        c = City.objects.get(name=info[0], state__code=info[1])
        c.name = value
        c.save()
        print "[...] {} fixed to {}".format(info[0], value)
      except:
        print "[...] {} does not need fixing".format(info[0])
        pass

def remove_accents(input_str):
    nfkd_form = unicodedata.normalize('NFKD', input_str)
    only_ascii = nfkd_form.encode('ASCII', 'ignore')
    return only_ascii

redpajama_set_name: RedPajamaGithub


text:
package edu.uw.tacoma.piggy.view;

import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

import edu.uw.tacoma.piggy.view.listener.MenuListener;

/**
 * The class for application menu
 * @author Varik Hoang
 */
@SuppressWarnings("serial")
public class PiggyMenu
extends JMenuBar
{
	MenuListener listener;

	/**
	 * The constructor for the menu
	 */
	public PiggyMenu(PiggyGUI gui)
	{
		listener = new MenuListener(gui);

		createFileMenu();
		createHelpMenu();
	}

	/**
	 * The Piggy GUI
	 */
	private PiggyGUI myGUI;

	/**
	 * The method returns the GUI.
	 * @return the GUI
	 */
	protected PiggyGUI getGUI()
	{
		return myGUI;
	}

	/**
	 * The method sets the GUI
	 * @param theGUI the Piggy GUI
	 */
	public void setGUI(PiggyGUI theGUI)
	{
		myGUI = theGUI;
	}

	public void createFileMenu()
	{
		JMenu menuFile = new JMenu("File");
		add(menuFile);

		JMenuItem menuFileExit = new JMenuItem("Exit");
		menuFileExit.setActionCommand(PiggyViewConst.MENU_FILE_EXIT);
		menuFileExit.addActionListener(listener);
		menuFile.add(menuFileExit);
	}

	public void createHelpMenu()
	{
		JMenu menuHelp = new JMenu("Help");
		add(menuHelp);

		JMenuItem menuHelpAbout = new JMenuItem("About");
		menuHelpAbout.setActionCommand(PiggyViewConst.MENU_HELP_ABOUT);
		menuHelpAbout.addActionListener(listener);
		menuHelp.add(menuHelpAbout);
	}

}


text:
@extends('base')

@section('head')
    <title>Store</title>
    @parent
@stop

@section('body')

    <store-management :character="{{ $character->load('inventory.items', 'store.items') }}"></store-management>

                    Back to Profile

@stop

@section('footer')
    @parent

@stop


text:
/* Vendor */
@import '~normalize.css/normalize.css';

/* App */
@import '~styles/base';
@import '~styles/ui';
@import '~styles/sandbox';
@import '~styles/controls';
@import '~styles/preview';
@import '~styles/theme';
@import '~styles/snippet';


text:
author: robmyers
comments: true
date: 2006-01-14 04:31:38+00:00
layout: post
slug: nkos-foad
title: NKOS FOAD
wordpress_id: 784
categories:
- Aesthetics
- Generative Art
- Reviews
- Satire
---

I like the pictures in A New Kind Of Science but it's low on my list of things to actually read. I think Wolfram is going to be digital art's Baudrillard. Shudder. My least favourite part of NKOS is the New Kind Of Copyright License Wolfram has at the start of the book. Hint: Wolfram either doesn't know about, or is choosing to ignore, fair use/fair dealing. Actually that's not true, his treatment of Matthew Cook makes that pale into insignificance.

Anyway, this brings us to the most wonderful review of NKOS that I've read in a while:

[A Rare Blend of Monster Raving Egomania and Utter Batshit Insanity.](http://www.cscs.umich.edu/~crshalizi/reviews/wolfram/)

Technorati Tags: [aesthetics](http://www.technorati.com/tag/aesthetics), [art](http://www.technorati.com/tag/art), [generative art](http://www.technorati.com/tag/generative art)


text:
@interface BNCreditCardTests : XCTestCase

@property NSData *key;
@property BNCreditCard *encryptedCreditCard;
@property BNCreditCard *cardToEncrypt;

@end

@implementation BNCreditCardTests

static const int KEY_LENGTH = 16;

- (void)setUp {
    [super setUp];

    uint8_t key[KEY_LENGTH] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
    self.key = [NSData dataWithBytes:key length:sizeof(key)];

    self.encryptedCreditCard = [BNCreditCard new];
    self.encryptedCreditCard.cardNumber = @"NXU/WqdgRAtAkXHnRiZ5xqmosqJhCFDiAgacb+GbS68=";
    self.encryptedCreditCard.expMonth = @"UbiBOe/QNlUpavS0KhOVkQ==";
    self.encryptedCreditCard.expYear = @"YycsTWZvdnqKyKqscPYTZw==";
    self.encryptedCreditCard.cvv = @"wrp0KdVqXRv6U4CAGtkorw==";

    self.cardToEncrypt = [BNCreditCard new];
    self.cardToEncrypt.cardNumber = @"4002620000000005";
    self.cardToEncrypt.expMonth = @"10";
    self.cardToEncrypt.expYear = @"20";
    self.cardToEncrypt.cvv = @"000";

}

- (void)testEncryptCreditCard {

    // When:
    BNCreditCard *encryptedCard = [self.cardToEncrypt encryptedCreditCardWithSessionKey:self.key];

    // Then:
    XCTAssertEqualObjects(self.encryptedCreditCard, encryptedCard, @"The pre-existing encrypted credit card object (self.encryptedCreditCard) should be equal to the credit card object that is created in this test (encryptedCard).");
}

- (void)tearDown {
    [super tearDown];
}

@end


text:
{% if site.search %}

{% endif %}
{% if site.owner.google.analytics %}

{% endif %}

{% if page.comments %}
  {% include disqus_comments.html %}
{% endif %}


text:
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using MS.Core;

namespace System.Runtime.Remoting.Metadata.W3cXsd2001
{
    public static class __SoapIdrefs
    {
        public static IObservable<System.String> GetXsdType(
            this IObservable<System.Runtime.Remoting.Metadata.W3cXsd2001.SoapIdrefs> SoapIdrefsValue)
        {
            return Observable.Select(SoapIdrefsValue, (SoapIdrefsValueLambda) => SoapIdrefsValueLambda.GetXsdType());
        }

        public static IObservable<System.String> ToString(
            this IObservable<System.Runtime.Remoting.Metadata.W3cXsd2001.SoapIdrefs> SoapIdrefsValue)
        {
            return Observable.Select(SoapIdrefsValue, (SoapIdrefsValueLambda) => SoapIdrefsValueLambda.ToString());
        }

        public static IObservable<System.Runtime.Remoting.Metadata.W3cXsd2001.SoapIdrefs> Parse(
            IObservable<System.String> value)
        {
            return Observable.Select(value,
                (valueLambda) => System.Runtime.Remoting.Metadata.W3cXsd2001.SoapIdrefs.Parse(valueLambda));
        }

        public static IObservable<System.String> get_XsdType()
        {
            return ObservableExt.Factory(() => System.Runtime.Remoting.Metadata.W3cXsd2001.SoapIdrefs.XsdType);
        }

        public static IObservable<System.String> get_Value(
            this IObservable<System.Runtime.Remoting.Metadata.W3cXsd2001.SoapIdrefs> SoapIdrefsValue)
        {
            return Observable.Select(SoapIdrefsValue, (SoapIdrefsValueLambda) => SoapIdrefsValueLambda.Value);
        }

        public static IObservable<System.Reactive.Unit> set_Value(
            this IObservable<System.Runtime.Remoting.Metadata.W3cXsd2001.SoapIdrefs> SoapIdrefsValue,
            IObservable<System.String> value)
        {
            return ObservableExt.ZipExecute(SoapIdrefsValue, value,
                (SoapIdrefsValueLambda, valueLambda) => SoapIdrefsValueLambda.Value = valueLambda);
        }
    }
}


text:
import Ember from 'ember';
import layout from '../templates/components/s-map-card';

export default Ember.Component.extend({
  layout: layout,
  card: null,

  markerObserver: Ember.observer('marker', 'marker.marker', function() {
		let marker = this.get('marker.marker');
    let card = new SMap.Card();
    card.getHeader().innerHTML = this.getWithDefault('header', '');
    card.getBody().appendChild(this.get('element'));
    marker.decorate(SMap.Marker.Feature.Card, card);

    this.set('card', card);
  })
});


text:
<?php

namespace Zumba\GastonJS\Browser;

use Zumba\GastonJS\Exception\BrowserError;

/**
 * Trait BrowserNavigateTrait
 * @package Zumba\GastonJS\Browser
 */
trait BrowserNavigateTrait {

  /**
   * Send a visit command to the browser
   * @param $url
   * @return mixed
   */
  public function visit($url) {
    return $this->command('visit', $url);
  }

  /**
   * Gets the current url we are in
   * @return mixed
   */
  public function currentUrl() {
    return $this->command('current_url');
  }

  /**
   * Goes back on the browser history if possible
   * @return bool
   * @throws BrowserError
   * @throws \Exception
   */
  public function goBack() {
    return $this->command('go_back');
  }

  /**
   * Goes forward on the browser history if possible
   * @return mixed
   * @throws BrowserError
   * @throws \Exception
   */
  public function goForward() {
    return $this->command('go_forward');
  }

  /**
   * Reloads the current page we are in
   */
  public function reload() {
    return $this->command('reload');
  }
}


text:
var selfEasyrtcid = "";

function initApp() {
    console.log("Initializing.");
    easyrtc.enableVideo(false);
    easyrtc.enableAudio(false);
    connect();
}

function connect() {
    easyrtc.connect("easyrtc.reconnect", loginSuccess, loginFailure);
}

function disconnect() {
    easyrtc.disconnect();
}

easyrtc.enableDebug(true);

easyrtc.setDisconnectListener(function() {
   easyrtc.showError("xx", "saw disconnect");
});

function sendDummy() {
    easyrtc.getRoomList(
      function() {
         easyrtc.showError("xx", "got fresh roomlist");
      },
      function(){
         easyrtc.showError("xx", "failed on fresh roomlist");
      });
}

function loginSuccess(easyrtcid) {
    document.getElementById("stateLabel").innerHTML = " connected as " + easyrtcid;
    easyrtc.showError("xx", "login success");
}

function loginFailure(errorCode, message) {
    document.getElementById("stateLabel").innerHTML = "disconnected";
    easyrtc.showError("xx", "login failure");
}


text:
Um pequeno app 'backendless' usando Jekyll que criei para agilizar o sorteio dos times na pela de final de semana que eu jogo. Foi feito pensando numa interface mobile, então acesse pelo seu smartphone. :)

## Instalação Local

- git clone git@github.com:matheusbras/tiratime.git
- cd tiratime
- bundle install
- jekyll serve --watch
- http://localhost:4000
- PROFIT!

## Contributing

1. Fork it
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 new Pull Request


text:
package main;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.*;
import javafx.event.*;
import javafx.scene.control.*;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.application.Platform;

import java.net.URL;
import java.util.ResourceBundle;
import java.util.ArrayList;

public class Controller implements Initializable {

    @FXML public Button startButton;
    @FXML public ProgressBar progressBar;
    @FXML public TextArea outputText;
    @FXML public Slider trialsSlider;
    @FXML public TextField trialsCounter;

    @FXML public RadioButton singleSetOption;
    @FXML public RadioButton threeSetOption;
    @FXML public RadioButton fiveSetOption;

    @FXML public ChoiceBox<String> player1ChoiceBox;
    @FXML public ChoiceBox<String> player2ChoiceBox;

    @FXML public CheckBox verboseModeCB;
    @FXML public CheckBox printMatchScoresCB;

    @Override // This method is called by the FXMLLoader when initialization is complete
    public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
        assert startButton != null : "fx:id=\"startButton\" was not injected: check your FXML file 'main.fxml'.";
        assert progressBar != null : "fx:id=\"progressBar\" was not injected: check your FXML file 'main.fxml'.";
        assert outputText != null : "fx:id=\"outputText\" was not injected: check your FXML file 'main.fxml'.";
        assert trialsSlider != null : "fx:id=\"trialsSlider\" was not injected: check your FXML file 'main.fxml'.";
        assert trialsCounter != null : "fx:id=\"trialsCounter\" was not injected: check your FXML file 'main.fxml'.";
        assert singleSetOption != null : "fx:id=\"singleSetOption\" was not injected: check your FXML file 'main.fxml'.";
        assert threeSetOption != null : "fx:id=\"threeSetOption\" was not injected: check your FXML file 'main.fxml'.";
        assert fiveSetOption != null : "fx:id=\"fiveSetOption\" was not injected: check your FXML file 'main.fxml'.";
        assert player1ChoiceBox != null : "fx:id=\"player1ChoiceBox\" was not injected: check your FXML file 'main.fxml'.";
        assert player2ChoiceBox != null : "fx:id=\"player2ChoiceBox\" was not injected: check your FXML file 'main.fxml'.";
        assert verboseModeCB != null : "fx:id=\"verboseModeCB\" was not injected: check your FXML file 'main.fxml'.";
        assert printMatchScoresCB != null : "fx:id=\"printSetScoresCB\" was not injected: check your FXML file 'main.fxml'.";

        ArrayList<Player> players = Settings.getPreloadedPlayers();
        ObservableList<String> playerNameList = FXCollections.observableArrayList();
        for(int i = 0; i < players.size(); i++){
            playerNameList.add(players.get(i).getName());
        }
        player1ChoiceBox.setItems(playerNameList);
        player2ChoiceBox.setItems(playerNameList);
        player1ChoiceBox.setValue(players.get(0).getName());
        player2ChoiceBox.setValue(players.get(1).getName());

        trialsSlider.valueProperty().addListener(new ChangeListener<Number>() {
            public void changed(ObservableValue<? extends Number> ov,
                                Number old_val, Number new_val) {
                trialsCounter.setText(new_val.intValue() + "");
                trialsSlider.setValue(new_val.intValue());
            }
        });
        trialsSlider.setShowTickLabels(true);
        trialsSlider.setShowTickMarks(true);
//        trialsSlider.setSnapToTicks(true);
//        trialsSlider.snapToTicksProperty().set(true);

        startButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override public void handle(ActionEvent e) {
                //Start button was clicked
                startClicked(e);
            }
        });
    }

    @FXML
    private void startClicked(ActionEvent event) {
        progressBar.setProgress(0.0);
        progressBar.progressProperty().set(0.0);
        outputText.setText("");

        new Thread(){
            public void run(){
                int trials = 1;
                try{
                    trials = Integer.parseInt(trialsCounter.getText());
                } catch(Exception ex){
                    outputText.setText("If you're seeing this, it means JavaFX broke.  It's not my fault!!");
                }

                int numSets = 1;
                if(threeSetOption.isSelected()){
                    numSets = 3;
                } else if(fiveSetOption.isSelected()){
                    numSets = 5;
                }

                boolean verbose = verboseModeCB.isSelected();
                boolean printMatchScores = printMatchScoresCB.isSelected();

                //get player1
                ArrayList<Player> players = Settings.getPreloadedPlayers();
                Player p1 = null;  Player p2 = null;
                for(Player p : players){
                    if(p.getName().equalsIgnoreCase(player1ChoiceBox.getValue())){
                        p1 = p;
                    }
                    if(p.getName().equalsIgnoreCase(player2ChoiceBox.getValue())){
                        p2 = p;
                    }
                }
                if(p1==null || p2==null){
                    outputText.setText("Uh-oh!  One or more of the players could not be found!\n");
                } else{
                    float p1Wins = 0;
                    float p2Wins = 0;

                    for(int i = 0; i < trials; i++){
                        //update the progress bar
                        final double progress = (i+1.0)/trials;
                        Platform.runLater(() -> progressBar.setProgress(progress));

                        //setup a match between these players:
                        Match match = new Match(p1, p2, numSets);
                        match.playMatch(verbose);
                        if(match.didPLayer1Win()){
                            if(printMatchScores){
                                final String text = p1.getName() + " wins!\n";
                                Platform.runLater(() -> outputText.appendText(text));
                            }
                            p1Wins++;
                        } else{
                            if(printMatchScores){
                                final String text = p2.getName() + " wins!\n";
                                Platform.runLater(() -> outputText.appendText(text));
                            }
                            p2Wins++;
                        }

                        if(printMatchScores){
                            final String text = match.score.toString() + "\n";
                            Platform.runLater(() -> outputText.appendText(text));
                        }
                        try{
                            Thread.sleep(5);
                        } catch(InterruptedException ex){
                            System.out.println("Thread sleep was interrupted!  How rude.");
                        }
                    }

                    //print the final results:
                    final String text1 = "Player 1 Wins " + (p1Wins/ trials)*100 + "% of the matches\n";
                    Platform.runLater(() -> outputText.appendText(text1));
                    final String text2 = "Player 2 Wins " + (p2Wins/ trials)*100 + "% of the matches\n";
                    Platform.runLater(() -> outputText.appendText(text2));

                }
            }
        }.start();

    }

}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>ACE whitespace extension Demo</title>
  <link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet">

       Bootswatch

News

Gallery

            Preview

Default

Amelia

Cerulean

Cosmo

Cyborg

Flatly

Journal

Readable

Simplex

Slate

Spacelab

Spruce

Superhero

United

            Download

bootstrap.min.css

bootstrap.css

variables.less

Built With Bootstrap

WrapBootstrap

ace rocks!


text:
BoxParser.mfhdBox.prototype.parse = function(stream) {
	this.parseFullHeader(stream);
	this.sequence_number = stream.readUint32();
}


text:
package com.asakusafw.operation.tools.directio.transaction;

import java.io.PrintWriter;
import java.text.MessageFormat;
import java.time.Instant;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.asakusafw.runtime.directio.hadoop.DirectIoTransactionEditor.TransactionInfo;
import com.asakusafw.utils.jcommander.CommandConfigurationException;
import com.asakusafw.utils.jcommander.common.HelpParameter;
import com.asakusafw.utils.jcommander.common.OutputParameter;
import com.asakusafw.utils.jcommander.common.VerboseParameter;
import com.beust.jcommander.Parameters;
import com.beust.jcommander.ParametersDelegate;

/**
 * A command for printing transaction information.
 * @since 0.10.0
 */
@Parameters(
        commandNames = "show",
        commandDescriptionKey = "command.transaction-show",
        resourceBundle = "com.asakusafw.operation.tools.directio.jcommander"
)
public class TransactionShowCommand implements Runnable {

    static final Logger LOG = LoggerFactory.getLogger(TransactionShowCommand.class);

    @ParametersDelegate
    final HelpParameter helpParameter = new HelpParameter();

    @ParametersDelegate
    final VerboseParameter verboseParameter = new VerboseParameter();

    @ParametersDelegate
    final OutputParameter outputParameter = new OutputParameter();

    @ParametersDelegate
    final TransactionEditorParameter transactionEditorParameter = new TransactionEditorParameter();

    @ParametersDelegate
    final TransactionIdParameter transactionIdParameter = new TransactionIdParameter();

    @Override
    public void run() {
        LOG.debug("starting {}", getClass().getSimpleName());

        String id = transactionIdParameter.getId();
        TransactionInfo spec = transactionEditorParameter.find(id)
                .orElseThrow(() -> new CommandConfigurationException(MessageFormat.format(
                        "transaction \"{0}\" is not found (may be already completed)",
                        id)));

        try (PrintWriter writer = outputParameter.open()) {
            print(writer, spec, 0);
        }
    }

    static void print(PrintWriter writer, TransactionInfo tx, int indent) {
        writer.printf("%sID: %s%n", indent(indent), tx.getExecutionId());
        writer.printf("%sstatus: %s%n", indent(indent), tx.isCommitted() ? "Committed" : "Uncommitted");
        writer.printf("%sdate: %s%n", indent(indent), Instant.ofEpochMilli(tx.getTimestamp()));
        writer.printf("%scomment:%n", indent(indent));
        tx.getComment().forEach(s -> writer.printf("%s> %s%n", indent(indent), s));
    }

    private static CharSequence indent(int level) {
        if (level <= 0) {
            return "";
        }
        StringBuilder buf = new StringBuilder(level);
        for (int i = 0; i < level; i++) {
            buf.append(' ');
        }
        return buf;
    }
}


text:
namespace content {

#if BUILDFLAG(IS_WIN)
// Called in the browser process to ensure the system is set up correctly before
// running web tests.
bool WebTestBrowserCheckLayoutSystemDeps();
#endif

// Called in the browser process to initialize anything platform-specific for
// web tests.
void WebTestBrowserPlatformInitialize();

}  // namespace content

#endif  // CONTENT_WEB_TEST_BROWSER_WEB_TEST_BROWSER_MAIN_PLATFORM_SUPPORT_H_


text:
package com.kuxhausen.huemore.persistence;

import com.google.gson.Gson;

import android.content.ContentValues;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.support.v7.preference.PreferenceManager;
import android.provider.BaseColumns;

import com.kuxhausen.huemore.CommunityDialogFragment;
import com.kuxhausen.huemore.DisableDozeDialogFragment;
import com.kuxhausen.huemore.Helpers;
import com.kuxhausen.huemore.NetworkManagedActivity;
import com.kuxhausen.huemore.R;
import com.kuxhausen.huemore.net.NewConnectionFragment;
import com.kuxhausen.huemore.net.hue.HubData;
import com.kuxhausen.huemore.onboarding.WelcomeDialogFragment;
import com.kuxhausen.huemore.persistence.Definitions.DeprecatedPreferenceKeys;
import com.kuxhausen.huemore.persistence.Definitions.InternalArguments;
import com.kuxhausen.huemore.persistence.Definitions.NetBulbColumns;
import com.kuxhausen.huemore.persistence.Definitions.NetConnectionColumns;
import com.kuxhausen.huemore.persistence.Definitions.PreferenceKeys;

public class PreferenceInitializer {

  public static void initializedPreferencesAndShowDialogs(NetworkManagedActivity act) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(act);
    Gson gson = new Gson();

    if (settings.contains(DeprecatedPreferenceKeys.BRIDGE_IP_ADDRESS)) {
      HubData hubData = new HubData();
      hubData.localHubAddress =
          settings.getString(DeprecatedPreferenceKeys.LOCAL_BRIDGE_IP_ADDRESS, null);
      hubData.portForwardedAddress =
          settings.getString(DeprecatedPreferenceKeys.INTERNET_BRIDGE_IP_ADDRESS, null);
      hubData.hashedUsername = settings.getString(DeprecatedPreferenceKeys.HASHED_USERNAME, null);
      if (hubData.localHubAddress == null) {
        hubData.localHubAddress =
            settings.getString(DeprecatedPreferenceKeys.BRIDGE_IP_ADDRESS, null);
      }

      if (hubData.hashedUsername != null
          && (hubData.localHubAddress != null || hubData.portForwardedAddress != null)) {
        ContentValues connectionValues = new ContentValues();
        connectionValues.put(Definitions.NetConnectionColumns.TYPE_COLUMN,
                             Definitions.NetBulbColumns.NetBulbType.PHILIPS_HUE);
        connectionValues.put(Definitions.NetConnectionColumns.JSON_COLUMN,
                             gson.toJson(hubData));
        long connectionId =
            Long.parseLong(act.getContentResolver()
                               .insert(Definitions.NetConnectionColumns.URI,
                                       connectionValues)
                               .getLastPathSegment());

        // also update any migrated NetBulbs to point to this NetConnection
        ContentValues bulbValues = new ContentValues();
        bulbValues.put(NetBulbColumns.CONNECTION_DATABASE_ID, connectionId);
        act.getContentResolver().update(NetBulbColumns.URI, bulbValues, null, null);
      } else {
        // remove any NetBulbs because there is no NetConnection
        act.getContentResolver().delete(NetBulbColumns.URI, null, null);
      }

      Editor edit = settings.edit();
      edit.remove(DeprecatedPreferenceKeys.LOCAL_BRIDGE_IP_ADDRESS);
      edit.remove(DeprecatedPreferenceKeys.INTERNET_BRIDGE_IP_ADDRESS);
      edit.remove(DeprecatedPreferenceKeys.BRIDGE_IP_ADDRESS);
      edit.remove(DeprecatedPreferenceKeys.HASHED_USERNAME);
      edit.commit();
    }

    if (!settings.contains(PreferenceKeys.FIRST_RUN)) {
      // Mark no longer first run in preferences cache
      Editor edit = settings.edit();
      edit.putBoolean(PreferenceKeys.FIRST_RUN, false);
      edit.commit();
    } else if (settings.getInt(PreferenceKeys.VERSION_NUMBER, -1) < act.getResources().getInteger(
        R.integer.major_update_version)) {
      // TODO show any kind of update release notes, etc
    }
    if (!settings.contains(PreferenceKeys.DEFAULT_TO_GROUPS)) {
      Editor edit = settings.edit();
      edit.putBoolean(PreferenceKeys.DEFAULT_TO_GROUPS, true);
      edit.commit();
    }
    if (!settings.contains(PreferenceKeys.DEFAULT_TO_MOODS)) {
      Editor edit = settings.edit();
      edit.putBoolean(PreferenceKeys.DEFAULT_TO_MOODS, true);
      edit.commit();
    }

    DisableDozeDialogFragment.showDozeOptOutIfNeeded(act);

    // check to see if the bridge IP address is setup yet
    String[] columns = {BaseColumns._ID, NetConnectionColumns.TYPE_COLUMN};
    Cursor cursor =
        act.getContentResolver().query(NetConnectionColumns.URI, columns, null, null, null);
    if (cursor.getCount() <= 0) {
      if (!settings.contains(PreferenceKeys.DONE_WITH_WELCOME_DIALOG)) {
        WelcomeDialogFragment wdf = new WelcomeDialogFragment();
        wdf.show(act.getSupportFragmentManager(), InternalArguments.FRAG_MANAGER_DIALOG_TAG);
      } else {
        NewConnectionFragment dhdf = new NewConnectionFragment();
        dhdf.show(act.getSupportFragmentManager(), InternalArguments.FRAG_MANAGER_DIALOG_TAG);
      }
    } else if (!settings.contains(PreferenceKeys.HAS_SHOWN_COMMUNITY_DIALOG)) {
      CommunityDialogFragment cdf = new CommunityDialogFragment();
      cdf.show(act.getSupportFragmentManager(), InternalArguments.FRAG_MANAGER_DIALOG_TAG);

    }
    cursor.close();

    if (!settings.contains(PreferenceKeys.NUMBER_OF_CONNECTED_BULBS)) {
      Editor edit = settings.edit();
      edit.putInt(PreferenceKeys.NUMBER_OF_CONNECTED_BULBS, 1);
      edit.commit();
    }

    Editor edit = settings.edit();
    try {
      edit.putInt(PreferenceKeys.VERSION_NUMBER,
                  act.getPackageManager().getPackageInfo(act.getPackageName(), 0).versionCode);
    } catch (NameNotFoundException e) {
    }
    edit.commit();

    // Performance optimization, don't re-run setDefaultValues on release builds
    boolean reRunSetDefaultValues = Helpers.isDebugVersion();
    PreferenceManager.setDefaultValues(act, R.xml.settings, reRunSetDefaultValues);
  }
}


text:
const packageJson = require('../../package.json');

export const environment = {
  envName: 'DEV',
  production: false,
  versions: {
    app: packageJson.version,
    angular: packageJson.dependencies['@angular/core'],
    ngrx: packageJson.dependencies['@ngrx/store'],
    material: packageJson.dependencies['@angular/material'],
    bootstrap: packageJson.dependencies.bootstrap,
    rxjs: packageJson.dependencies.rxjs,
    angularCli: packageJson.devDependencies['@angular/cli'],
    typescript: packageJson.devDependencies['typescript']
  }
};


text:
#include "gm.h"

#include "Resources.h"
#include "SkBitmapScaler.h"
#include "SkGradientShader.h"
#include "SkTypeface.h"
#include "SkStream.h"
#include "SkPaint.h"
#include "SkMipMap.h"
#include "Resources.h"
#include "sk_tool_utils.h"

#define SHOW_MIP_COLOR  0xFF000000

static SkBitmap make_bitmap(int w, int h) {
    SkBitmap bm;
    bm.allocN32Pixels(w, h);
    SkCanvas canvas(bm);
    canvas.clear(0xFFFFFFFF);
    SkPaint paint;
    paint.setStyle(SkPaint::kStroke_Style);
    paint.setStrokeWidth(w / 16.0f);
    paint.setColor(SHOW_MIP_COLOR);
    canvas.drawCircle(w/2.0f, h/2.0f, w/3.0f, paint);
    return bm;
}

static SkBitmap make_bitmap2(int w, int h) {
    SkBitmap bm;
    bm.allocN32Pixels(w, h);
    SkCanvas canvas(bm);
    canvas.clear(0xFFFFFFFF);
    SkPaint paint;
    paint.setColor(SHOW_MIP_COLOR);
    paint.setStyle(SkPaint::kStroke_Style);

    SkScalar inset = 2;
    SkRect r = SkRect::MakeIWH(w, h).makeInset(0.5f, 0.5f);
    while (r.width() > 4) {
        canvas.drawRect(r, paint);
        r.inset(inset, inset);
        inset += 1;
    }
    return bm;
}

#include "SkNx.h"
static SkBitmap make_bitmap3(int w, int h) {
    SkBitmap bm;
    bm.allocN32Pixels(w, h);
    SkCanvas canvas(bm);
    canvas.clear(0xFFFFFFFF);
    SkPaint paint;
    paint.setStyle(SkPaint::kStroke_Style);
    paint.setStrokeWidth(2.1f);
    paint.setColor(SHOW_MIP_COLOR);

    SkScalar s = SkIntToScalar(w);
    Sk4f p(s, -s, -s, s);
    Sk4f d(5);
    while (p[1] < s) {
        canvas.drawLine(p[0],p[1], p[2], p[3], paint);
        p = p + d;
    }
    return bm;
}

class ShowMipLevels : public skiagm::GM {
    const int fN;
    SkBitmap  fBM[4];

public:
    static unsigned gamma(unsigned n) {
        float x = n / 255.0f;
#if 0
        x = sqrtf(x);
#else
        if (x > 0.0031308f) {
            x = 1.055f * (powf(x, (1.0f / 2.4f))) - 0.055f;
        } else {
            x = 12.92f * x;
        }
#endif
        return (int)(x * 255);
    }

    static void apply_gamma(const SkBitmap& bm) {
        return; // below is our experiment for sRGB correction
        bm.lockPixels();
        for (int y = 0; y < bm.height(); ++y) {
            for (int x = 0; x < bm.width(); ++x) {
                SkPMColor c = *bm.getAddr32(x, y);
                unsigned r = gamma(SkGetPackedR32(c));
                unsigned g = gamma(SkGetPackedG32(c));
                unsigned b = gamma(SkGetPackedB32(c));
                *bm.getAddr32(x, y) = SkPackARGB32(0xFF, r, g, b);
            }
        }
    }

    ShowMipLevels(int N) : fN(N) {
        fBM[0] = sk_tool_utils::create_checkerboard_bitmap(N, N, SK_ColorBLACK, SK_ColorWHITE, 2);
        fBM[1] = make_bitmap(N, N);
        fBM[2] = make_bitmap2(N, N);
        fBM[3] = make_bitmap3(N, N);
    }

protected:

    SkString onShortName() override {
        SkString str;
        str.printf("showmiplevels_%d", fN);
        return str;
    }

    SkISize onISize() override {
        return { 824, 862 };
    }

    static void DrawAndFrame(SkCanvas* canvas, const SkBitmap& orig, SkScalar x, SkScalar y) {
        SkBitmap bm;
        orig.copyTo(&bm);
        apply_gamma(bm);

        canvas->drawBitmap(bm, x, y, nullptr);
        SkPaint paint;
        paint.setStyle(SkPaint::kStroke_Style);
        paint.setColor(0xFFFFCCCC);
        canvas->drawRect(SkRect::MakeIWH(bm.width(), bm.height()).makeOffset(x, y).makeOutset(0.5f, 0.5f), paint);
    }

    template <typename F> void drawLevels(SkCanvas* canvas, const SkBitmap& baseBM, F func) {
        SkScalar x = 4;
        SkScalar y = 4;

        SkPixmap prevPM;
        baseBM.lockPixels();
        baseBM.peekPixels(&prevPM);

        SkAutoTUnref<SkMipMap> mm(SkMipMap::Build(baseBM, nullptr));

        int index = 0;
        SkMipMap::Level level;
        SkScalar scale = 0.5f;
        while (mm->extractLevel(SkSize::Make(scale, scale), &level)) {
            SkBitmap bm = func(prevPM, level.fPixmap);
            DrawAndFrame(canvas, bm, x, y);

            if (level.fPixmap.width() <= 2 || level.fPixmap.height() <= 2) {
                break;
            }
            if (index & 1) {
                x += level.fPixmap.width() + 4;
            } else {
                y += level.fPixmap.height() + 4;
            }
            scale /= 2;
            prevPM = level.fPixmap;
            index += 1;
        }
    }

    void drawSet(SkCanvas* canvas, const SkBitmap& orig) {
        SkAutoCanvasRestore acr(canvas, true);

        drawLevels(canvas, orig, [](const SkPixmap& prev, const SkPixmap& curr) {
            SkBitmap bm;
            bm.installPixels(curr);
            return bm;
        });

        const SkBitmapScaler::ResizeMethod methods[] = {
            SkBitmapScaler::RESIZE_BOX,
            SkBitmapScaler::RESIZE_TRIANGLE,
            SkBitmapScaler::RESIZE_LANCZOS3,
            SkBitmapScaler::RESIZE_HAMMING,
            SkBitmapScaler::RESIZE_MITCHELL,
        };

        SkPixmap basePM;
        orig.lockPixels();
        orig.peekPixels(&basePM);
        for (auto method : methods) {
            canvas->translate(orig.width()/2 + 8.0f, 0);
            drawLevels(canvas, orig, [basePM, method](const SkPixmap& prev, const SkPixmap& curr) {
                SkBitmap bm;
                SkBitmapScaler::Resize(&bm, prev, method, curr.width(), curr.height());
                return bm;
            });
        }
    }

    void onDraw(SkCanvas* canvas) override {
        canvas->translate(4, 4);
        for (const auto& bm : fBM) {
            this->drawSet(canvas, bm);
            canvas->translate(0, bm.height() * 0.85f);
        }
    }

private:
    typedef skiagm::GM INHERITED;
};
DEF_GM( return new ShowMipLevels(255); )
DEF_GM( return new ShowMipLevels(256); )

///////////////////////////////////////////////////////////////////////////////////////////////////

/**
 *  Show mip levels that were built, for all supported colortypes
 */
class ShowMipLevels2 : public skiagm::GM {
    const int fW, fH;
    SkBitmap  fBM[4];

public:
    ShowMipLevels2(int w, int h) : fW(w), fH(h) {
        fBM[0] = sk_tool_utils::create_checkerboard_bitmap(w, h, SHOW_MIP_COLOR, SK_ColorWHITE, 2);
        fBM[1] = make_bitmap(w, h);
        fBM[2] = make_bitmap2(w, h);
        fBM[3] = make_bitmap3(w, h);
    }

protected:

    SkString onShortName() override {
        SkString str;
        str.printf("showmiplevels2_%dx%d", fW, fH);
        return str;
    }

    SkISize onISize() override {
        return { 824, 862 };
    }

    static void DrawAndFrame(SkCanvas* canvas, const SkBitmap& bm, SkScalar x, SkScalar y) {
        canvas->drawBitmap(bm, x, y, nullptr);
        SkPaint paint;
        paint.setStyle(SkPaint::kStroke_Style);
        paint.setColor(0xFFFFCCCC);
        canvas->drawRect(SkRect::MakeIWH(bm.width(), bm.height()).makeOffset(x, y).makeOutset(0.5f, 0.5f), paint);
    }

    void drawLevels(SkCanvas* canvas, const SkBitmap& baseBM) {
        SkScalar x = 4;
        SkScalar y = 4;

        SkAutoTUnref<SkMipMap> mm(SkMipMap::Build(baseBM, nullptr));

        int index = 0;
        SkMipMap::Level level;
        SkScalar scale = 0.5f;
        while (mm->extractLevel(SkSize::Make(scale, scale), &level)) {
            SkBitmap bm;
            bm.installPixels(level.fPixmap);
            DrawAndFrame(canvas, bm, x, y);

            if (level.fPixmap.width() <= 2 || level.fPixmap.height() <= 2) {
                break;
            }
            if (index & 1) {
                x += level.fPixmap.width() + 4;
            } else {
                y += level.fPixmap.height() + 4;
            }
            scale /= 2;
            index += 1;
        }
    }

    void drawSet(SkCanvas* canvas, const SkBitmap& orig) {
        const SkColorType ctypes[] = {
            kN32_SkColorType, kRGB_565_SkColorType, kARGB_4444_SkColorType, kGray_8_SkColorType
        };

        SkAutoCanvasRestore acr(canvas, true);

        for (auto ctype : ctypes) {
            SkBitmap bm;
            orig.copyTo(&bm, ctype);
            drawLevels(canvas, bm);
            canvas->translate(orig.width()/2 + 8.0f, 0);
        }
    }

    void onDraw(SkCanvas* canvas) override {
        canvas->translate(4, 4);
        for (const auto& bm : fBM) {
            this->drawSet(canvas, bm);
            // round so we always produce an integral translate, so the GOLD tool won't show
            // unimportant diffs if this is drawn on a GPU with different rounding rules
            // since we draw the bitmaps using nearest-neighbor
            canvas->translate(0, SkScalarRoundToScalar(bm.height() * 0.85f));
        }
    }

private:
    typedef skiagm::GM INHERITED;
};
DEF_GM( return new ShowMipLevels2(255, 255); )
DEF_GM( return new ShowMipLevels2(256, 255); )
DEF_GM( return new ShowMipLevels2(255, 256); )
DEF_GM( return new ShowMipLevels2(256, 256); )


text:
package goa

import (
	"fmt"
	"net"
	"net/mail"
	"net/url"
	"regexp"
	"sync"
	"time"

	"github.com/goadesign/goa/uuid"
)

// Format defines a validation format.
type Format string

const (
	// FormatDateTime defines RFC3339 date time values.
	FormatDateTime Format = "date-time"

	// FormatUUID defines RFC4122 uuid values.
	FormatUUID Format = "uuid"

	// FormatEmail defines RFC5322 email addresses.
	FormatEmail = "email"

	// FormatHostname defines RFC1035 Internet host names.
	FormatHostname = "hostname"

	// FormatIPv4 defines RFC2373 IPv4 address values.
	FormatIPv4 = "ipv4"

	// FormatIPv6 defines RFC2373 IPv6 address values.
	FormatIPv6 = "ipv6"

	// FormatIP defines RFC2373 IPv4 or IPv6 address values.
	FormatIP = "ip"

	// FormatURI defines RFC3986 URI values.
	FormatURI = "uri"

	// FormatMAC defines IEEE 802 MAC-48, EUI-48 or EUI-64 MAC address values.
	FormatMAC = "mac"

	// FormatCIDR defines RFC4632 and RFC4291 CIDR notation IP address values.
	FormatCIDR = "cidr"

	// FormatRegexp Regexp defines regular expression syntax accepted by RE2.
	FormatRegexp = "regexp"

	// FormatRFC1123 defines RFC1123 date time values.
	FormatRFC1123 = "rfc1123"
)

var (
	// Regular expression used to validate RFC1035 hostnames*/
	hostnameRegex = regexp.MustCompile(`^[[:alnum:]][[:alnum:]\-]{0,61}[[:alnum:]]|[[:alpha:]]$`)

	// Simple regular expression for IPv4 values, more rigorous checking is done via net.ParseIP
	ipv4Regex = regexp.MustCompile(`^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$`)
)

// ValidateFormat validates a string against a standard format.
// It returns nil if the string conforms to the format, an error otherwise.
// The format specification follows the json schema draft 4 validation extension.
// see http://json-schema.org/latest/json-schema-validation.html#anchor105
// Supported formats are:
//
//     - "date-time": RFC3339 date time value
//     - "email": RFC5322 email address
//     - "hostname": RFC1035 Internet host name
//     - "ipv4", "ipv6", "ip": RFC2673 and RFC2373 IP address values
//     - "uri": RFC3986 URI value
//     - "mac": IEEE 802 MAC-48, EUI-48 or EUI-64 MAC address value
//     - "cidr": RFC4632 and RFC4291 CIDR notation IP address value
//     - "regexp": Regular expression syntax accepted by RE2
//     - "rfc1123": RFC1123 date time value
func ValidateFormat(f Format, val string) error {
	var err error
	switch f {
	case FormatDateTime:
		_, err = time.Parse(time.RFC3339, val)
	case FormatUUID:
		_, err = uuid.FromString(val)
	case FormatEmail:
		_, err = mail.ParseAddress(val)
	case FormatHostname:
		if !hostnameRegex.MatchString(val) {
			err = fmt.Errorf("hostname value '%s' does not match %s",
				val, hostnameRegex.String())
		}
	case FormatIPv4, FormatIPv6, FormatIP:
		ip := net.ParseIP(val)
		if ip == nil {
			err = fmt.Errorf("\"%s\" is an invalid %s value", val, f)
		}
		if f == FormatIPv4 {
			if !ipv4Regex.MatchString(val) {
				err = fmt.Errorf("\"%s\" is an invalid ipv4 value", val)
			}
		}
		if f == FormatIPv6 {
			if ipv4Regex.MatchString(val) {
				err = fmt.Errorf("\"%s\" is an invalid ipv6 value", val)
			}
		}
	case FormatURI:
		_, err = url.ParseRequestURI(val)
	case FormatMAC:
		_, err = net.ParseMAC(val)
	case FormatCIDR:
		_, _, err = net.ParseCIDR(val)
	case FormatRegexp:
		_, err = regexp.Compile(val)
	case FormatRFC1123:
		_, err = time.Parse(time.RFC1123, val)
	default:
		return fmt.Errorf("unknown format %#v", f)
	}
	if err != nil {
		go IncrCounter([]string{"goa", "validation", "error", string(f)}, 1.0)
		return fmt.Errorf("invalid %s value, %s", f, err)
	}
	return nil
}

// knownPatterns records the compiled patterns.
// TBD: refactor all this so that the generated code initializes the map on start to get rid of the
// need for a RW mutex.
var knownPatterns = make(map[string]*regexp.Regexp)

// knownPatternsLock is the mutex used to access knownPatterns
var knownPatternsLock = &sync.RWMutex{}

// ValidatePattern returns an error if val does not match the regular expression p.
// It makes an effort to minimize the number of times the regular expression needs to be compiled.
func ValidatePattern(p string, val string) bool {
	knownPatternsLock.RLock()
	r, ok := knownPatterns[p]
	knownPatternsLock.RUnlock()
	if !ok {
		r = regexp.MustCompile(p) // DSL validation makes sure regexp is valid
		knownPatternsLock.Lock()
		knownPatterns[p] = r
		knownPatternsLock.Unlock()
	}
	return r.MatchString(val)
}


text:
package org.rpmoore.algorist.hashes;

public interface TimedHashTable {
    void put(final String key, final String value, final int time);
    String get(final String key, final int time);
}


text:
from c7n_azure.provider import resources
from c7n_azure.resources.arm import ArmResourceManager

@resources.register('datalake')
class DataLakeStore(ArmResourceManager):

    class resource_type(ArmResourceManager.resource_type):
        service = 'azure.mgmt.datalake.store'
        client = 'DataLakeStoreAccountManagementClient'
        enum_spec = ('accounts', 'list', None)
        default_report_fields = (
            'name',
            'location',
            'resourceGroup'
        )


text:
@class SWDeck;

@interface SWPlayer : NSObject

@property (nonatomic, strong) NSArray *allDecks;
@property (nonatomic, strong) SWDeck *currentDeck;
@property (nonatomic, copy) NSString *playerName;
@property (nonatomic, copy) NSString *playerImageName;

@end


text:
layout: page
title: Land Holdings Executive Retreat
date: 2016-05-24
author: Patrick Horn
tags: weekly links, java
status: published
summary: Vivamus nisi enim, dapibus vitae ornare nec, sagittis in nisi.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 08/17/2019
  endDate: 08/22/2019
  ctyhocn: DUAOKHX
  groupCode: LHER
published: true
---
Suspendisse potenti. Mauris eu lacinia leo. Pellentesque non metus porttitor, vulputate lorem condimentum, tristique felis. Aenean mollis, quam eget pretium bibendum, nibh risus viverra mauris, nec bibendum dui magna in risus. Suspendisse semper sed nisl euismod posuere. Integer gravida, est congue ultricies ultricies, massa diam pharetra mi, sed vestibulum arcu elit mollis justo. Nunc luctus rutrum quam nec mollis. Sed nec hendrerit enim.
Vivamus eleifend eros et purus tempus blandit. Donec vel tempor risus, non gravida magna. Curabitur venenatis arcu ac urna finibus, eu lobortis odio elementum. Nunc tristique consectetur ligula, sit amet hendrerit urna placerat eu. Praesent lectus odio, porta id condimentum eu, luctus id risus. Nulla sapien ligula, fermentum id nulla sed, vehicula egestas ante. Nunc molestie id mauris in tincidunt. Ut in ligula eu metus viverra malesuada. Praesent et orci a felis elementum dictum. Sed id lacinia mi. Nunc nec ante egestas risus pharetra viverra nec vel est. Mauris id condimentum lorem, ac laoreet justo. Vivamus ac dolor at lacus efficitur tincidunt. Duis aliquet vitae risus in rhoncus. Aliquam eu accumsan nisl, sed auctor massa.

* Phasellus id ex ut augue molestie rhoncus
* Nullam a ante sed neque mollis consequat
* Vivamus nec leo volutpat dolor viverra accumsan
* Mauris eu orci et erat accumsan interdum.

Etiam vitae ligula id augue tincidunt sollicitudin. Morbi mattis condimentum turpis mollis mattis. Proin fermentum quam at libero placerat aliquam. Nam et nulla volutpat, euismod orci at, tempor orci. Sed vel purus arcu. Vivamus sit amet faucibus elit. Mauris erat lectus, scelerisque at lobortis vitae, feugiat id arcu. Suspendisse potenti. Sed tempor, eros sit amet ullamcorper bibendum, arcu mauris pharetra justo, ut tincidunt quam tortor eu dui.


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fungi Catalaunici: Contributions à l'étude de la Flore Mycologique de la Catalogne 82 (1933)

#### Original name
Armillaria pinetorum Gillet

### Remarks
null


text:
package de.gishmo.gwt.example.mvp4g2.simpleapplication.client.data.model.dto;

import java.io.Serializable;

public class PersonSearch
  implements Serializable {

  private String name;
  private String city;

  public PersonSearch() {
    super();
  }

  public PersonSearch(String name,
                      String city) {
    super();
    this.name = name;
    this.city = city;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public String getCity() {
    return city;
  }

  public void setCity(String city) {
    this.city = city;
  }
}


text:
ig.module(
    'plusplus.helpers.utilsintersection'
)
    .requires(
        'plusplus.helpers.utilsmath',
        'plusplus.helpers.utilsvector2'
)
    .defines(function() {
        "use strict";

        var _utm = ig.utilsmath;
        var _utv2 = ig.utilsvector2;

        /**
         * Static utilities for intersections.
         * @memberof ig
         * @namespace ig.utilsintersection
         * @author Collin Hover - collinhover.com
         **/
        ig.utilsintersection = {};

        /**
         * Calculates bounds from a position and dimensions.
         * @param {Number} x x position of top left
         * @param {Number} y y position of top left
         * @param {Number} width width
         * @param {Number} height height
         * @param {Object} [bounds] bounding object
         * @returns {Object} bounding object
         * @example
         * // get bounds
         * var bounds = ig.utilsintersection.bounds( 0, 0, 100, 100 );
         * // left
         * bounds.minX;
         * // right
         * bounds.maxX;
         * // top
         * bounds.minY;
         * // bottom
         * bounds.maxY;
         * // width
         * bounds.width;
         * // height
         * bounds.height;
         **/
        ig.utilsintersection.bounds = function(x, y, width, height, bounds) {

            bounds = bounds || {};
            bounds.minX = x;
            bounds.minY = y;
            bounds.maxX = x + width;
            bounds.maxY = y + height;
            bounds.width = width;
            bounds.height = height;

            return bounds;

        };

        /**
         * Calculates bounds from min/max values.
         * @param {Number} minX x position of top left
         * @param {Number} minY y position of top left
         * @param {Number} maxX x position of bottom right
         * @param {Number} maxY y position of bottom right
         * @param {Object} [bounds] bounding object
         * @returns {Object} bounding object
         * @example
         * // get bounds
         * var bounds = ig.utilsintersection.boundsMinMax( 0, 0, 100, 100 );
         * // left
         * bounds.minX;
         * // right
         * bounds.maxX;
         * // top
         * bounds.minY;
         * // bottom
         * bounds.maxY;
         * // width
         * bounds.width;
         * // height
         * bounds.height;
         **/
        ig.utilsintersection.boundsMinMax = function(minX, minY, maxX, maxY, bounds) {

            bounds = bounds || {};
            bounds.minX = minX;
            bounds.minY = minY;
            bounds.maxX = maxX;
            bounds.maxY = maxY;
            bounds.width = maxX - minX;
            bounds.height = maxY - minY;

            return bounds;

        };

        /**
         * Returns bounds from a set of points.
         * Tip: each point should be an object with x and y values.
         * @param {Array} points Array of points.
         * @param {Object} [bounds] bounding object
         * @returns {Object} bounding object
         * @example
         * // get bounds
         * var bounds = ig.utilsintersection.boundsOfPoints( [
         *      {x: 0, y: 0},
         *      {x: 100, y: 0},
         *      {x: 100, y: 100},
         *      {x: 0, y: 100}
         * ]);
         * // left
         * bounds.minX;
         * // right
         * bounds.maxX;
         * // top
         * bounds.minY;
         * // bottom
         * bounds.maxY;
         * // width
         * bounds.width;
         * // height
         * bounds.height;
         **/
        ig.utilsintersection.boundsOfPoints = function(points, bounds) {

            var i, il, point = points[0];
            var minX = point.x;
            var minY = point.y;
            var maxX = point.x;
            var maxY = point.y;

            for (i = 1, il = points.length; i < il; i++) {

                point = points[i];

                if (point.x < minX) minX = point.x;
                else if (point.x > maxX) maxX = point.x;
                if (point.y < minY) minY = point.y;
                else if (point.y > maxY) maxY = point.y;

            }

            bounds = bounds || {};
            bounds.minX = minX;
            bounds.minY = minY;
            bounds.maxX = maxX;
            bounds.maxY = maxY;
            bounds.width = maxX - minX;
            bounds.height = maxY - minY;

            return bounds;

        };

        /**
         * Clones a bounds object, with the addition of optional offset position.
         * @param {Object} boundsSource bounds to clone
         * @param {Number} [offsetX=0] offset x
         * @param {Number} [offsetY=0] offset y
         * @param {Object} [bounds] bounding object
         * @returns {Object} bounding object clone.
         * @see ig.utilsintersection.bounds
         **/
        ig.utilsintersection.boundsClone = function(boundsSource, offsetX, offsetY, bounds) {

            offsetX = offsetX || 0;
            offsetY = offsetY || 0;

            var minX = boundsSource.minX + offsetX;
            var minY = boundsSource.minY + offsetY;
            var maxX = boundsSource.maxX + offsetX;
            var maxY = boundsSource.maxY + offsetY;

            bounds = bounds || {};
            bounds.minX = minX;
            bounds.minY = minY;
            bounds.maxX = maxX;
            bounds.maxY = maxY;
            bounds.width = maxX - minX;
            bounds.height = maxY - minY;

            return bounds;

        };

        /**
         * Copies a bounds object into another bounds object, with the addition of optional offset position and scale.
         * @param {Object} boundsA bounds to copy into
         * @param {Object} boundsB bounds to copy from
         * @param {Number} [offsetX=0] offset x
         * @param {Number} [offsetY=0] offset y
         * @param {Number} [scaleX=1] scale x
         * @param {Number} [scaleY=1] scale y
         * @returns {Object} bounding object based on bounds plus offset
         * @see ig.utilsintersection.bounds
         **/
        ig.utilsintersection.boundsCopy = function(boundsA, boundsB, offsetX, offsetY, scaleX, scaleY) {

            offsetX = offsetX || 0;
            offsetY = offsetY || 0;

            scaleX = scaleX || 1;
            scaleY = scaleY || 1;

            boundsA.minX = boundsB.minX * scaleX + offsetX;
            boundsA.maxX = boundsB.maxX * scaleX + offsetX;
            boundsA.minY = boundsB.minY * scaleY + offsetY;
            boundsA.maxY = boundsB.maxY * scaleY + offsetY;
            boundsA.width = boundsA.maxX - boundsA.minX;
            boundsA.height = boundsA.maxY - boundsA.minY;

            return boundsA;

        };

        /**
         * Copies the horizontal properties of a bounds object into another bounds object, with the addition of optional offset position and scale.
         * @param {Object} boundsA bounds to copy into
         * @param {Object} boundsB bounds to copy from
         * @param {Number} [offsetX=0] offset x
         * @param {Number} [scaleX=1] scale x
         * @returns {Object} bounding object based on bounds plus offset
         * @see ig.utilsintersection.bounds
         **/
        ig.utilsintersection.boundsCopyX = function(boundsA, boundsB, offsetX, scaleX) {

            offsetX = offsetX || 0;
            scaleX = scaleX || 1;

            boundsA.minX = boundsB.minX * scaleX + offsetX;
            boundsA.maxX = boundsB.maxX * scaleX + offsetX;
            boundsA.width = boundsA.maxX - boundsA.minX;

            return boundsA;

        };

        /**
         * Copies the vertical properties of a bounds object into another bounds object, with the addition of optional offset position and scale.
         * @param {Object} boundsA bounds to copy into
         * @param {Object} boundsB bounds to copy from
         * @param {Number} [offsetY=0] offset y
         * @param {Number} [scaleY=1] scale y
         * @returns {Object} bounding object based on bounds plus offset
         * @see ig.utilsintersection.bounds
         **/
        ig.utilsintersection.boundsCopyY = function(boundsA, boundsB, offsetY, scaleY) {

            offsetY = offsetY || 0;
            scaleY = scaleY || 1;

            boundsA.minY = boundsB.minY * scaleY + offsetY;
            boundsA.maxY = boundsB.maxY * scaleY + offsetY;
            boundsA.height = boundsA.maxY - boundsA.minY;

            return boundsA;

        };

        /**
         * Copies bounds after rotated by angle.
         * @param {Object} boundsA bounds to copy into
         * @param {Object} boundsB bounds to rotate
         * @param {Number} angle angle in radians
         * @returns {Object} boundsA
         */
        ig.utilsintersection.boundsCopyRotated = function(boundsA, boundsB, angle) {

            // ensure angle is between PI and -PI

            angle = (angle % _utm.TWOPI);

            if (angle > Math.PI) {

                angle -= _utm.TWOPI;

            } else if (angle < -Math.PI) {

                angle += _utm.TWOPI;

            }

            var cos = Math.cos(angle);
            var sin = Math.sin(angle);

            var width = boundsB.width;
            var height = boundsB.height;

            var hcos = height * cos;
            var wcos = width * cos;
            var hsin = height * sin;
            var wsin = width * sin;

            var minX = boundsB.minX;
            var minY = boundsB.minY;
            var cX = minX + boundsB.width * 0.5;
            var cY = minY + boundsB.height * 0.5;
            var dminX = minX - cX;
            var dminY = minY - cY;
            var x = cX + dminX * cos - dminY * sin;
            var y = cY + dminX * sin + dminY * cos;

            if (angle > 0) {

                if (angle < _utm.HALFPI) {

                    boundsA.minY = y;
                    boundsA.maxY = y + hcos + wsin;
                    boundsA.minX = x - hsin;
                    boundsA.maxX = x + wcos;

                } else {

                    boundsA.minY = y + hcos;
                    boundsA.maxY = y + wsin;
                    boundsA.minX = x - hsin + wcos;
                    boundsA.maxX = x;

                }

            } else {

                if (angle < -_utm.HALFPI) {

                    boundsA.minY = y + wsin;
                    boundsA.maxY = y + hcos;
                    boundsA.minX = x;
                    boundsA.maxX = x + wcos - hsin;

                } else {

                    boundsA.minY = y + wsin + hcos;
                    boundsA.maxY = y;
                    boundsA.minX = x + wcos;
                    boundsA.maxX = x - hsin;

                }

            }

            boundsA.width = boundsA.maxX - boundsA.minX;
            boundsA.height = boundsA.maxY - boundsA.minY;

            return boundsA;

        };

        /**
         * Checks two 2D axis aligned bounding boxes: is A contained by B?
         * @param {Number} aminX A left
         * @param {Number} aminY A top
         * @param {Number} amaxX A right
         * @param {Number} amaxY A bottom
         * @param {Number} bminX B left
         * @param {Number} bminY B top
         * @param {Number} bmaxX B right
         * @param {Number} bmaxY B bottom
         * @returns {Boolean} whether bounds A contains bounds B
         **/
        ig.utilsintersection.AABBContains = function(aminX, aminY, amaxX, amaxY, bminX, bminY, bmaxX, bmaxY) {

            if (aminX >= bminX && amaxX <= bmaxX && aminY >= bminY && amaxY <= bmaxY) {
                return true;
            }

            return false;

        };

        /**
         * Checks two 2D axis aligned bounding boxes: does A intersect B?
         * @param {Number} aminX A left
         * @param {Number} aminY A top
         * @param {Number} amaxX A right
         * @param {Number} amaxY A bottom
         * @param {Number} bminX B left
         * @param {Number} bminY B top
         * @param {Number} bmaxX B right
         * @param {Number} bmaxY B bottom
         * @returns {Boolean} whether bounds intersect
         **/
        ig.utilsintersection.AABBIntersect = function(aminX, aminY, amaxX, amaxY, bminX, bminY, bmaxX, bmaxY) {

            if (amaxX < bminX) return false;
            if (aminX > bmaxX) return false;
            if (amaxY < bminY) return false;
            if (aminY > bmaxY) return false;

            return true;

        };

        /**
         * This is a convenience method to test intersection of two bounding boxes.
         * @param {Object} boundsA bounding object A
         * @param {Object} boundsB bounding object B
         * @returns {Boolean} whether bounds intersect
         * @see ig.utilsintersection.AABBIntersect
         **/
        ig.utilsintersection.boundsIntersect = function(boundsA, boundsB) {

            if (boundsA.maxX < boundsB.minX) return false;
            if (boundsA.minX > boundsB.maxX) return false;
            if (boundsA.maxY < boundsB.minY) return false;
            if (boundsA.minY > boundsB.maxY) return false;

            return true;

        };

        /**
         * This is a convenience method to test intersection of two bounding boxes.
         * @param {Object} bounds bounding object A
         * @param {Number} minX B left
         * @param {Number} minY B top
         * @param {Number} maxX B right
         * @param {Number} maxY B bottom
         * @returns {Boolean} whether bounds intersect
         * @see ig.utilsintersection.AABBIntersect
         **/
        ig.utilsintersection.boundsAABBIntersect = function(bounds, minX, minY, maxX, maxY) {

            if (bounds.maxX < minX) return false;
            if (bounds.minX > maxX) return false;
            if (bounds.maxY < minY) return false;
            if (bounds.minY > maxY) return false;

            return true;

        };

        /**
         * This is a convenience method to test intersection of a point with a bounding box.
         * @param {Number} x point x
         * @param {Number} y point y
         * @param {Number} minX bounds left
         * @param {Number} minY bounds top
         * @param {Number} maxX bounds right
         * @param {Number} maxY bounds bottom
         * @returns {Boolean} whether point is inside bounds
         * @see ig.utilsintersection.AABBIntersect
         **/
        ig.utilsintersection.pointInAABB = function(x, y, minX, minY, maxX, maxY) {

            if (x < minX) return false;
            if (x > maxX) return false;
            if (y < minY) return false;
            if (y > maxY) return false;

            return true;

        };

        /**
         * This is a convenience method to test intersection of a point with a bounding box.
         * @param {Number} x point x
         * @param {Number} y point y
         * @param {Object} bounds bounding object
         * @returns {Boolean} whether point is inside bounds
         * @see ig.utilsintersection.AABBIntersect
         **/
        ig.utilsintersection.pointInBounds = function(x, y, bounds) {

            if (x < bounds.minX) return false;
            if (x > bounds.maxX) return false;
            if (y < bounds.minY) return false;
            if (y > bounds.maxY) return false;

            return true;

        };

        /**
         * Checks if a point lies inside or on the edge of a circle.
         * @param {Number} x point x
         * @param {Number} y point y
         * @param {Number} cx center x of circle
         * @param {Number} cy center y of circle
         * @param {Number} radius radius of circle
         * @returns {Boolean} whether point is inside circle
         **/
        ig.utilsintersection.pointInCircle = function(x, y, cx, cy, radius) {

            var dx = cx - x;
            var dy = cy - y;
            var squareDistance = dx * dx + dy * dy;
            var squareRadius = radius * radius;

            return squareDistance < squareRadius;

        };

        /**
         Determine if a point is inside a polygon.
         * @param {Number} x point x
         * @param {Number} y point y
         * @param {Array} vertices array of vertices that defines a polygon
         * @returns {Boolean} true if polygon contains the given point
         **/
        ig.utilsintersection.pointInPolygon = function(x, y, vertices) {

            var i, j = vertices.length - 1;
            var oddNodes = false;

            for (i = 0; i < vertices.length; i++) {

                var va = vertices[j];
                var vb = vertices[i];

                // point is a vertex in polygon

                if ((va.x === x && va.y === y) || (vb.x === x && vb.y === y)) {

                    oddNodes = true;
                    break;

                }
                // raycast edges
                // odd number of crosses = inside polygon
                else if ((vb.y < y && va.y >= y || va.y < y && vb.y >= y) && (vb.x <= x || va.x <= x)) {

                    if (vb.x + (y - vb.y) / (va.y - vb.y) * (va.x - vb.x) < x) {

                        oddNodes = !oddNodes;

                    }

                }

                j = i;

            }

            return oddNodes;

        };

        /**
         * Finds all entities intersecting an axis aligned bounding box in world space coordinates.
         * @param {Number} minX left position.
         * @param {Number} minY top position.
         * @param {Number} maxX right position.
         * @param {Number} maxY bottom position.
         * @param {Boolean} [targetable] only find entities that are targetable.
         * @param {Object} [layerName] name of layer to search.
         * @param {Boolean} [unsorted] whether to sort.
         * @returns {Array} list of all entities intersecting box.
         */
        ig.utilsintersection.entitiesInAABB = function(minX, minY, maxX, maxY, targetable, layerName, unsorted) {

            var intersected = [];
            var layer;
            var i, il;

            if (!layerName) {

                for (i = 0, il = ig.game.layers.length; i < il; i++) {

                    layer = ig.game.layers[i];

                    if (layer.name && layer.numEntities && (!targetable || layer.itemsTargetable.length)) {

                        intersected = intersected.concat(ig.utilsintersection.entitiesInAABB(minX, minY, maxX, maxY, targetable, layer.name, true));

                    }

                }

            } else {

                layer = ig.game.layersMap[layerName];
                var entities = targetable ? layer.itemsTargetable : layer.items;

                // find if touch intersects bounding box of each entity

                for (i = 0, il = entities.length; i < il; i++) {

                    var entity = entities[i];
                    var intersects;

                    // fixed element bounds should not be relative to world space
                    // so we need to offset it by screen

                    if (entity.fixed) {

                        var screenX = ig.game.screen.x;
                        var screenY = ig.game.screen.y;

                        intersects = ig.utilsintersection.AABBIntersect(
                            entity.pos.x + screenX, entity.pos.y + screenY, entity.pos.x + (entity.size.x * entity.scaleMod) + screenX, entity.pos.y + (entity.size.y * entity.scaleMod) + screenY,
                            minX, minY, maxX, maxY
                        );

                    } else {

                        intersects = ig.utilsintersection.AABBIntersect(
                            entity.pos.x, entity.pos.y, entity.pos.x + (entity.size.x * entity.scaleMod), entity.pos.y + (entity.size.y * entity.scaleMod),
                            minX, minY, maxX, maxY
                        );

                    }

                    if (intersects) {

                        intersected.push(entity);

                    }

                }

            }

            // sort by distance from center of aabb

            if (intersected.length > 1 && !unsorted) {

                ig.utilsintersection.sortByDistance(minX + (maxX - minX) * 0.5, minY + (maxY - minY) * 0.5, intersected);

            }

            return intersected;

        };

        /**
         * Gets if an axis aligned bounding box is in the screen.
         * @param {Number} x bounds top left x position
         * @param {Number} y bounds top left y position
         * @param {Number} width bounds width
         * @param {Number} height bounds height
         * @returns {Boolean} whether bounds is in screen
         **/
        ig.utilsintersection.getIsAABBInScreen = function(x, y, width, height) {

            var adjustedX = x - ig.game.screen.x;
            var adjustedY = y - ig.game.screen.y;

            return ig.utilsintersection.AABBIntersect(adjustedX, adjustedY, adjustedX + width, adjustedY + height, 0, 0, ig.system.width, ig.system.height);

        };

        /**
         * Sort a list of entities by distance to a point in world space coordinates.
         * IMPORTANT: this modifies the array in place.
         * @param {Number} x x position
         * @param {Number} y y position
         * @param {Array} entities list of entities
         * @returns {Array} list of entities modified in place.
         **/
        ig.utilsintersection.sortByDistance = function(x, y, entities) {

            var pos = _utv2.set(ig.utilsintersection._utilVec2Sort, x, y);

            entities.sort(function(a, b) {

                var aDistance = a.distanceSquaredEdgeTo(pos);
                var bDistance = b.distanceSquaredEdgeTo(pos);

                return aDistance - bDistance || a.distanceSquaredTo(pos) - b.distanceSquaredTo(pos);

            });

            return entities;

        };

        ig.utilsintersection._utilVec2Sort = {
            x: 0.1,
            y: 0.1
        };

    });


text:
<!DOCTYPE html>

	<meta charset="utf-8">

	<title>BRRelutionScanConfigLoader Protocol Reference</title>

	<link rel="stylesheet" href="../css/style.css">
	<meta name="viewport" content="initial-scale=1, maximum-scale=1.4">
	<meta name="generator" content="appledoc 2.2.1 (build 1334)">

				BlueRange SDK

				M-Way Solutions GmbH

Index

Hierarchy

							On This Page

							<select id="jump-to">
	<option value="top">Jump To…</option>

	<option value="tasks">Tasks</option>

	<optgroup label="Instance Methods">

		<option value="//api/name/start">- start</option>

		<option value="//api/name/stop">- stop</option>

	</optgroup>

</select>

BRRelutionScanConfigLoader Protocol Reference

	Declared in
	BRRelutionScanConfigLoader.h

– start
required method

- (void)start

– stop
required method

- (void)stop

Copyright © 2017 M-Way Solutions GmbH. All rights reserved. Updated: 2017-09-15

Generated by appledoc 2.2.1 (build 1334).