text:
layout: post
title:  "Pixie Pi"
excerpt: "Installing Pixie, a Clojure-inspired Lisp, on the Raspberry Pi"
date:   2015-05-05 12:36:00
categories: pixie
tags: pixie clojure
---

[Pixie](https://github.com/pixie-lang/pixie) is a Clojure-inspired lisp that has a quick startup time and [nice FFI support](https://github.com/pixie-lang/pixie/wiki/FFI-(interop-with-C)) that allows it to make use of existing C libraries, making it a nice option for working with the Raspberry Pi.

## Installing Pixie

#### Meeting Dependencies

From a base Raspbian install, [Pixie's dependencies](https://github.com/pixie-lang/pixie#dependencies) (as of eb5886ff95) except for `libuv-dev` can be satisfied using `aptitude`

`sudo apt-get install libffi-dev libedit-dev libboost-all-dev`

`libuv-dev` (and `libuv`) are available from the [Jesse packages](https://packages.debian.org/jessie/libuv0.10-dev). Use the armhf builds.

  * [libuv](https://packages.debian.org/jessie/armhf/libuv0.10/download)
  * [libuv-dev](https://packages.debian.org/jessie/armhf/libuv0.10-dev/download)

Use `wget` to grab the packages and install with

{% highlight sh %}
sudo dpkg -i libuv*armhf.deb
{% endhighlight %}
#### Building the Pixie VM

`make build_no_jit`

It'll run for about an hour. Enjoy the excellent ascii art the RPython build process produces.

Cross compilation from a faster machine may be an option as well.

## Interfacing with the Raspberry Pi's GPIO

Using Pixie's FFI, I made a [library called wiringPixie](https://github.com/stuarth/wiringPixie) wrapping [wiringPi](http://wiringpi.com). Follow the instructions on the README to install

[https://github.com/stuarth/wiringPixie](https://github.com/stuarth/wiringPixie)

and start hacking (or controlling LEDs :))

{% highlight clojure %}
(require wiring-pixie.gpio :refer :all)

(def pin 7)

(wiringPiSetup)         ;; required first!
(pinMode pin OUTPUT)    ;; pin to OUTPUT
(digitalWrite pin HIGH) ;; set pin 7 to HIGH
{% endhighlight %}


text:
<?xml version="1.0" encoding="UTF-8"?>
<estimates type="array">
  <estimate>
    <link rel="self" href="http://apicashboard.i/estimates/80170468"/>
    <link rel="toggle_status" href="http://apicashboard.i/estimates/80170468/toggle_status"/>
    <link rel="line_items" href="http://apicashboard.i/estimates/80170468/line_items"/>
    <id>80170468</id>
    <assigned_id>CLOSED-1</assigned_id>
    <agreement_text></agreement_text>
    <client_id>760501033</client_id>
    <client_type>Company</client_type>
    <created_on>2010-07-28 21:10:00</created_on>
    <deposit_amount rel="financial">50.00</deposit_amount>
    <discount_percentage rel="financial"></discount_percentage>
    <document_template_id></document_template_id>
    <has_been_sent>true</has_been_sent>
    <intro_text></intro_text>
    <is_active read_only="true">false</is_active>
    <name>Old and crusty Estimate</name>
    <requires_agreement>true</requires_agreement>
    <sales_tax rel="financial"></sales_tax>
    <sales_tax_2 rel="financial"></sales_tax_2>
    <sales_tax_2_cumulative rel="financial">false</sales_tax_2_cumulative>
    <discount_best read_only="true" rel="financial">-0.0</discount_best>
    <discount_worst read_only="true" rel="financial">-0.0</discount_worst>
    <item_actual_best read_only="true" rel="financial">0.0</item_actual_best>
    <item_actual_worst read_only="true" rel="financial">0.0</item_actual_worst>
    <item_cost_best read_only="true" rel="financial">0.0</item_cost_best>
    <item_cost_worst read_only="true" rel="financial">0.0</item_cost_worst>
    <item_profit_best read_only="true" rel="financial">0.0</item_profit_best>
    <item_profit_worst read_only="true" rel="financial">0.0</item_profit_worst>
    <item_taxable_best read_only="true" rel="financial">0.0</item_taxable_best>
    <item_taxable_worst read_only="true" rel="financial">0.0</item_taxable_worst>
    <price_best read_only="true" rel="financial">0.0</price_best>
    <price_worst read_only="true" rel="financial">0.0</price_worst>
    <tax_cost_best read_only="true" rel="financial">0.0</tax_cost_best>
    <tax_cost_worst read_only="true" rel="financial">0.0</tax_cost_worst>
    <tax_cost_2_best read_only="true" rel="financial">0.0</tax_cost_2_best>
    <tax_cost_2_worst read_only="true" rel="financial">0.0</tax_cost_2_worst>
    <time_best read_only="true">00</time_best>
    <time_worst read_only="true">00</time_worst>
  </estimate>
  <estimate>
    <link rel="self" href="http://apicashboard.i/estimates/112106857"/>
    <link rel="toggle_status" href="http://apicashboard.i/estimates/112106857/toggle_status"/>
    <link rel="line_items" href="http://apicashboard.i/estimates/112106857/line_items"/>
    <id>112106857</id>
    <assigned_id>PERSONAL-1</assigned_id>
    <agreement_text></agreement_text>
    <client_id>121898072</client_id>
    <client_type>Person</client_type>
    <created_on>2010-07-28 21:10:00</created_on>
    <deposit_amount rel="financial">0.00</deposit_amount>
    <discount_percentage rel="financial"></discount_percentage>
    <document_template_id></document_template_id>
    <has_been_sent>true</has_been_sent>
    <intro_text></intro_text>
    <is_active read_only="true">true</is_active>
    <name>A personal estimate for one person</name>
    <requires_agreement>true</requires_agreement>
    <sales_tax rel="financial"></sales_tax>
    <sales_tax_2 rel="financial"></sales_tax_2>
    <sales_tax_2_cumulative rel="financial">false</sales_tax_2_cumulative>
    <discount_best read_only="true" rel="financial">-0.0</discount_best>
    <discount_worst read_only="true" rel="financial">-0.0</discount_worst>
    <item_actual_best read_only="true" rel="financial">0.0</item_actual_best>
    <item_actual_worst read_only="true" rel="financial">0.0</item_actual_worst>
    <item_cost_best read_only="true" rel="financial">0.0</item_cost_best>
    <item_cost_worst read_only="true" rel="financial">0.0</item_cost_worst>
    <item_profit_best read_only="true" rel="financial">0.0</item_profit_best>
    <item_profit_worst read_only="true" rel="financial">0.0</item_profit_worst>
    <item_taxable_best read_only="true" rel="financial">0.0</item_taxable_best>
    <item_taxable_worst read_only="true" rel="financial">0.0</item_taxable_worst>
    <price_best read_only="true" rel="financial">0.0</price_best>
    <price_worst read_only="true" rel="financial">0.0</price_worst>
    <tax_cost_best read_only="true" rel="financial">0.0</tax_cost_best>
    <tax_cost_worst read_only="true" rel="financial">0.0</tax_cost_worst>
    <tax_cost_2_best read_only="true" rel="financial">0.0</tax_cost_2_best>
    <tax_cost_2_worst read_only="true" rel="financial">0.0</tax_cost_2_worst>
    <time_best read_only="true">00</time_best>
    <time_worst read_only="true">00</time_worst>
  </estimate>
  <estimate>
    <link rel="self" href="http://apicashboard.i/estimates/200482051"/>
    <link rel="toggle_status" href="http://apicashboard.i/estimates/200482051/toggle_status"/>
    <link rel="line_items" href="http://apicashboard.i/estimates/200482051/line_items"/>
    <id>200482051</id>
    <assigned_id>0000002</assigned_id>
    <agreement_text></agreement_text>
    <client_id>695681551</client_id>
    <client_type>Company</client_type>
    <created_on>2010-07-28 21:10:00</created_on>
    <deposit_amount rel="financial">0.00</deposit_amount>
    <discount_percentage rel="financial"></discount_percentage>
    <document_template_id></document_template_id>
    <has_been_sent>false</has_been_sent>
    <intro_text></intro_text>
    <is_active read_only="true">true</is_active>
    <name>An internal estimate</name>
    <requires_agreement>true</requires_agreement>
    <sales_tax rel="financial"></sales_tax>
    <sales_tax_2 rel="financial"></sales_tax_2>
    <sales_tax_2_cumulative rel="financial">false</sales_tax_2_cumulative>
    <discount_best read_only="true" rel="financial">-0.0</discount_best>
    <discount_worst read_only="true" rel="financial">-0.0</discount_worst>
    <item_actual_best read_only="true" rel="financial">0.0</item_actual_best>
    <item_actual_worst read_only="true" rel="financial">0.0</item_actual_worst>
    <item_cost_best read_only="true" rel="financial">0.0</item_cost_best>
    <item_cost_worst read_only="true" rel="financial">0.0</item_cost_worst>
    <item_profit_best read_only="true" rel="financial">0.0</item_profit_best>
    <item_profit_worst read_only="true" rel="financial">0.0</item_profit_worst>
    <item_taxable_best read_only="true" rel="financial">0.0</item_taxable_best>
    <item_taxable_worst read_only="true" rel="financial">0.0</item_taxable_worst>
    <price_best read_only="true" rel="financial">0.0</price_best>
    <price_worst read_only="true" rel="financial">0.0</price_worst>
    <tax_cost_best read_only="true" rel="financial">0.0</tax_cost_best>
    <tax_cost_worst read_only="true" rel="financial">0.0</tax_cost_worst>
    <tax_cost_2_best read_only="true" rel="financial">0.0</tax_cost_2_best>
    <tax_cost_2_worst read_only="true" rel="financial">0.0</tax_cost_2_worst>
    <time_best read_only="true">00</time_best>
    <time_worst read_only="true">00</time_worst>
  </estimate>
  <estimate>
    <link rel="self" href="http://apicashboard.i/estimates/296221756"/>
    <link rel="toggle_status" href="http://apicashboard.i/estimates/296221756/toggle_status"/>
    <link rel="line_items" href="http://apicashboard.i/estimates/296221756/line_items"/>
    <id>296221756</id>
    <assigned_id>NO-ASSOC-PROJECT</assigned_id>
    <agreement_text></agreement_text>
    <client_id>438872084</client_id>
    <client_type>Company</client_type>
    <created_on>2010-07-28 21:10:00</created_on>
    <deposit_amount rel="financial">0.00</deposit_amount>
    <discount_percentage rel="financial"></discount_percentage>
    <document_template_id></document_template_id>
    <has_been_sent>true</has_been_sent>
    <intro_text></intro_text>
    <is_active read_only="true">true</is_active>
    <name>Estimate with no project</name>
    <requires_agreement>true</requires_agreement>
    <sales_tax rel="financial"></sales_tax>
    <sales_tax_2 rel="financial"></sales_tax_2>
    <sales_tax_2_cumulative rel="financial">false</sales_tax_2_cumulative>
    <discount_best read_only="true" rel="financial">-0.0</discount_best>
    <discount_worst read_only="true" rel="financial">-0.0</discount_worst>
    <item_actual_best read_only="true" rel="financial">1340.0</item_actual_best>
    <item_actual_worst read_only="true" rel="financial">2120.0</item_actual_worst>
    <item_cost_best read_only="true" rel="financial">1340.0</item_cost_best>
    <item_cost_worst read_only="true" rel="financial">2120.0</item_cost_worst>
    <item_profit_best read_only="true" rel="financial">0.0</item_profit_best>
    <item_profit_worst read_only="true" rel="financial">0.0</item_profit_worst>
    <item_taxable_best read_only="true" rel="financial">0.0</item_taxable_best>
    <item_taxable_worst read_only="true" rel="financial">0.0</item_taxable_worst>
    <price_best read_only="true" rel="financial">1340.0</price_best>
    <price_worst read_only="true" rel="financial">2120.0</price_worst>
    <tax_cost_best read_only="true" rel="financial">0.0</tax_cost_best>
    <tax_cost_worst read_only="true" rel="financial">0.0</tax_cost_worst>
    <tax_cost_2_best read_only="true" rel="financial">0.0</tax_cost_2_best>
    <tax_cost_2_worst read_only="true" rel="financial">0.0</tax_cost_2_worst>
    <time_best read_only="true">220</time_best>
    <time_worst read_only="true">350</time_worst>
  </estimate>
  <estimate>
    <link rel="self" href="http://apicashboard.i/estimates/317862090"/>
    <link rel="toggle_status" href="http://apicashboard.i/estimates/317862090/toggle_status"/>
    <link rel="line_items" href="http://apicashboard.i/estimates/317862090/line_items"/>
    <id>317862090</id>
    <assigned_id>0000001</assigned_id>
    <agreement_text></agreement_text>
    <client_id>760501033</client_id>
    <client_type>Company</client_type>
    <created_on>2010-07-28 21:10:00</created_on>
    <deposit_amount rel="financial">50.00</deposit_amount>
    <discount_percentage rel="financial"></discount_percentage>
    <document_template_id></document_template_id>
    <has_been_sent>false</has_been_sent>
    <intro_text></intro_text>
    <is_active read_only="true">true</is_active>
    <name>Auctions Redesign</name>
    <requires_agreement>true</requires_agreement>
    <sales_tax rel="financial"></sales_tax>
    <sales_tax_2 rel="financial"></sales_tax_2>
    <sales_tax_2_cumulative rel="financial">false</sales_tax_2_cumulative>
    <discount_best read_only="true" rel="financial">-0.0</discount_best>
    <discount_worst read_only="true" rel="financial">-0.0</discount_worst>
    <item_actual_best read_only="true" rel="financial">2640.0</item_actual_best>
    <item_actual_worst read_only="true" rel="financial">2640.0</item_actual_worst>
    <item_cost_best read_only="true" rel="financial">2640.0</item_cost_best>
    <item_cost_worst read_only="true" rel="financial">2640.0</item_cost_worst>
    <item_profit_best read_only="true" rel="financial">0.0</item_profit_best>
    <item_profit_worst read_only="true" rel="financial">0.0</item_profit_worst>
    <item_taxable_best read_only="true" rel="financial">1440.0</item_taxable_best>
    <item_taxable_worst read_only="true" rel="financial">1440.0</item_taxable_worst>
    <price_best read_only="true" rel="financial">2640.0</price_best>
    <price_worst read_only="true" rel="financial">2640.0</price_worst>
    <tax_cost_best read_only="true" rel="financial">0.0</tax_cost_best>
    <tax_cost_worst read_only="true" rel="financial">0.0</tax_cost_worst>
    <tax_cost_2_best read_only="true" rel="financial">0.0</tax_cost_2_best>
    <tax_cost_2_worst read_only="true" rel="financial">0.0</tax_cost_2_worst>
    <time_best read_only="true">240</time_best>
    <time_worst read_only="true">240</time_worst>
  </estimate>
  <estimate>
    <link rel="self" href="http://apicashboard.i/estimates/660985040"/>
    <link rel="toggle_status" href="http://apicashboard.i/estimates/660985040/toggle_status"/>
    <link rel="line_items" href="http://apicashboard.i/estimates/660985040/line_items"/>
    <id>660985040</id>
    <assigned_id>SURVIVAL-1</assigned_id>
    <agreement_text></agreement_text>
    <client_id>438872084</client_id>
    <client_type>Company</client_type>
    <created_on>2010-07-28 21:10:00</created_on>
    <deposit_amount rel="financial">0.00</deposit_amount>
    <discount_percentage rel="financial"></discount_percentage>
    <document_template_id></document_template_id>
    <has_been_sent>true</has_been_sent>
    <intro_text></intro_text>
    <is_active read_only="true">true</is_active>
    <name>Surviving the wild - 2 weeks</name>
    <requires_agreement>true</requires_agreement>
    <sales_tax rel="financial"></sales_tax>
    <sales_tax_2 rel="financial"></sales_tax_2>
    <sales_tax_2_cumulative rel="financial">false</sales_tax_2_cumulative>
    <discount_best read_only="true" rel="financial">-0.0</discount_best>
    <discount_worst read_only="true" rel="financial">-0.0</discount_worst>
    <item_actual_best read_only="true" rel="financial">0.0</item_actual_best>
    <item_actual_worst read_only="true" rel="financial">0.0</item_actual_worst>
    <item_cost_best read_only="true" rel="financial">0.0</item_cost_best>
    <item_cost_worst read_only="true" rel="financial">0.0</item_cost_worst>
    <item_profit_best read_only="true" rel="financial">0.0</item_profit_best>
    <item_profit_worst read_only="true" rel="financial">0.0</item_profit_worst>
    <item_taxable_best read_only="true" rel="financial">0.0</item_taxable_best>
    <item_taxable_worst read_only="true" rel="financial">0.0</item_taxable_worst>
    <price_best read_only="true" rel="financial">0.0</price_best>
    <price_worst read_only="true" rel="financial">0.0</price_worst>
    <tax_cost_best read_only="true" rel="financial">0.0</tax_cost_best>
    <tax_cost_worst read_only="true" rel="financial">0.0</tax_cost_worst>
    <tax_cost_2_best read_only="true" rel="financial">0.0</tax_cost_2_best>
    <tax_cost_2_worst read_only="true" rel="financial">0.0</tax_cost_2_worst>
    <time_best read_only="true">00</time_best>
    <time_worst read_only="true">00</time_worst>
  </estimate>
</estimates>

redpajama_set_name: RedPajamaGithub


text:
//
//  LShowListsTableViewController.m
//  Lists
//
//  Created by Nikhil Kalra on 6/18/14.
//  Copyright (c) 2014 Nikhil Kalra. All rights reserved.
//

#import "LShowListsTableViewController.h"
#import "List.h"
#import "Item.h"
#import "UIImage+Color.h"
#import "LListTableViewController.h"
#import "UIImage+Text.h"
#import "EditableTableViewCell.h"
#import "LCommon.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>

@interface LShowListsTableViewController () <EditableTableViewCellDelegate, LListSplitViewControllerDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (nonatomic, strong) NSMutableArray *lists;
@property (nonatomic, strong) NSTimer *savingTimer;
@property (nonatomic, assign) BOOL newCellShouldAllowEditing;
@property (nonatomic, weak) EditableTableViewCell *cellForEditing;
@property (nonatomic, strong) LListTableViewController *detailVC;
@property (nonatomic, strong) EditableTableViewCell *selectedCell;
@property (nonatomic, assign) BOOL emptyViewShouldUseOffset;
@end

@implementation LShowListsTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    self.navigationItem.leftBarButtonItem = self.editButtonItem;

    // empty table stuff
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;

    [self.tableView setSeparatorInset:UIEdgeInsetsZero];

    self.detailVC = (LListTableViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
    if (self.detailVC) [self.detailVC setSplitVCDelegate:self];

    // google analytics
    // May return nil if a tracker has not already been initialized with a
    // property ID.
    id tracker = [[GAI sharedInstance] defaultTracker];

    // This screen name value will remain set on the tracker and sent with
    // hits until it is set to a new value or to nil.
    [tracker set:kGAIScreenName value:@"Show Lists VC"];

    [tracker send:[[GAIDictionaryBuilder createAppView] build]];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    // load lists
    self.lists = [self reloadLists];
//    if (self.lists.count == 0) {
//        // create new empty list
//        [self persistNewListWithName:@"Empty List"];
//    }

    if (self.lists.count == 0) { self.emptyViewShouldUseOffset = YES; [self.tableView reloadData]; }
    else self.emptyViewShouldUseOffset = NO;

    // auto-select first item if ipad
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && self.lists.count > 0) {
        NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionTop];
        [self tableView:self.tableView didSelectRowAtIndexPath:path];
    }

    // setup saving timer - saves every 5 seconds
    self.savingTimer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:YES];
    [self.savingTimer setTolerance:self.savingTimer.timeInterval / 10.f];
    [[NSRunLoop currentRunLoop] addTimer:self.savingTimer forMode:NSDefaultRunLoopMode];

    // restore bar tint color if not ipad
    if (UI_USER_INTERFACE_IDIOM() != UIUserInterfaceIdiomPad) {
        self.navigationController.navigationBar.tintColor = nil;
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor]};
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    // invalidate timer
    [self.savingTimer invalidate];
    self.savingTimer = nil;

    [self.selectedCell.listText resignFirstResponder];
    [self.cellForEditing.listText resignFirstResponder];

    [self saveList];

    [super viewWillDisappear:animated];
}

- (void)setLists:(NSMutableArray *)lists
{
    if (_lists != lists) { _lists = lists; [self.tableView reloadData]; }
}

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    if (!editing && self.cellForEditing) [self.cellForEditing.listText resignFirstResponder];

    [super setEditing:editing animated:animated];

    if (!editing) {
        // auto-select first item if ipad
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && self.lists.count > 0) {
            NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
            [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionTop];
            [self tableView:self.tableView didSelectRowAtIndexPath:path];
        } else {
            [self.detailVC setList:nil];
            // set tint color
            UIColor *tintColor = nil;
            self.navigationController.navigationBar.tintColor = tintColor;
            self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor]};
        }
    }
}

#pragma mark - List Methods

- (void)persistNewListWithName:(NSString *)name
{
    List *newList = [List MR_createEntity];
    newList.name = name;
    newList.color = [NSKeyedArchiver archivedDataWithRootObject:[LCommon colorForItemCount:(int)(self.lists.count + 1)]];
    newList.position = @(0);

    self.newCellShouldAllowEditing = YES;
    [self.tableView reloadData];

    // add to array
    [self.lists insertObject:newList atIndex:0];
    // add to tableview
    NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationAutomatic];
    // save
    [self persistNewListOrders];

    // get the cell
    EditableTableViewCell *cell = (EditableTableViewCell *)[self.tableView cellForRowAtIndexPath:path];
    // show first responder
    self.cellForEditing = cell;
    [cell.listText becomeFirstResponder];

    self.emptyViewShouldUseOffset = NO;
}

- (void)deleteList:(List *)list
{
    [self.lists removeObject:list];
    [list MR_deleteEntity];
    [self persistNewListOrders];

    // auto-select first item if ipad
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && self.lists.count > 0) {
        NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionTop];
        [self tableView:self.tableView didSelectRowAtIndexPath:path];
    } else {
        [self.detailVC setList:nil];
        // set tint color
        UIColor *tintColor = nil;
        self.navigationController.navigationBar.tintColor = tintColor;
        self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor]};
    }
}

- (void)persistNewListOrders
{
    [self.lists enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        List *list = (List *)obj;
        list.position = @(idx);
    }];
}

- (NSMutableArray *)reloadLists
{
    NSMutableArray *lists = [[List MR_findAllSortedBy:@"position" ascending:YES] mutableCopy];
    if (!lists) return [[NSMutableArray alloc] init];

    return lists;
}

- (void)timerFireMethod:(NSTimer *)timer
{
    [self saveList];
}

- (void)saveList
{
    // save to database
    DDLogWarn(@"Saving to database now!");
    [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if (error) DDLogError(@"Error: %@", error);
        if (success) DDLogWarn(@"Successfully saved to database at %@", [NSDate date]);
    }];
}

- (void)refreshItemCounts
{
    [self.tableView reloadData];
    if (self.selectedCell) {
        NSIndexPath *path = [self.tableView indexPathForCell:self.selectedCell];
        [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
}

- (void)setNavBarColor:(UIColor *)color
{
    self.navigationController.navigationBar.barTintColor = color;
}

- (void)setTintColor:(UIColor *)color
{
    self.navigationController.navigationBar.tintColor = color;
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : color};
}

#pragma mark - UI Methods

- (IBAction)addNewList:(id)sender
{
//    NSString *name = [NSString stringWithFormat:@"Test List #%lu", self.lists.count + 1];
//    [self persistNewListWithName:name];

//    UIAlertView *nameAlert = [[UIAlertView alloc] initWithTitle:@"List Name" message:@"What would you like to call the list?" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
//    nameAlert.alertViewStyle = UIAlertViewStylePlainTextInput;
//    [nameAlert show];

    BOOL isValid = NO;
    [LCommon cleanString:self.cellForEditing.listText.text isValid:&isValid];

    if (isValid) [self.selectedCell.listText resignFirstResponder];
    if (!self.newCellShouldAllowEditing) [self persistNewListWithName:@""];
}

//- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
//{
//    if (buttonIndex != 1) return; // return if ok was not pressed
//
//    NSString *input = [alertView textFieldAtIndex:0].text;
//    BOOL isValid = NO;
//    NSString *name = [self cleanString:input isValid:&isValid];
//
//    if (isValid) [self persistNewListWithName:name];
//    else [self persistNewListWithName:[NSString stringWithFormat:@"Unnamed List %lu", (unsigned long)self.lists.count + 1]];
//}

- (void)tableViewCell:(EditableTableViewCell *)cell withTextField:(UITextField *)textField didSetListText:(NSString *)text
{
    DDLogVerbose(@"Resigned");
    self.cellForEditing = nil;
    self.newCellShouldAllowEditing = NO;

    // get cell position
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    int index = (int)indexPath.row;

    if (index > self.lists.count || indexPath == nil) {[self.tableView reloadData]; return;}
    List *list = [self.lists objectAtIndex:index];

    BOOL isValid = NO;
    NSString *name = [LCommon cleanString:text isValid:&isValid];

    if (isValid) {
        list.name = name;

        // auto-select first item if ipad
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && self.lists.count > 0) {
            NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
            [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionTop];
            [self tableView:self.tableView didSelectRowAtIndexPath:path];
        }
    } else {
        [self deleteList:list];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView reloadData];
    }
}

- (BOOL)tableViewCellShouldBeEditable:(EditableTableViewCell *)cell withTextField:(UITextField *)textField
{
    if (cell == self.cellForEditing && self.newCellShouldAllowEditing) return YES;

    if (self.tableView.editing) return YES;
    else {
        NSIndexPath *path = [self.tableView indexPathForCell:cell];
        [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone];
        [self tableView:self.tableView didSelectRowAtIndexPath:path];
        return NO;
    }
}

- (void)tableViewCellDidBeginEditing:(EditableTableViewCell *)cell withTextField:(UITextField *)textField
{
    if (self.cellForEditing != cell) self.cellForEditing = cell;
}

#pragma mark -
#pragma mark DZNEmptyDataSetDataSource

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {

    NSString *text = @"No lists created";

    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentCenter;

    NSDictionary *attributes = @{NSFontAttributeName: [UIFont boldSystemFontOfSize:17.0],
                                 NSForegroundColorAttributeName: [UIColor colorWithRed:170/255.0 green:171/255.0 blue:179/255.0 alpha:1.0],
                                 NSParagraphStyleAttributeName: paragraphStyle};

    return [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView
{
    NSString *text = @"Tap \"+ List\" to create a new list.";

    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.alignment = NSTextAlignmentCenter;

    NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:15.0],
                                 NSForegroundColorAttributeName: [UIColor colorWithRed:170/255.0 green:171/255.0 blue:179/255.0 alpha:1.0],
                                 NSParagraphStyleAttributeName: paragraphStyle};

    return [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
}

- (NSAttributedString *)buttonTitleForEmptyDataSet:(UIScrollView *)scrollView forState:(UIControlState)state
{
    return nil;
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIImage imageNamed:@"empty_placeholder"];
}

- (UIColor *)backgroundColorForEmptyDataSet:(UIScrollView *)scrollView
{
    return [UIColor groupTableViewBackgroundColor];
}

- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView
{
    return nil;
}

- (CGFloat)spaceHeightForEmptyDataSet:(UIScrollView *)scrollView
{
    return 0;
}

- (CGPoint)offsetForEmptyDataSet:(UIScrollView *)scrollView
{
    if (self.emptyViewShouldUseOffset && UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
        return CGPointMake(0, -self.navigationController.navigationBar.frame.size.height * 2);
    else
        return CGPointMake(0, 0);
}

#pragma mark -
#pragma mark DZNEmpryDataSetDelegate

- (BOOL)emptyDataSetShouldDisplay:(UIScrollView *)scrollView
{
    if (self.lists.count == 0 && !self.newCellShouldAllowEditing) {
        // A little trick for removing the cell separators
        self.tableView.tableFooterView = [UIView new];
        return YES;
    } else { self.tableView.tableFooterView = nil; return NO; }
}

- (BOOL)emptyDataSetShouldAllowTouch:(UIScrollView *)scrollView
{
    return YES;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return NO;
}

- (void)emptyDataSetDidTapView:(UIScrollView *)scrollView
{
    return;
}

- (void)emptyDataSetDidTapButton:(UIScrollView *)scrollView
{
    return;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.lists.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EditableTableViewCell *cell = (EditableTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"Lists Detail" forIndexPath:indexPath];
    cell.delegate = self;

    // Configure the cell...
    List *list = [self.lists objectAtIndex:indexPath.row];
    cell.listText.text = list.name;

    __block int count = 0;
    [list.listItems enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        Item *item = (Item *)obj;
        if (!item.isHidden.boolValue) count++;
    }];

    NSString *imageText = [NSString stringWithFormat:@"%d", count];
    UIColor *listColor = (UIColor *)[NSKeyedUnarchiver unarchiveObjectWithData:list.color];
    UIImage *cellImage = [UIImage imageWithColor:listColor andSize:CGSizeMake(40, 40)];
    cellImage = [UIImage drawText:imageText inImage:cellImage];
    cell.imageView.image = cellImage;
    cell.imageView.layer.cornerRadius = cell.imageView.image.size.height / 2;
    cell.imageView.layer.masksToBounds = YES;

    // add text to image

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source]
        [self deleteList:[self.lists objectAtIndex:indexPath.row]];
        if (indexPath.row < self.tableView.indexPathsForVisibleRows.count && indexPath != nil)
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        if (self.lists.count == 0) [self setEditing:NO];
        [self.tableView reloadData];

        // auto-select first item if ipad
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && self.lists.count > 0) {
            NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
            [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionTop];
            [self tableView:self.tableView didSelectRowAtIndexPath:path];
        } else {
            [self.detailVC setList:nil];
            // set tint color
            UIColor *tintColor = nil;
            self.navigationController.navigationBar.tintColor = tintColor;
            self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : [UIColor blackColor]};
        }

    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}

// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    List *list = [self.lists objectAtIndex:fromIndexPath.row];
    [self.lists removeObjectAtIndex:fromIndexPath.row];
    [self.lists insertObject:list atIndex:toIndexPath.row];

    // persist to core data
    [self persistNewListOrders];
}

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Navigation

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    List *list = [self.lists objectAtIndex:indexPath.row];

    if (!self.cellForEditing) {
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            self.selectedCell = (EditableTableViewCell *) [self.tableView cellForRowAtIndexPath:indexPath];
            [self.detailVC setList:list];
            // set tint color
            UIColor *tintColor = [NSKeyedUnarchiver unarchiveObjectWithData:list.color];
            self.navigationController.navigationBar.tintColor = tintColor;
            self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName : tintColor};
        } else [self performSegueWithIdentifier:@"pushToList" sender:list];
    } else [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    self.selectedCell = nil;
}

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
    if ([segue.identifier isEqualToString:@"pushToList"]) [segue.destinationViewController setList:sender];
}

@end


text:
class Config(object):
	DEBUG = False
	TESTING = False
	SITE_NAME = 'Shopping Price Locator'
	SQLALCHEMY_DATABASE_URI = ''
	SQLALCHEMY_ECHO=False
	SECRET_KEY	= ''

class Production(Config):
	DEBUG=False
	SQLALCHEMY_ECHO=False

class Development(Config):
	DEBUG = True
	SQLALCHEMY_TRACK_MODIFICATIONS 	= True

class Test(Config):
	TESTING = True

	SQLALCHEMY_DATABASE_URI        = "mysql+pymysql://test_admin:test_account@localhost/sag_test_db"
	SQLALCHEMY_TRACK_MODIFICATIONS = True
	SQLALCHEMY_ECHO                = False
	SECRET_KEY                     = "thisisafakesecretkeyonlyusedfortesting"
	WTF_CSRF_ENABLED               = False

configs = {
	'development': Development,
	'production': Production,
	'test' : Test
}


text:
package org.apache.sshd.sftp.common.extensions;

import org.apache.sshd.common.util.ValidateUtils;

/**
 * @param  <T> Parse result type
 * @author     Apache MINA SSHD Project
 */
public abstract class AbstractParser<T> implements ExtensionParser<T> {
    private final String name;

    protected AbstractParser(String name) {
        this.name = ValidateUtils.checkNotNullAndNotEmpty(name, "No extension name");
    }

    @Override
    public final String getName() {
        return name;
    }
}


text:
#include <stdlib.h>
#include <stack.h>
#include <string.h>
#include <stdio.h>
#include <hashmap.h>
#include <array_list.h>
#include "ast.h"
#include "validator.h"

enum types {
    T_NUMBER = 1,
    T_BOOL,
    T_VECTOR,
    T_EVENT,
    T_EVENT_DEFINITION
};

const char *type_names[] = {
    "NUMBER",
    "BOOL",
    "VECTOR",
    "EVENT",
    "EVENT_DEFINITION"
};

static enum types *new_type(enum types type)
{
    enum types *t = malloc(sizeof(enum types));
    *t = type;
    return t;
}

int stack_size = 0;

int validate_event_declaration(struct node *temp, struct payload *payload);

int validate_rule_declaration(struct node *temp, struct payload *payload);

int validate_rule_signature(struct node *temp, struct payload *payload);

int validate_event(struct node *temp, struct payload *payload);

int validate_predicate_definition(struct node *temp, struct payload *payload,
                                  struct stack **type_stack);

int validate_function_definition(struct node *temp, struct payload *payload,
                                 struct stack **type_stack);

int validate_parameter_list(struct node *temp);

int validate_function_call(struct node *temp, struct payload *payload, struct stack **type_stack);

int validate_event_definition(struct node *temp, struct stack **type_stack);

int validate_initializer(struct node *temp, struct payload *payload, struct stack **type_stack);

int validate_vector(struct node *temp, struct stack **type_stack);

int validate_component_sequence(struct node *temp, struct stack **type_stack);

int validate_comparison_expression(struct node *temp, struct payload *payload,
                                   struct stack **type_stack);

int validate_addition(struct node *temp, struct stack **type_stack);

int validate_multiplication(struct node *temp, struct payload *payload, struct stack **type_stack);

int validate_power(struct node *temp, struct payload *payload, struct stack **type_stack);

int validate_atomic(struct node *temp, struct payload *payload, struct stack **type_stack);

static enum types *type_stack_pop(struct stack **stack)
{
    stack_size--;
    enum types *type = stack_pop(stack);
    //printf("Pop: %s (Stack Size: %i)\n", type_names[*type - 1], stack_size);
    return type;
}

static void type_stack_push(struct stack **stack, enum types *type)
{
    stack_size++;
    //printf("Push: %s (Stack Size: %i)\n", type_names[*type - 1], stack_size);
    stack_push(stack, type);
}

int check_duplicate_members(struct node *event_declaration, char *member)
{
    struct payload *payload = event_declaration->payload;
    if (hashmap_get(payload->event_declaration.scope, member)) {
        return 1;
    } else if (payload->event_declaration.parent_ref) {
        return check_duplicate_members(payload->event_declaration.parent_ref, member);
    } else {
        return 0;
    }
}

int validate(struct node *root)
{
    struct tree_iterator *it = tree_iterator_init(&root, POSTORDER);
    struct node *temp = NULL;
    struct payload *payload = NULL;
    struct stack *type_stack = NULL;
    int success = 1;

    while ((temp = tree_iterator_next(it)) != NULL) {
        payload = (struct payload *)temp->payload;
        switch (payload->type) {
            case N_EVENT_DECLARATION:
                success = validate_event_declaration(temp, payload);
                break;
            case N_RULE_DECLARATION:
                success = validate_rule_declaration(temp, payload);
                break;
            case N_RULE_SIGNATURE:
                success = validate_rule_signature(temp, payload);
                break;
            case N_EVENT:
                success = validate_event(temp, payload);
                break;
            case N_PREDICATE_DEFINITION:
                success = validate_predicate_definition(temp, payload, &type_stack);
                break;
            case N_FUNCTION_DEFINITION:
                success = validate_function_definition(temp, payload, &type_stack);
                break;
            case N_PARAMETER_LIST:
                success = validate_parameter_list(temp);
                break;
            case N_FUNCTION_CALL:
                success = validate_function_call(temp, payload, &type_stack);
                break;
            case N_EVENT_DEFINITION:
                success = validate_event_definition(temp, &type_stack);
                break;
            case N_INITIALIZER:
                success = validate_initializer(temp, payload, &type_stack);
                break;
            case N_VECTOR:
                success = validate_vector(temp, &type_stack);
                break;
            case N_COMPONENT_SEQUENCE:
                success = validate_component_sequence(temp, &type_stack);
                break;
            case N_COMPARISON_EXPRESSION:
                success = validate_comparison_expression(temp, payload, &type_stack);
                break;
            case N_ADDITION:
                success = validate_addition(temp, &type_stack);
                break;
            case N_MULTIPLICATION:
                success = validate_multiplication(temp, payload, &type_stack);
                break;
            case N_POWER:
                success = validate_power(temp, payload, &type_stack);
                break;
            case N_ATOMIC:
                success = validate_atomic(temp, payload, &type_stack);
                break;
            default:
                /* passed by */
                break;
        }

        if (!success) {
            break;
        }
    }

    stack_free(&type_stack, free);
    tree_iterator_free(it);

    return success;
}

int validate_event(struct node *temp, struct payload *payload)
{
    int success = 1;

    if (payload->event.ref == NULL) {
        /* event does not exist */
        success = 0;
    }

    return success;
}

int validate_rule_signature(struct node *temp, struct payload *payload)
{
    int success = 1;

    if (payload->alternative == ALT_PREDICATE_SEQUENCE) {
        /* a predicate sequence is present */

        /* loop over predicates */
        for (int i = 0; i < temp->childv[1]->childc; i++) {
            /* get predicate definition */
            struct node *predicate_definition =
                ((struct payload *)(temp->childv[1]->childv[i]->payload))->predicate.ref;
            if (predicate_definition == NULL) {
                /* referenced predicate does not exist */
                success = 0;
                break;
            } else {
                /* predicate found */

                if (temp->childv[0]->childc != predicate_definition->childv[0]->childc) {
                    /* unequal number of parameters and events */
                    success = 0;
                } else {
                    /* number of parameters und events are equal */

                    /* loop over parameters */
                    char *parameter_type = NULL;
                    char *event_type = NULL;
                    for (int j = 0; j < predicate_definition->childv[0]->childc; j++) {
                        event_type = ((struct payload *)(temp->childv[0]->childv[j]->payload))->event.type;
                        parameter_type = ((struct payload *)(predicate_definition->childv[0]->childv[j]->payload))->parameter.type;
                        if (strcmp(event_type, parameter_type) != 0) {
                            /* one parameter does not match the the events in order or type */
                            success = 0;
                            break;
                        }
                    }
                }
            }
        }
    }

    return success;
}

int validate_rule_declaration(struct node *temp, struct payload *payload)
{
    int success = 1;

    if (NULL) {
        /* rule does already exist */
        success = 0;
    } else {
        /* rule does not exist */
        if (payload->rule_declaration.ref == NULL) {
            /* referenced function does not exist */
            success = 0;
        } else {
            /* referenced function exists */
            struct node *function_definition = payload->rule_declaration.ref;
            if (payload->rule_declaration.eventc != 0) {
                /* event sequence is not empty */
                if (((struct payload *)(function_definition->payload))->alternative == ALT_PARAMETER_LIST) {
                    /* parameter_list exists */
                    if (payload->rule_declaration.eventc != function_definition->childv[0]->childc) {
                        /* count of function parameters does not match the event sequence size */
                        success = 0;
                    } else {
                        /* same number of function parameters as events */

                        /* loop over parameters */
                        for (int i = 0; i < payload->rule_declaration.eventc; i++) {
                            struct node *event = array_list_get(&(payload->rule_declaration.eventv),
                                                                payload->rule_declaration.eventc - 1 - i);
                            struct node *parameter = function_definition->childv[0]->childv[i];
                            char *event_type = ((struct payload *)event->payload)->event.type;
                            char *parameter_type = ((struct payload *)parameter->payload)->parameter.type;
                            if (strcmp(event_type, parameter_type) != 0) {
                                /* at least one parameter does not match in type or order */
                                success = 0;
                                break;
                            }
                        }
                    }
                } else {
                    /* needed parameter_list is missing */
                    success = 0;
                }
            } else {
                /* event sequence is empty */
                if (((struct payload *)(function_definition->payload))->alternative == ALT_PARAMETER_LIST) {
                    success = 0;
                }
            }
        }
    }

    return success;
}

int validate_event_declaration(struct node *temp, struct payload *payload)
{
    int success = 1;

    if (NULL) {
        /* event already exists */
        success = 0;
    } else {
        /* event does not already exist */
        if (payload->event_declaration.type[1] != NULL) {
            /* event is inherited */
            if (payload->event_declaration.parent_ref == NULL) {
                /* parent event does not exist */
                success = 0;
            } else {
                /* parent event exists */
                for (int i = 0; i < temp->childv[0]->childc; i++) {
                    if (check_duplicate_members(payload->event_declaration.parent_ref,
                                                ((struct payload *)temp->childv[0]->childv[i]->payload)->member.identifier)) {
                        /* at least one member exists already in the parent */
                        success = 0;
                    }
                }
            }
        }
    }

    return success;
}

int validate_predicate_definition(struct node *temp, struct payload *payload,
                                  struct stack **type_stack)
{
    int success = 1;

    if (NULL) {
        /* predicate definition already exists */
        success = 0;
    } else {
        /* predicate definition does not exist */

        enum types *type = type_stack_pop(type_stack);
        if (*type != T_BOOL) {
            /* expression is not boolean */
            success = 0;
        }
        free(type);
    }

    return success;
}

int validate_function_definition(struct node *temp, struct payload *payload,
                                 struct stack **type_stack)
{
    int success = 1;

    if (NULL) {
        /* function already exists */
        success = 0;
    } else {
        /* function does not exists */
        if (payload->function_definition.event_ref == NULL) {
            /* return event type does not exist */
            success = 0;
        } else {
            /* return event type exists */

            /* comes from comparison_expression */
            enum types *type = type_stack_pop(type_stack);
            if (*type == T_EVENT) {
                /* expression is an event */
                char *ret_event_name = payload->function_definition.type;
                char *exp_event_name = stack_pop(type_stack);
                if (strcmp(ret_event_name, exp_event_name) != 0) {
                    /* return event and expression event have not the same type */
                    success = 0;
                }
                free(exp_event_name);
            } else if (*type == T_EVENT_DEFINITION) {
                /* the expression is an event definition */
                // TODO: CHECK THAT EVERY MEMBER IS PRESENT IN EVENT_DEFINITION
            } else {
                /* the expression is not an event or event_definition */
                success = 0;
            }
            free(type);
        }
    }

    return success;
}

int validate_parameter_list(struct node *temp)
{
    int success = 1;

    /* loop over parameters */
    for (int i = 0; i < temp->childc; i++) {
        struct payload *parameter_payload_one = temp->childv[i]->payload;
        /* loop over parameters */
        for (int j = i + 1; j < temp->childc; j++) {
            struct payload *parameter_payload_two = temp->childv[j]->payload;
            if (parameter_payload_one->parameter.identifier == parameter_payload_two->parameter.identifier) {
                /* there are double parameter names */
                success = 0;
                break;
            }
        }

        if (!success) {
            break;
        }
    }

    return success;
}

int validate_function_call(struct node *temp, struct payload *payload, struct stack **type_stack)
{
    int success = 1;

    struct node *function_definition = payload->function_call.ref;
    if (function_definition == NULL) {
        /* called function does not exist */
        success = 0;
    } else {
        /* function exists */
        stack_push(type_stack, strdup(((struct payload *)(function_definition->payload))->function_definition.type));
        type_stack_push(type_stack, new_type(T_EVENT));
    }

    return success;
}

int validate_event_definition(struct node *temp, struct stack **type_stack)
{
    int success = 1;

    /* TODO: check that no initializer is doubled */

    type_stack_push(type_stack, new_type(T_EVENT_DEFINITION));

    return success;
}

int validate_initializer(struct node *temp, struct payload *payload, struct stack **type_stack)
{
    int success = 1;

    if (payload->initializer.ref_index == -1) {
        /* no corresponding event member found */
        success = 0;
    } else {
        /* event member found */

        enum types *type = type_stack_pop(type_stack);
        if (*type != T_VECTOR) {
            /* expression is not a vector */
            success = 0;
        }
        free(type);
    }

    return success;
}

int validate_vector(struct node *temp, struct stack **type_stack)
{
    int success = 1;

    type_stack_push(type_stack, new_type(T_VECTOR));

    return success;
}

int validate_component_sequence(struct node *temp, struct stack **type_stack)
{
    int success = 1;

    /* loop over all expressions in the expression sequence and check that
     * they're all numbers
     */
    enum types *type = NULL;
    for (int i = 0; i < temp->childv[0]->childc; i++) {
        type = type_stack_pop(type_stack);
        if (*type != T_NUMBER) {
            /* one expression is not a number */
            success = 0;
            free(type);
            break;
        }
        free(type);
    }

    return success;
}

int validate_comparison_expression(struct node *temp, struct payload *payload,
                                   struct stack **type_stack)
{
    int success = 1;

    if (payload->alternative != ALT_ADDITIVE_EXPRESSION) {
        enum types *add_exp_one = type_stack_pop(type_stack);
        enum types *add_exp_two = type_stack_pop(type_stack);
        if (*add_exp_one != T_VECTOR || *add_exp_two != T_VECTOR) {
            /* comparison needs two vectors */
            success = 0;
        } else {
            /* two vectors are given */
            type_stack_push(type_stack, new_type(T_BOOL));
        }
        free(add_exp_one);
        free(add_exp_two);
    }

    return success;
}

int validate_addition(struct node *temp, struct stack **type_stack)
{
    int success = 1;

    enum types *mult_exp = type_stack_pop(type_stack);
    enum types *add_exp = type_stack_pop(type_stack);

    if (*mult_exp != *add_exp) {
        /* the expressions have not the same type */
        success = 0;
    } else {
        /* the expressions have the same type */
        type_stack_push(type_stack, mult_exp);
    }

    free(add_exp);

    return success;
}

int validate_multiplication(struct node *temp, struct payload *payload, struct stack **type_stack)
{
    int success = 1;

    enum types *neg = type_stack_pop(type_stack);
    enum types *mult_exp = type_stack_pop(type_stack);

    if (*mult_exp != T_NUMBER) {
        /* first operand is not a number */
        success = 0;
    } else {
        /* first operand is a number */
        if (*neg != T_NUMBER && *neg != T_VECTOR) {
            /* second operand is not a number or not a vector */
            success = 0;
        } else if (*neg == T_NUMBER) {
            /* second operand is a number */
            type_stack_push(type_stack, new_type(T_NUMBER));
        } else {
            /* second operator is a vector */
            if (payload->alternative == ALT_DIV) {
                /* times vector is not defined */
                success = 0;
            } else {
                type_stack_push(type_stack, new_type(T_VECTOR));
            }
        }
    }

    free(neg);
    free(mult_exp);

    return success;
}

int validate_power(struct node *temp, struct payload *payload, struct stack **type_stack)
{
    int success = 1;

    if (temp->childc > 1) {
        /* Node is no proxy */
        enum types *prim_exp2 = type_stack_pop(type_stack);
        enum types *prim_exp1 = type_stack_pop(type_stack);

        if (*prim_exp1 != T_VECTOR) {
            /* first operand is not a vector */
            success = 0;
        } else {
            /* first operand is a vector */
            if (*prim_exp2 != T_NUMBER) {
                /* second operand is not a number */
                success = 0;
            } else {
                /* second operand is a number */
                type_stack_push(type_stack, new_type(T_NUMBER));
            }
        }

        free(prim_exp1);
        free(prim_exp2);
    }

    return success;
}

int validate_atomic(struct node *temp, struct payload *payload, struct stack **type_stack)
{
    int success = 1;
    if (payload->alternative == ALT_IDENTIFIER) {
        /* atomic is a vector or an event */

        if (payload->atomic.ref == NULL) {
            /* vector or event does not exist */
            success = 0;
        } else {
            /* vector or event exists */
            if (payload->atomic.identifier[1] != NULL) {
                /* it's a vector */
                type_stack_push(type_stack, new_type(T_VECTOR));
            } else {
                /* it's an event */
                stack_push(type_stack,
                           strdup(((struct payload *)payload->atomic.ref->payload)->parameter.type));
                type_stack_push(type_stack, new_type(T_EVENT));
            }
        }

        return success;
    }

    if (payload->alternative == ALT_NUMBER) {
        /* atomic is a number */

        type_stack_push(type_stack, new_type(T_NUMBER));
    }

    /* other alternatives are passed by */

    return success;
}


text:
PiClock and this install guide are based on Raspian Jessie
last released on https://downloads.raspberrypi.org/raspbian/images/raspbian-2017-07-05/
It will work with many raspbian versions, but you may have to add more packages,
etc.  That exercise is left for the reader.

What follows is a step by step guide.  If you start with a new clean raspbian
image, it should just work. I'm assuming that you already know how to hook
up your Raspi, monitor, and keyboard/mouse.   If not, please do a web search
regarding setting up the basic hardware for your Raspi.

### Download Raspbian Jessie and put it on an SD Card

The image and instructions for doing this are on the following page:
https://www.raspberrypi.org/downloads/

### First boot and configure
A keyboard and mouse are really handy at this point.
When you first boot your Pi, you'll be presented with the desktop.
Navigate to Menu->Preferences->Raspberry Pi Configuration.
Just change the Items below.
 - General Tab
  - Change User Password -- this will set the password for the use pi,
     for ssh logins.
  - Hostname: (Maybe set this to PiClock?)
  - Boot: To Desktop
  - Auto Login: Checked
  - Underscan: (Initally leave as default, but if your monitor has extra black area on the border, or bleeds off the edge, then change this)
 - Interfaces
  - 1-Wire Enable (for the inside temperature, DS18B20 if you're using it)
 - Internationalization Tab
   - Set Locale.
    - Set Language  -- if you set language and country here, the date will automaticly be in your language
    				-- other settings in Config.py (described later) control the language of the weather data
    - Set Country
    - Character Set: UTF-8
  - Set Timezone.
    -  You'll want this to be correct, or the clock will be wrong.
  - Set Keyboard
    -  Generally not needed, but good to check if you like the default
  - Set WiFi Country (may not always show up)

Finish and let it reboot.

I've found that sometimes on reboot, Jessie doesn't go back to desktop mode.
If this is the case,
```
sudo raspi-config
```
and change the boot option to Desktop/Auto-login

### editing config.txt

Log into your Pi, (either on the screen or via ssh)

use nano to edit the boot config file
```
sudo nano /boot/config.txt
```
Be sure the lines
```
dtoverlay=lirc-rpi,gpio_in_pin=3,gpio_out_pin=2
dtoverlay=w1-gpio,gpiopin=4
```
are in there somewhere, and occur only once.
The default config has lirc-rpi commented out (# in front), don't forget to remove the #
Also add the pin arguments just as shown above, if they are not already there.

You're free to change the pins, but of course the hardware guide will need to
be adjusted to match.

use nano to edit the modules file
```
sudo nano /etc/modules
```
Be sure the lines
```
lirc_rpi gpio_in_pin=3 gpio_out_pin=2
w1-gpio
```
are in there somewhere, and only occur once.

reboot
```
sudo reboot
```

### Get connected to the internet

Either connect to your wired network, or setup wifi and verify you have
internet access from the Pi

```
ping github.com
```
(remember ctrl-c aborts programs, like breaking out of ping, which will
go on forever)

### Get all the software that PiClock needs.

Become super user! (root)  (trumpets play in the background) (ok, maybe
just in my head)
```
sudo su -
```
update the repository
```
apt-get update
```
then get qt4 for python
```
apt-get install python-qt4
```
you may need to confirm some things, like:
After this operation, 44.4 MB of additional disk space will be used.
Do you want to continue [Y/n]? y
Go ahead, say yes

then get ws281x driver for python (optional for the NeoPixel LED Driver)
```
pip install rpi_ws281x
```
Someversions of Raspbian need python-dev to be installed as well, before
rpi-ws281x can be installed.  If the prevous command fails reporting
a missing include file, then do this:
```
apt-get install python-dev
```
Then try the pip command again.

then install more needed python libraries
```
pip install python-dateutil --upgrade
pip install tzlocal --upgrade
pip install python-metar --upgrade
```

then get unclutter (disables the mouse pointer when there's no activity)
```
apt-get install unclutter
```

### Get the DS18B20 Temperature driver for Python (optional)

(you must still be root [super user])
```
git clone https://github.com/timofurrer/w1thermsensor.git && cd w1thermsensor
python setup.py install
```

### Get Lirc driver for IR remote (optional)

(you must still be root [super user])
```
apt-get install lirc
```

use nano to edit lirc hardware file
```
sudo nano /etc/lirc/hardware.conf
```
Be sure the LIRCD_ARGS line appears as follows
```
LIRCD_ARGS="--uinput"
```

Be sure the DRIVER line appears as follows
```
DRIVER="default"
```

Be sure the DEVICE line appears as follows
```
DEVICE="/dev/lirc0"
```

Be sure the MODULES line appears as follows
```
MODULES="lirc_rpi"
```

### Get mpg123 (optional to play NOAA weather radio streams)

(you must still be root [super user])
```
apt-get install mpg123
```

### reboot
To get some things running, and ensure the final config is right, we'll do
a reboot
```
reboot
```

### Get the PiClock software
Log into your Pi, (either on the screen or via ssh) (NOT as root)
You'll be in the home directory of the user pi (/home/pi) by default,
and this is where we want to be.
```
git clone https://github.com/n0bel/PiClock.git
```
Once that is done, you'll have a new directory called PiClock
A few commands are needed if you intend to use gpio buttons
and the gpio-keys driver to compile it for the latest Raspbian:
```
cd PiClock/Button
make gpio-keys
cd ../..
```

### Set up Lirc (IR Remote)
If you're using the recommended IR Key Fob,
https://www.google.com/search?q=Mini+Universal+Infrared+IR+TV+Set+Remote+Control+Keychain
you can copy the lircd.conf file included in the distribution as follows:
```
sudo cp IR/lircd.conf /etc/lirc/
```
If you're using something else, you'll need to use irrecord, or load a remote file
as found on http://lirc.org/

The software expects 7 keys.   KEY_F1, KEY_F2, KEY_F3, KEY_UP, KEY_DOWN, KEY_RIGHT
and KEY_LEFT.   Lirc takes these keys and injects them into linix as if they
were typed from a keyboard.   PyQPiClock.py then simply looks for normal keyboard
events.   Therefore of course, if you have a usb keyboard attached, those keys
work too.  On the key fob remote, F1 is power, F2 is mute and F3 is AV/TV.

You should (must) verify your IR codes.   I've included a program called IRCodes.pl
which will verify that your lircd.conf is setup correctly.
If you've rebooted after installing lircd.conf, you'll have to stop lirc first:
```
sudo service lirc stop
```
Then use the IRCodes.pl program as follows:
```
perl IR/IRCodes.pl
```
Yes, I reverted to perl.. I may redo it in Python one day.

If you're using the recommended key fob remote, they come randomly programmed from
the supplier.   To program them you press and hold the mute button (the middle one)
while watching the screen scroll through codes.
When the screen shows
```
************ KEY_F2
```
STOP! then try the other keys, be sure they all report KEY_UP, KEY_DOWN correctly.
If not press and hold the mute button again, waiting for the asterisks and KEY_F2,
then STOP again, try the other keys.   Repeat the process until you have all the
keys working.

Ctrl-C to abort perl.

then reboot
```
sudo reboot
```

### Configure the PiClock api keys

The first is to set API keys for DarkSky and Google Maps.
These are both free, unless you have large volume.
The PiClock usage is well below the maximums imposed by the no cost api keys.

#### DarkSky api keys

DarkSky api keys are created at this link:
https://darksky.net/dev

#### Google Maps API key

A Google Maps api key is _required_.  (Requires credit card which won't be
charged unless usage is great.)

An intro to Google static maps api keys, and a link to creating your account and ApiKeys:
https://developers.google.com/maps/documentation/maps-static/intro
You'll require a google user and password.  It'll also require a credit card.
The credit card should not be charged, because my reading of https://cloud.google.com/maps-platform/pricing/sheet/ the $200.00 credit will
apply, and your charges incurred will be for 31 map pulls per month will be
$0.62 , if you reboot daily.
You'll be required to create a "project" (maybe PiClock for a project name?)
You need to then activate the key.

_Protect your API keys._  You'd be surprised how many pastebin's are out
there with valid API keys, because of people not being careful.   If you post
your keys somewhere, your usage will skyrocket, and your bill as well.  Google
has the ability to add referer, device and ip requirements on your api key.  It
can also allow you to limit an api key to specific applications only (static-maps)
in this case.   Also you might consider disabling all the other APIs on your
project dashboard.   Under the Billing section of things you can set up budgets
and alerts.  (Set to like $1.00)

Now that you have your api keys...

```
cd PiClock
cd Clock
cp ApiKeys-example.py ApiKeys.py
nano ApiKeys.py
```
Put your api keys in the file as indicated
```
#change this to your API keys
# DarkSky API key
dsapi = 'YOUR DARKSKY API KEY'
# Google Maps API key
googleapi = 'YOUR GOOGLE API KEY'
```

### Configure your PiClock
here's were you tell PiClock where your weather should come from, and the
radar map centers and markers.

```
cd PiClock
cd Clock
cp Config-Example.py Config.py
nano Config.py
```

This file is a python script, subject to python rules and syntax.
The configuration is a set of variables, objects and arrays,
set up in python syntax.  The positioning of the {} and () and ','
are not arbitrary.  If you're not familiar with python, use extra
care not to disturb the format while changing the data.

The first thing is to change the primary_coordinates to yours.  That is really
all that is manditory.  Further customization of the radar maps can be done in
the Radar section.  There you can customize where your radar images are centered
and where the markers appear on those images.  Markers are those little red
location pointers.  Radar1 and 2 show on the first page, and 3 and 4 show on the
second page of the display (here's a post of about that:
https://www.facebook.com/permalink.php?story_fbid=1371576642857593&id=946361588712436&substory_index=0 )

The second thing to change is your NOAA weather radio stream url.  You can
find it here: http://noaaweatherradio.org/  They don't put the .mp3 urls
where they are easily accessable, so you need to use your browser to "View Page Source"
in order to find the proper .mp3 url.

At this point, I'd not recommend many other changes until you have tested
and gotten it running.

### Run it!
You'll need to be on the desktop, in a terminal program.

```
cd PiClock
sh startup.sh -n -s
```
Your screen should be covered by the PiClock  YAY!

There will be some output on the terminal screen as startup.sh executes.
If everything works, it can be ignored.  If for some reason the clock
doesn't work, or maps are missing, etc the output may give a reason
or reasons, which usually reference something to do with the config
file (Config.py)

### Logs
The -s option causes no log files to be created, but
instead logs to your terminal screen.  If -s is omitted, logs are
created in PiClock/Clock as PyQtPiClock.[1-7].log, which can also help
you find issues.  -s is normally omitted when started from the desktop icon
or from crontab.  Logs are then created for debugging auto starts.

### First Use

  * The space bar or right or left arrows will change the page.
  * F2 will start and stop the NOAA weather radio stream
  * F4 will close the clock

If you're using the temperature feature AND you have multiple temperature sensors,
you'll see the clock display: 000000283872:74.6 00000023489:65.4 or something similar.
Note the numbers exactly.   Use F4 to stop the clock,
then..
```
nano Temperature/TempNames.py
```
Give each number a name, like is shown in the examples in that file

### setting the clock to auto start
At this point the clock will only start when you manually start it, as
described in the Run It section.

Use only one autostart method.
## Autostart Method 1
(NOT as root)
```
cd PiClock
chmod +x PiClock.desktop
ln PiClock.desktop ~/Desktop
mkdir ~/.config/autostart
ln PiClock.desktop ~/.config/autostart
```
This puts the a PiClock icon on your desktop.  It also runs it when
the desktop starts.

## Autostart Method 2
To have it auto start on boot we need to do one more thing, edit the
crontab file as follows: (it will automatically start nano)  (NOT as root)
```
crontab -e
```
and add the following line:
```
@reboot sh /home/pi/PiClock/startup.sh
```
save the file
and reboot to test
```
sudo reboot
```

## Some notes about startup.sh
startup.sh has a few options:
* -n or --no-delay			Don't delay on starting the clock right away (default is 45 seconds delay)
* -d X or --delay X			Delay X seconds before starting the clock
* -m X or --message-delay X 	Delay X seconds while displaying a message on the desktop

Startup also looks at the various optional PiClock items (Buttons, Temperature, NeoPixel, etc)
and only starts those things that are configured to run.   It also checks if they are already
running, and refrains from starting them again if they are.

### Switching skins at certain times of the day
This is optional, but if its just too bright at night, a switcher script will kill and restart
PyQtPiClock with an alternate config.

First you need to set up an alternate config.   Config.py is the normal name, so perhaps Config-Night.py
might be appropriate.  For a dimmer display use Config-Example-Bedside.py as a guide.

Now we'll tell our friend cron to run the switcher script (switcher.sh) on day/night cycles.
Run the cron editor: (should *not* be roor)
```
crontab -e
```
Add lines similar to this:
```
0 8 * * * sh /home/pi/PiClock/switcher.sh Config
0 21 * * * sh /home/pi/PiClock/switcher.sh Config-Night
```
The 8 there means 8am, to switch to the normal config, and the 21 means switch to Config-Night at 9pm.
More info on crontab can be found here: https://en.wikipedia.org/wiki/Cron

### Setting the Pi to auto reboot every day
This is optional but some may want their PiClock to reboot every day.  I do this with mine,
but it is probably not needed.
```
sudo crontab -e
```
add the following line
```
22 3 * * * /sbin/reboot
```
save the file

This sets the reboot to occur at 3:22am every day.   Adjust as needed.

### Updating to newer/updated versions
Since we pulled the software from github originally, it can be updated
using git and github.
```
cd PiClock
git pull
python update.py
```
This will automatically update any part(s) of the software that has changed.
The update.py program will then convert any config files as needed.

You'll want to reboot after the update.

Note: If you get errors because you've made changes to the base code you might need
```
git reset --hard
```
Backup your changes first!
(This won't bother your Config.py nor ApiKeys.py because they are not tracked in git.

Also, if you're using gpio-keys, you may need to remake it:
```
cd PiClock/Buttons
rm gpio-keys
make gpio-keys
```


text:
package org.languagetool.rules.uk;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.LinkedHashSet;
import java.util.ResourceBundle;
import java.util.regex.Pattern;

import org.languagetool.JLanguageTool;
import org.languagetool.AnalyzedSentence;
import org.languagetool.AnalyzedToken;
import org.languagetool.AnalyzedTokenReadings;
import org.languagetool.rules.Rule;
import org.languagetool.rules.RuleMatch;
import org.languagetool.rules.ITSIssueType;
import org.languagetool.tagging.uk.PosTagHelper;

/**
 * A rule that matches proper names that has been renamed
 * Loads the relevant words from rules/uk/replace_renamed.txt.
 *
 * @author Andriy Rysin
 */
public class SimpleReplaceRenamedRule extends Rule {

  private static final Map<String, List<String>> RENAMED_LIST = ExtraDictionaryLoader.loadLists("/uk/replace_renamed.txt");
  private static final Pattern GEO_POSTAG_PATTERN = Pattern.compile("noun:inanim.*?:prop.*|adj.*");

  public SimpleReplaceRenamedRule(ResourceBundle messages) {
    super(messages);
    setLocQualityIssueType(ITSIssueType.Style);
  }

  @Override
  public final String getId() {
    return "UK_SIMPLE_REPLACE_RENAMED";
  }

  @Override
  public String getDescription() {
    return "Пропозиція поточної назви для перейменованих власних назв";
  }

  @Override
  public final RuleMatch[] match(AnalyzedSentence sentence) {
    List<RuleMatch> ruleMatches = new ArrayList<>();
    AnalyzedTokenReadings[] tokens = sentence.getTokensWithoutWhitespace();

    for (AnalyzedTokenReadings tokenReadings: tokens) {

      LinkedHashSet<String> renamedLemmas = new LinkedHashSet<>();
      for(AnalyzedToken reading: tokenReadings.getReadings()) {
        String lemma = reading.getLemma();

        if( JLanguageTool.SENTENCE_END_TAGNAME.equals(reading.getPOSTag()) )
          continue;

        if( lemma != null ) {
          if( RENAMED_LIST.containsKey(lemma)
              && PosTagHelper.hasPosTag(reading, GEO_POSTAG_PATTERN) ) {
            renamedLemmas.add(lemma);
          }
          else {
            // overlaps with normal lemma
            renamedLemmas.clear();
            break;
          }
        }
      }

      if( renamedLemmas.size() > 0 ) {
        String info = "";
        List<String> replacements = new ArrayList<>();
        for(String lemma: renamedLemmas) {
          List<String> repl = RENAMED_LIST.get(lemma);
          replacements.add(repl.get(0));

          for(int i=1; i<repl.size()-1; i++) {
            replacements.add(repl.get(i));
          }

          // kinda cheating - getting first explanation we find
          // but usually we'll get a noun and adj for the same name so it's ok
          if( info.isEmpty() && repl.size() > 1 ) {
            info = repl.get(repl.size()-1);
          }
        }

        RuleMatch match = createRuleMatch(tokenReadings, replacements, getMessage(renamedLemmas.iterator().next(), info), sentence);
        ruleMatches.add(match);
      }

    }
    return ruleMatches.toArray(new RuleMatch[0]);
  }

  private String getMessage(String tokenStr, String info) {
    String msg = "«" + tokenStr + "» було перейменовано";
    if( ! info.isEmpty() ) {
      msg += " (" + info + ")";
    }
    return msg;
  }

  private RuleMatch createRuleMatch(AnalyzedTokenReadings readings, List<String> replacements, String msg, AnalyzedSentence sentence) {
    RuleMatch potentialRuleMatch = new RuleMatch(this, sentence, readings.getStartPos(), readings.getEndPos(), msg, "Перейменована назва");
    potentialRuleMatch.setSuggestedReplacements(replacements);

    return potentialRuleMatch;
  }

}


text:
var React = require('react');
var Article = require('grommet/components/Article');
var Header = require('grommet/components/Header');
var Title = require('grommet/components/Title');
var Footer = require('grommet/components/Footer');
var Form = require('grommet/components/Form');
var FormFields = require('grommet/components/FormFields');
var FormField = require('grommet/components/FormField');
var Menu = require('grommet/components/Menu');
var Button = require('grommet/components/Button');
var Actions = require('../actions/Actions');

var Configuration = React.createClass({

  propTypes: {
    data: React.PropTypes.object.isRequired
  },

  _onConfigure: function (event) {
    event.preventDefault();
    let configuration = {
      model: this.refs.model.getDOMNode().value,
      numNodes: parseInt(this.refs.nodes.getDOMNode().value),
      numDrives: parseInt(this.refs.drives.getDOMNode().value)
    };
    Actions.configure(configuration);
  },

  render: function() {
    var options = this.props.data.configurationOptions;
    var configuration = this.props.data.configuration;
    var models = options.models.map(function (model) {
      return <option key={model}>{model}</option>;
    });

    return (
      <Article>
        <Header fixed={true} pad={{horizontal: 'medium'}}>
          <Title>{this.props.data.title}</Title>
        </Header>
        <Form pad="medium">
          <FormFields>
            <fieldset>
              <FormField label="Model" htmlFor={"model"}>
                <select ref="model" id={"model"} name="model">
                  {models}
                </select>
              </FormField>
              <FormField label="Nodes" htmlFor={"nodes"}>
                <input ref="nodes" id={"nodes"} name="nodes" type="number"
                  min="1" max={options.maxNodes} step="1"
                  defaultValue={configuration.numNodes} />
              </FormField>
              <FormField label="Drives" htmlFor={"drives"}>
                <input ref="drives" id={"drives"} name="drives" type="number"
                  min="1" max={options.maxDrives} step="1"
                  defaultValue={configuration.numDrives} />
              </FormField>
            </fieldset>
          </FormFields>
          <Footer pad={{vertical: 'medium'}}>
            <Menu>
              <Button label="Generate" primary={true} strong={true}
                onClick={this._onConfigure} />
            </Menu>
          </Footer>
        </Form>
      </Article>
    );
  }

});

module.exports = Configuration;


text:
id: 197
title: 'Ellen, Miguel Abuelo y… Calamaro'
date: 2008-03-27T22:03:22+00:00
author: Alvar
layout: post
guid: http://www.acercadelaeducacion.com.ar/?p=197
permalink: /2008/03/ellen-miguel-abuelo-y-calamaro/
aktt_tweeted:
  - "1"
podPressPostSpecific:
  - 'a:6:{s:15:"itunes:subtitle";s:15:"##PostExcerpt##";s:14:"itunes:summary";s:15:"##PostExcerpt##";s:15:"itunes:keywords";s:17:"##WordPressCats##";s:13:"itunes:author";s:10:"##Global##";s:15:"itunes:explicit";s:7:"Default";s:12:"itunes:block";s:7:"Default";}'
dsq_thread_id:
  - "2027018727"
bitly_url:
  - http://bit.ly/1UbRurP
bitly_hash:
  - 1UbRurP
bitly_long_url:
  - http://www.acercadelaeducacion.com.ar/2008/03/ellen-miguel-abuelo-y-calamaro/
categories:
  - Novedades
tags:
  - Andrés Calamaro
  - Ellen Howard
  - los chicos
  - Miguel Abuelo
---
Interminables discusiones (generalmete con motivo de hacerla enojar... cosa que no es difícil) con mi cuñada, Ellen, sobre Calamaro, se zanjan este día. En un humilde homenaje de quien escribe a Miguel Abuelo y en una suerte de reparación histórica con mi cuñada. Dejo uno de los temas que más me gusta de Andrés.
<object height="355" width="425"></object>

<param name="movie" value="http://www.youtube.com/v/2Fg9m9YZhTY&hl=en"></param>
<param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/2Fg9m9YZhTY&hl=en" type="application/x-shockwave-flash" wmode="transparent" height="355" width="425"></embed>


text:
package dnsimple

import (
	"context"
	"io"
	"net/http"
	"net/url"
	"reflect"
	"testing"
)

func TestTemplatePath(t *testing.T) {
	if want, got := "/1010/templates", templatePath("1010", ""); want != got {
		t.Errorf("templatePath(%v) = %v, want %v", "", got, want)
	}

	if want, got := "/1010/templates/1", templatePath("1010", "1"); want != got {
		t.Errorf("templatePath(%v) = %v, want %v", "1", got, want)
	}
}

func TestTemplatesService_List(t *testing.T) {
	setupMockServer()
	defer teardownMockServer()

	mux.HandleFunc("/v2/1010/templates", func(w http.ResponseWriter, r *http.Request) {
		httpResponse := httpResponseFixture(t, "/api/listTemplates/success.http")

		testMethod(t, r, "GET")
		testHeaders(t, r)
		testQuery(t, r, url.Values{})

		w.WriteHeader(httpResponse.StatusCode)
		_, _ = io.Copy(w, httpResponse.Body)
	})

	templatesResponse, err := client.Templates.ListTemplates(context.Background(), "1010", nil)
	if err != nil {
		t.Fatalf("Templates.ListTemplates() returned error: %v", err)
	}

	if want, got := (&Pagination{CurrentPage: 1, PerPage: 30, TotalPages: 1, TotalEntries: 2}), templatesResponse.Pagination; !reflect.DeepEqual(want, got) {
		t.Errorf("Templates.ListTemplates() pagination expected to be %v, got %v", want, got)
	}

	templates := templatesResponse.Data
	if want, got := 2, len(templates); want != got {
		t.Errorf("Templates.ListTemplates() expected to return %v templates, got %v", want, got)
	}

	if want, got := int64(1), templates[0].ID; want != got {
		t.Fatalf("Templates.ListTemplates() returned ID expected to be `%v`, got `%v`", want, got)
	}
	if want, got := "Alpha", templates[0].Name; want != got {
		t.Fatalf("Templates.ListTemplates() returned Name expected to be `%v`, got `%v`", want, got)
	}
}

func TestTemplatesService_List_WithOptions(t *testing.T) {
	setupMockServer()
	defer teardownMockServer()

	mux.HandleFunc("/v2/1010/templates", func(w http.ResponseWriter, r *http.Request) {
		httpResponse := httpResponseFixture(t, "/api/listTemplates/success.http")

		testQuery(t, r, url.Values{"page": []string{"2"}, "per_page": []string{"20"}})

		w.WriteHeader(httpResponse.StatusCode)
		_, _ = io.Copy(w, httpResponse.Body)
	})

	_, err := client.Templates.ListTemplates(context.Background(), "1010", &ListOptions{Page: Int(2), PerPage: Int(20)})
	if err != nil {
		t.Fatalf("Templates.ListTemplates() returned error: %v", err)
	}
}

func TestTemplatesService_Create(t *testing.T) {
	setupMockServer()
	defer teardownMockServer()

	mux.HandleFunc("/v2/1010/templates", func(w http.ResponseWriter, r *http.Request) {
		httpResponse := httpResponseFixture(t, "/api/createTemplate/created.http")

		testMethod(t, r, "POST")
		testHeaders(t, r)

		want := map[string]interface{}{"name": "Beta"}
		testRequestJSON(t, r, want)

		w.WriteHeader(httpResponse.StatusCode)
		_, _ = io.Copy(w, httpResponse.Body)
	})

	accountID := "1010"
	templateAttributes := Template{Name: "Beta"}

	templateResponse, err := client.Templates.CreateTemplate(context.Background(), accountID, templateAttributes)
	if err != nil {
		t.Fatalf("Templates.CreateTemplate() returned error: %v", err)
	}

	template := templateResponse.Data
	if want, got := int64(1), template.ID; want != got {
		t.Fatalf("Templates.CreateTemplate() returned ID expected to be `%v`, got `%v`", want, got)
	}
	if want, got := "Beta", template.Name; want != got {
		t.Fatalf("Templates.CreateTemplate() returned Label expected to be `%v`, got `%v`", want, got)
	}
}

func TestTemplatesService_Get(t *testing.T) {
	setupMockServer()
	defer teardownMockServer()

	mux.HandleFunc("/v2/1010/templates/1", func(w http.ResponseWriter, r *http.Request) {
		httpResponse := httpResponseFixture(t, "/api/getTemplate/success.http")

		testMethod(t, r, "GET")
		testHeaders(t, r)

		w.WriteHeader(httpResponse.StatusCode)
		_, _ = io.Copy(w, httpResponse.Body)
	})

	templateResponse, err := client.Templates.GetTemplate(context.Background(), "1010", "1")
	if err != nil {
		t.Fatalf("Templates.GetTemplate() returned error: %v", err)
	}

	template := templateResponse.Data
	wantSingle := &Template{
		ID:          1,
		SID:         "alpha",
		AccountID:   1010,
		Name:        "Alpha",
		Description: "An alpha template.",
		CreatedAt:   "2016-03-22T11:08:58Z",
		UpdatedAt:   "2016-03-22T11:08:58Z"}

	if !reflect.DeepEqual(template, wantSingle) {
		t.Fatalf("Templates.GetTemplate() returned %+v, want %+v", template, wantSingle)
	}
}

func TestTemplatesService_UpdateTemplate(t *testing.T) {
	setupMockServer()
	defer teardownMockServer()

	mux.HandleFunc("/v2/1010/templates/1", func(w http.ResponseWriter, r *http.Request) {
		httpResponse := httpResponseFixture(t, "/api/updateTemplate/success.http")

		testMethod(t, r, "PATCH")
		testHeaders(t, r)

		w.WriteHeader(httpResponse.StatusCode)
		_, _ = io.Copy(w, httpResponse.Body)
	})

	templateAttributes := Template{Name: "Alpha"}
	templateResponse, err := client.Templates.UpdateTemplate(context.Background(), "1010", "1", templateAttributes)
	if err != nil {
		t.Fatalf("Templates.UpdateTemplate() returned error: %v", err)
	}

	template := templateResponse.Data
	wantSingle := &Template{
		ID:          1,
		SID:         "alpha",
		AccountID:   1010,
		Name:        "Alpha",
		Description: "An alpha template.",
		CreatedAt:   "2016-03-22T11:08:58Z",
		UpdatedAt:   "2016-03-22T11:08:58Z"}

	if !reflect.DeepEqual(template, wantSingle) {
		t.Fatalf("Templates.UpdateTemplate() returned %+v, want %+v", template, wantSingle)
	}
}

func TestTemplatesService_DeleteTemplate(t *testing.T) {
	setupMockServer()
	defer teardownMockServer()

	mux.HandleFunc("/v2/1010/templates/1", func(w http.ResponseWriter, r *http.Request) {
		httpResponse := httpResponseFixture(t, "/api/deleteTemplate/success.http")

		testMethod(t, r, "DELETE")
		testHeaders(t, r)

		w.WriteHeader(httpResponse.StatusCode)
		_, _ = io.Copy(w, httpResponse.Body)
	})

	_, err := client.Templates.DeleteTemplate(context.Background(), "1010", "1")
	if err != nil {
		t.Fatalf("Templates.DeleteTemplate() returned error: %v", err)
	}
}


text:
class IndexController < ApplicationController
  def show
    if user_signed_in?
      redirect_to  controller: :private, action: :index
    end
  end

  def about
  end

  def contact
  end
end


text:
<data>
  <player>Billy</player>
  <player>Brad</player>
  <player>Christian</player>
  <player>Chris</player>
  <player>Dwane</player>
  <player>Jeff</player>
  <player>Magnus</player>
  <player>Matt</player>
  <player>Petr</player>
  <player>Robert</player>
</data>


text:
/*
 *  This file is part of the Wayback archival access software
 *   (http://archive-access.sourceforge.net/projects/wayback/).
 *
 *  Licensed to the Internet Archive (IA) by one or more individual
 *  contributors.
 *
 *  The IA licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.archive.wayback.util.webapp;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.archive.wayback.exception.BadQueryException;

/**
 * Abstract RequestHandler implementation which performs the minimal behavior
 * for self registration with a RequestMapper, requiring subclasses to implement
 * only handleRequest().
 *
 * @author brad
 *
 */
public abstract class AbstractRequestHandler implements RequestHandler {
	private String beanName = null;
	private String accessPointPath = null;
	private ServletContext servletContext = null;
	private int internalPort = 0;

	public void setBeanName(final String beanName) {
		this.beanName = beanName;
	}

	public String getBeanName() {
		return beanName;
	}

	public int getInternalPort() {
		return internalPort;
	}

	public void setInternalPort(int internalPort) {
		this.internalPort = internalPort;
	}

	public String getAccessPointPath() {
		return accessPointPath;
	}

	public void setAccessPointPath(String accessPointPath) {
		this.accessPointPath = accessPointPath;
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	public ServletContext getServletContext() {
		return servletContext;
	}

	// Refactor: this method is only called by RequestMapper, and eventually
	// calls RequestMapper.addRequestHandler() through static method BeanNameRegistrar.registerHandler().
	// AbstractRequestHandler does not play any active role there.  Move this code to RequestMapper.
	/**
	 * @deprecated 2014-04-24 call {@link BeanNameRegistrar#registerHandler(RequestHandler, RequestMapper)} directly.
	 */
	public void registerPortListener(RequestMapper requestMapper) {
		BeanNameRegistrar.registerHandler(this, requestMapper);
	}

	/**
	 * @deprecated 2014-04-23 use {@link RequestMapper#getRequestContextPath(HttpServletRequest)} directly.
	 */
	public String translateRequestPath(HttpServletRequest httpRequest) {
		return RequestMapper.getRequestContextPath(httpRequest);
	}

	/**
	 * @deprecated 2014-04-23 use {@link RequestMapper#getRequestContextPathQuery(HttpServletRequest)} directly
	 */
	public String translateRequestPathQuery(HttpServletRequest httpRequest) {
		return RequestMapper.getRequestContextPathQuery(httpRequest);
	}

	// Refactor: move getMapParam, getRequiredMapParam and getMapParamOrEmpty
	// to RequestParser base class.
	/**
	 * Extract the first value in the array mapped to by field in queryMap
	 * @param queryMap the Map in which to search
	 * @param field the field value desired
	 * @return the first value in the array mapped to field in queryMap, if
	 * present, null otherwise
	 */
	public static String getMapParam(Map<String,String[]> queryMap,
			String field) {
		String arr[] = queryMap.get(field);
		if (arr == null || arr.length == 0) {
			return null;
		}
		return arr[0];
	}

	/**
	 * Extract the first value in the array mapped to by field in queryMap
	 * @param queryMap the Map in which to search
	 * @param field the field value desired
	 * @return the first value in the array mapped to field in queryMap, if
	 * present. A BadQueryException is thrown if there is no appropriate value
	 * @throws BadQueryException if there is nothing mapped to field, or if the
	 * Array mapped to field is empty
	 */
	public static String getRequiredMapParam(Map<String, String[]> queryMap,
			String field) throws BadQueryException {
		// TODO: Throw something different, org.archive.wayback.util should have
		// no references outside of org.archive.wayback.util
		String value = getMapParam(queryMap, field);
		if (value == null) {
			throw new BadQueryException("missing field " + field);
		}
		if (value.length() == 0) {
			throw new BadQueryException("empty field " + field);
		}
		return value;
	}

	/**
	 * Extract the first value in the array mapped to by field in queryMap
	 * @param map the Map in which to search
	 * @param param the field value desired
	 * @return the first value in the array mapped to field in queryMap, if
	 * present, or an empty string otherwise
	 */
	public static String getMapParamOrEmpty(Map<String,String[]> map,
			String param) {
		String val = getMapParam(map, param);
		return (val == null) ? "" : val;
	}
}


text:
/*  ___ _  ___ _ _                                                                                *\
** / __| |/ (_) | |     Your SKilL scala Binding                                                                      **
** \__ \ ' <| | | |__   generated: 01.02.2019                                                                         **
** |___/_|\_\_|_|____|  by: feldentm                                                                                **
\*                                                                                */
package de.ust.skill.sir.api.internal

import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ListBuffer
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet
import scala.collection.mutable.WrappedArray

import java.nio.BufferUnderflowException
import java.nio.MappedByteBuffer
import java.util.Arrays

import de.ust.skill.common.jvm.streams.MappedInStream
import de.ust.skill.common.jvm.streams.MappedOutStream
import de.ust.skill.common.scala.api.PoolSizeMissmatchError
import de.ust.skill.common.scala.api.RestrictionCheckFailed
import de.ust.skill.common.scala.api.SkillObject
import de.ust.skill.common.scala.internal.AutoField
import de.ust.skill.common.scala.internal.BulkChunk
import de.ust.skill.common.scala.internal.Chunk
import de.ust.skill.common.scala.internal.DistributedField
import de.ust.skill.common.scala.internal.IgnoredField
import de.ust.skill.common.scala.internal.FieldDeclaration
import de.ust.skill.common.scala.internal.KnownField
import de.ust.skill.common.scala.internal.LazyField
import de.ust.skill.common.scala.internal.SimpleChunk
import de.ust.skill.common.scala.internal.SingletonStoragePool
import de.ust.skill.common.scala.internal.fieldTypes._
import de.ust.skill.common.scala.internal.restrictions._

/**
 * restriction[] UserdefinedType.restrictions
 */
final class F_UserdefinedType_restrictions(
  _index : Int,
  _owner : UserdefinedTypePool,
  _type : FieldType[scala.collection.mutable.ArrayBuffer[_root_.de.ust.skill.sir.Restriction]])
    extends FieldDeclaration[scala.collection.mutable.ArrayBuffer[_root_.de.ust.skill.sir.Restriction],_root_.de.ust.skill.sir.UserdefinedType](_type,
      "restrictions",
      _index,
      _owner)
    with KnownField[scala.collection.mutable.ArrayBuffer[_root_.de.ust.skill.sir.Restriction],_root_.de.ust.skill.sir.UserdefinedType] {

  override def createKnownRestrictions : Unit = {

  }

  override def read(part : MappedInStream, target : Chunk) {
    val d = owner.data
    val in = part.view(target.begin.toInt, target.end.toInt)

    try {
        target match {
          case c : SimpleChunk ⇒
            var i = c.bpo.toInt
            val high = i + c.count
            while (i != high) {
              d(i).asInstanceOf[_root_.de.ust.skill.sir.UserdefinedType].Internal_restrictions = t.read(in).asInstanceOf[scala.collection.mutable.ArrayBuffer[_root_.de.ust.skill.sir.Restriction]]
              i += 1
            }
          case bci : BulkChunk ⇒
            val blocks = owner.blocks
            var blockIndex = 0
            while (blockIndex < bci.blockCount) {
              val b = blocks(blockIndex)
              blockIndex += 1
              var i = b.bpo
              val end = i + b.dynamicCount
              while (i != end) {
                d(i).asInstanceOf[_root_.de.ust.skill.sir.UserdefinedType].Internal_restrictions = t.read(in).asInstanceOf[scala.collection.mutable.ArrayBuffer[_root_.de.ust.skill.sir.Restriction]]
                i += 1
              }
            }
        }
    } catch {
      case e : BufferUnderflowException ⇒
        throw new PoolSizeMissmatchError(dataChunks.size - 1,
          part.position() + target.begin,
          part.position() + target.end,
          this, in.position())
    }

    if(!in.eof())
      throw new PoolSizeMissmatchError(dataChunks.size - 1,
        part.position() + target.begin,
        part.position() + target.end,
        this, in.position())
  }

  def offset: Unit = {
    val data = owner.data
    var result = 0L
    dataChunks.last match {
      case c : SimpleChunk ⇒
        var i = c.bpo.toInt
        val high = i + c.count
        while (i != high) {
          val v = data(i).asInstanceOf[_root_.de.ust.skill.sir.UserdefinedType].Internal_restrictions
          result += (if(null == v) 1 else V64.offset(v.size))

          if(null != v) v.foreach { v => result += (if (null == v) 1 else V64.offset(v.getSkillID)) }
          i += 1
        }
      case bci : BulkChunk ⇒
        val blocks = owner.blocks
        var blockIndex = 0
        while (blockIndex < bci.blockCount) {
          val b = blocks(blockIndex)
          blockIndex += 1
          var i = b.bpo
          val end = i + b.dynamicCount
          while (i != end) {
          val v = data(i).asInstanceOf[_root_.de.ust.skill.sir.UserdefinedType].Internal_restrictions
          result += (if(null == v) 1 else V64.offset(v.size))

          if(null != v) v.foreach { v => result += (if (null == v) 1 else V64.offset(v.getSkillID)) }
          i += 1
          }
        }
    }
    cachedOffset = result
  }

  def write(out: MappedOutStream): Unit = {
    val data = owner.data
    dataChunks.last match {
      case c : SimpleChunk ⇒
        var i = c.bpo.toInt
        val high = i + c.count
        while (i != high) {
          val v = data(i).asInstanceOf[_root_.de.ust.skill.sir.UserdefinedType].Internal_restrictions
          if(null == v) out.i8(0) else { out.v64(v.size)

            v.foreach { v => if (null == v) out.i8(0) else out.v64(v.getSkillID) }}
          i += 1
        }
      case bci : BulkChunk ⇒
        val blocks = owner.blocks
        var blockIndex = 0
        while (blockIndex < bci.blockCount) {
          val b = blocks(blockIndex)
          blockIndex += 1
          var i = b.bpo
          val end = i + b.dynamicCount
          while (i != end) {
            val v = data(i).asInstanceOf[_root_.de.ust.skill.sir.UserdefinedType].Internal_restrictions
            if(null == v) out.i8(0) else { out.v64(v.size)

            v.foreach { v => if (null == v) out.i8(0) else out.v64(v.getSkillID) }}
            i += 1
          }
        }
    }
  }
  // note: reflective field access will raise exception for ignored fields
  override def getR(i : SkillObject) : scala.collection.mutable.ArrayBuffer[_root_.de.ust.skill.sir.Restriction] = i.asInstanceOf[_root_.de.ust.skill.sir.UserdefinedType].restrictions
  override def setR(i : SkillObject, v : scala.collection.mutable.ArrayBuffer[_root_.de.ust.skill.sir.Restriction]) {
    i.asInstanceOf[_root_.de.ust.skill.sir.UserdefinedType].restrictions = v.asInstanceOf[scala.collection.mutable.ArrayBuffer[_root_.de.ust.skill.sir.Restriction]]
  }
}


text:
package leo.datastructures

import leo.{Checked, LeoTestSuite}
/**
 * This test checks if the number of predefined symbols is coherent with the
 * description in [[leo.modules.HOLSignature]].
 *
 * @author Alexander Steen
 * @since 05.05.2014
 */
class HOLSignatureTest extends LeoTestSuite {
  import leo.modules.HOLSignature._
  test("Cardinality of fixed symbols",Checked) {
    assertResult(11)(fixedConsts.length)
  }
  test("cardinality of defined symbols",Checked) {
    assertResult(9)(definedConsts.length)
  }
  test("cardinality of type symbols",Checked) {
    assertResult(5)(types.length)
  }
}


text:
def base(request):
    return {'dcbase_need_tz_offset': getattr(request, 'needTzOffset', False)}