text:
@interface ImageFiltersViewController ()
<UIPickerViewDataSource, UIPickerViewDelegate>
@property (nonatomic, weak) IBOutlet UIImageView *imageView;
@property (nonatomic, strong) UIImage *orgImage;
@property (nonatomic, strong) NSArray *items;
@end

@implementation ImageFiltersViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.orgImage = [UIImage imageNamed:@"sample.jpg"];
    self.imageView.image = self.orgImage;

    self.items = @[@"Original",
//                   @"CIBlendWithAlphaMask",
//                   @"CIColorClamp",
//                   @"CIColorCrossPolynomial",
//                   @"CIColorCubeWithColorSpace",
//                   @"CIColorPolynomial",
//                   @"CIConvolution3X3",
//                   @"CIConvolution5X5",
//                   @"CIConvolution7X7",
//                   @"CIConvolution9Horizontal",
//                   @"CIConvolution9Vertical",
                   @"CILinearToSRGBToneCurve",
                   @"CIPhotoEffectChrome",
                   @"CIPhotoEffectFade",
                   @"CIPhotoEffectInstant",
                   @"CIPhotoEffectMono",
                   @"CIPhotoEffectNoir",
                   @"CIPhotoEffectProcess",
                   @"CIPhotoEffectTonal",
                   @"CIPhotoEffectTransfer",
                   @"CISRGBToneCurveToLinear",
                   @"CIVignetteEffect",
                   ];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

// =============================================================================
#pragma mark - UIPickerViewDataSource

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {

    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {

    return self.items.count;
}

// =============================================================================
#pragma mark - UIPickerViewDelegate

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {

    return self.items[row];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    if (row == 0) {

        self.imageView.image = self.orgImage;

        return;
    }

    CIImage *ciImage = [[CIImage alloc] initWithImage:self.orgImage];

    CIFilter *filter = [CIFilter filterWithName:self.items[row]
                                  keysAndValues:kCIInputImageKey, ciImage, nil];
    [filter setDefaults];

    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *outputImage = [filter outputImage];
    CGImageRef cgImage = [context createCGImage:outputImage
                                       fromRect:[outputImage extent]];

    self.imageView.image = [UIImage imageWithCGImage:cgImage];

    CGImageRelease(cgImage);
}

@end

redpajama_set_name: RedPajamaGithub


text:
package com.alibaba.json.bvt.support.jaxrs.mock.entity;

import java.util.List;

/**
 *
Title: FastJsonParentTestVO

 *
Description:

 *
 * @since 2016年4月20日
 * @author Victor.Zxy
 * @version 1.0
 */
public class FastJsonParentTestVO {

	private String name;

	private List<FastJsonSonTestVO> sonList;

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * @param name the name to set
	 */
	public void setName(String name) {
		this.name = name;
	}

	/**
	 * @return the sonList
	 */
	public List<FastJsonSonTestVO> getSonList() {
		return sonList;
	}

	/**
	 * @param sonList the sonList to set
	 */
	public void setSonList(List<FastJsonSonTestVO> sonList) {
		this.sonList = sonList;
	}

}


text:
layout: post
title: "Zoom: Learn How Databases Work: NoSQL & SQL"
categories: database
tags: [meetup, databases, sql, nosql, mongodb]
excerpt: Databases are what you use to store data in all applications and there are two main ways to store data in a database SQL and NOSQL, but how are they different?
date: 2021-03-02
link: https://www.meetup.com/Astrolabs-Digital-Tech/events/276380848/
---

> Databases are what you use to store data in all applications and there are two main ways to store data in a database: SQL and NOSQL, but how are they different?

In this meetup, we'll be going over:

- How databases work
- How we use databases with backend systems, API's and apps
- What an SQL database is
- What a NOSQL database is
- How to relate tables together (using keys)
- How NOSQL relates data (in an unstructured way)
- Which database is better? (we actually have an answer)

[Hope to see you there!](https://www.meetup.com/Astrolabs-Digital-Tech/events/276380848/)


text:
/* This file is derivative of us_ticker.c from BEETLE */

#include <stddef.h>
#include "cmsis.h"
#include "us_ticker_api.h"
#include "PeripheralNames.h"

#define TIMER_MAX_VALUE  0

/* Private data */
struct us_ticker_drv_data_t {
    uint32_t inited;          /* us ticker initialized */
    uint32_t overflow_delta;  /* us ticker overflow */
    uint32_t overflow_limit;  /* us ticker overflow limit */
};

static struct us_ticker_drv_data_t us_ticker_drv_data = {
    .inited = 0,
    .overflow_delta = 0,
    .overflow_limit = 0
};

void __us_ticker_irq_handler(void)
{
    Timer_ClearInterrupt(TIMER1);
    /*
     * For each overflow event adds the timer max represented value to
     * the delta. This allows the us_ticker to keep track of the elapsed
     * time:
     * elapsed_time = (num_overflow * overflow_limit) + current_time
     */
    us_ticker_drv_data.overflow_delta += us_ticker_drv_data.overflow_limit;
}

void us_ticker_init(void)
{
    uint32_t us_ticker_irqn0 = 0;
    uint32_t us_ticker_irqn1 = 0;

    if (us_ticker_drv_data.inited) {
        return;
    }

    us_ticker_drv_data.inited = 1;

    /* Initialize Timer 0 */
    Timer_Initialize(TIMER0, TIMER_MAX_VALUE);
    /* Enable Timer 0 */
    Timer_Enable(TIMER0);

    /* Initialize Timer 1 */
    Timer_Initialize(TIMER1, TIMER_MAX_VALUE);
    /* Enable Timer 1 */
    Timer_Enable(TIMER1);

    /* Timer 0 get IRQn */
    us_ticker_irqn0 = Timer_GetIRQn(TIMER0);
    NVIC_SetVector((IRQn_Type)us_ticker_irqn0, (uint32_t)us_ticker_irq_handler);
    NVIC_EnableIRQ((IRQn_Type)us_ticker_irqn0);

    /* Timer 1 get IRQn */
    us_ticker_irqn1 = Timer_GetIRQn(TIMER1);
    NVIC_SetVector((IRQn_Type)us_ticker_irqn1, (uint32_t)__us_ticker_irq_handler);
    NVIC_EnableIRQ((IRQn_Type)us_ticker_irqn1);

    /* Timer set interrupt on TIMER1 */
    Timer_SetInterrupt(TIMER1, TIMER_DEFAULT_RELOAD);

    /*
     * Set us_ticker Overflow limit. The us_ticker overflow limit is required
     * to calculated the return value of the us_ticker read function in us
     * on 32bit.
     * A 32bit us value cannot be represented directly in the Timer Load
     * register if it is greater than (0xFFFFFFFF ticks)/TIMER_DIVIDER_US.
     */
    us_ticker_drv_data.overflow_limit = Timer_GetReloadValue(TIMER1);
}

uint32_t us_ticker_read()
{
    uint32_t return_value = 0;

    if (!us_ticker_drv_data.inited) {
        us_ticker_init();
    }

    return_value = us_ticker_drv_data.overflow_delta + Timer_Read(TIMER1);

    return return_value;
}

void us_ticker_set_interrupt(timestamp_t timestamp)
{
    int32_t delta = 0;

    if (!us_ticker_drv_data.inited) {
        us_ticker_init();
    }

    delta = (int32_t)(timestamp - us_ticker_read());

    /* Check if the event was in the past */
    if (delta <= 0) {
        /* This event was in the past */
        Timer_SetInterrupt(TIMER0, 0);
    } else {
        /* If the event was not in the past enable interrupt */
        Timer_SetInterrupt(TIMER0, delta);
    }
}

void us_ticker_disable_interrupt(void)
{
    Timer_DisableInterrupt(TIMER0);
}

void us_ticker_clear_interrupt(void)
{
    Timer_ClearInterrupt(TIMER0);
}


text:
package com.phoenixnap.oss.ramlplugin.raml2code.raml;

/**
 * Enumeration of a Raml Types
 *
 * @author armin.weisser
 * @since 0.8.1
 */
public enum RamlParamType {
	STRING, NUMBER, INTEGER, DATE, FILE, BOOLEAN, DATA_TYPE;
}


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

namespace Starbuzz_DecoratorPattern
{
    public class Soy : CondimentDecorator
    {
        private Beverage _beverage;

        public Soy(Beverage beverage)
        {
            this._beverage = beverage;
        }

        public override string Description
        {
            get { return _beverage.Description + ", Soy"; }
        }

        public override double Cost
        {
            get
            {
                switch (_beverage.Size)
                {
                    case BeverageSize.TALL: return _beverage.Cost + .10;
                    case BeverageSize.GRANDLE: return _beverage.Cost + .15;
                    case BeverageSize.VENTI: return _beverage.Cost + .20;
                }
                return _beverage.Cost;
            }
        }
    }
}


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

namespace Alphicsh.Audio.Metadata.Id3v2.Frames
{
    /// <summary>
    /// A class representing integer ID3v2 frame contents.
    /// </summary>
    public class IntegerFrameContent : TextFrameContent, IIntegerFrameContent
    {
        public Int64 Number { get; private set; }

        /// <summary>
        /// Creates a new integer frame content, based on string representation provided.
        /// </summary>
        /// <param name="text">The string representation of the integer.</param>
        public IntegerFrameContent(String text)
            : base(text)
        {
            Number = Convert.ToInt64(text);
        }
    }
}


text: $$ to be the image of the cylinder $$


text:
require 'rexml/parsers/sax2parser'
require 'rexml/sax2listener'

xml = File.read(ARGV[0])
parser = REXML::Parsers::SAX2Parser.new(xml)

parser.listen(:start_element) do |uri, local, qname, attrs|
    puts "start element: #{uri}"
    puts "start element: #{local}"
    puts "start element: #{qname}"
    puts "start element: #{attrs}"
end

parser.listen(:end_element) do |uri, local, qname|
    puts "end element: #{uri}"
    puts "end element: #{local}"
    puts "end element: #{qname}"
end

parser.parse


text:
(*

category:      Test
synopsis:      Single forward reaction with two species in one compartment and three events
componentTags: CSymbolTime, Compartment, EventNoDelay, EventPriority, Species
testTags:      Amount, EventIsNotPersistent, EventIsPersistent
testType:      TimeCourse
levels:        3.1
generatedBy:   Analytic

The model contains three events that assign value to species S1 and S2 defined below.

The events will execute simultaneously and must be executed in order determined by
the Priority. However, since Event2 is not persistent, the execution of Event1
causes the Trigger of Event2 to return to 'false'. It must therefore be removed
from the list of pending events.

The model contains:
* 2 species (S1, S2)
* 1 compartment (C)

There are 3 events:

[{width:40em,margin: 1em auto}|  *Event*  |  *Trigger*  |  *Priority*  |  *Persistent*  | *Event Assignments* |
| A | $and(geq(time, 0.99), lt(S1, 0.5))$ | $10$ | true | $S1 = 1$ |
|  |  |  |  | $S2 = 0$ |
| B | $and(geq(time, 0.99), lt(S1, 0.5))$ | $8$ | false | $S1 = 2$ |
|  |  |  |  | $S2 = 1$ |
| C1 | $and(geq(time, 0.99), lt(S1, 0.5))$ | $9$ | true | $S1 = 3$ |
|  |  |  |  | $S2 = 2$ |]

The initial conditions are as follows:

[{width:35em,margin: 1em auto}|       | *Value* | *Constant* |
| Initial amount of species S1 | $0$ | variable |
| Initial amount of species S2 | $1$ | variable |
| Initial volume of compartment 'C' | $1$ | constant |]

The species' initial quantities are given in terms of substance units to
make it easier to use the model in a discrete stochastic simulator, but
their symbols represent their values in concentration units where they
appear in expressions.

Note: The test data for this model was generated from an analytical
solution of the system of equations.

*)


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.N863.html">

Redirecting to type.N863.html...


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Schalk Neethling</title>
  <meta name="author" content="Schalk Neethling">

  <meta name="description" content="Developing for the modern web has a lot of challenges. Some has been overcome and addressed by the evolution of HTML, and there are lots still being …">

  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="canonical" href="http://schalkneethling.github.io/posts/2/">
  <link href="/favicon.png" rel="icon">
  <link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css">
  <link href="/atom.xml" rel="alternate" title="Schalk Neethling" type="application/atom+xml">

<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700' rel='stylesheet' type='text/css' />

  <hgroup>

Schalk Neethling

Scripting on Caffiene

</hgroup>

RSS

<form action="https://duckduckgo.com/?q=" method="get">
  <fieldset role="search">
    <input type="hidden" name="sitesearch" value="schalkneethling.github.io">
    <input class="search" type="text" name="q" results="0" placeholder="Search"/>
  </fieldset>
</form>

Blog

Archives

About

Image Loading Helpers in the Bedrock, Aka mozilla.org, Codebase

<time class='entry-date' datetime='2015-08-11T12:40:22+02:00'>Aug 11th, 2015 12:40 pm</time>

           | Comments

Developing for the modern web has a lot of challenges. Some has been overcome and addressed by the evolution of HTML, and there are lots still being actively discussed on the WHAT-WG mailing list, and more and more being implemented by the various browser vendors.

In fact it has grown way beyond just the evolution of HTML and is now an all encompassing goliath, we lovingly call The Open Web Platform. Then there is of course the device ecosystem. Growing and expanding at a dizzying pace. With larger form factors, devices with high density displays, audio and video capabilities that puts many DSLR cameras to shame.

      Read on →

Two Little Known HTML5 Attributes

<time class='entry-date' datetime='2015-08-05T12:40:22+02:00'>Aug 5th, 2015 12:40 pm</time>

           | Comments

The new HTML5 specification has introduced an array of new elements and attributes, some more useful than others, and some better implemented and supported.

Of course, if you want to know whether you can safely use one of these, there is the indispensable caniuse.com. There are some though that has flown below the radar but, that can be very useful.

Here I am going to look at two of these lesser known attributes that I have recently stumbled upon.

      Read on →

Tabzilla Static Released

<time class='entry-date' datetime='2015-07-16T21:55:06+02:00'>Jul 16th, 2015 9:55 pm</time>

           | Comments

Tabzilla, the Mozilla universal tab, has been around for a while and today, we are happy to announce that a new version of Tabzilla has been released. This latest release introduces quite a few changes though so, let's take a look at those.

Firstly, it is now a static ribbon style tab. This means there is no longer a drawer that opens when clicking on the Mozilla wordmark but instead, this will now simply take the user to the landing page for the mozilla.org site.

      Read on →

Squashing a Number of Commits on Master - Git

<time class='entry-date' datetime='2015-07-14T21:55:06+02:00'>Jul 14th, 2015 9:55 pm</time>

           | Comments

I was working on a simple project recently and ended up doing a bunch of work straight on master. Not a good idea, don't do it. But of course you already know all about  using feature branches. Alas, that is the situation I found myself in.

      Read on →

    Blog Archives

    Newer →

Recent Posts

        Html-compiler - Add Includes Support to Your HTML

        Respect User Choice ~ Do Not Track

        Duck It! ~ Useful Bangs for Developers and Other Goodies

GitHub Repos

Status updating...

  @schalkneethling on GitHub

  Copyright © 2016 - Schalk Neethling -
  Powered by Octopress


text:
# How to contribute

## Issue Submission Guidlines

* If you have a problem with your code, please ask your question on stackoverflow.com or the [user group](https://groups.google.com/forum/?fromgroups#!forum/dc-js-user-group)
* It will be far, far easier for others to understand your problem or bug if you demonstrate it with a short example on http://jsfiddle.net/ or on http://bl.ocks.org/
* For bugs and feature requests submit a [github issue](http://github.com/dc-js/dc.js/issues)
  * Please include the version of DC you are using
  * If you can, please try the latest version of DC on the [master](https://raw.github.com/dc-js/dc.js/master/dc.js) branch to see if your issue has already been addressed or is otherwise affected by recent changes.

## Pull Request Guidelines

* Fork the repository
* Make changes to the files in `src/` not dc.js
* Add tests to `spec/`. Feel free to create a new file if needed.
* Run `grunt server` and go to http://localhost:8888/spec to develop your tests.
* Run `grunt lint` to fix any final linting issues via jshint.
* Run `grunt test` to confirm that all tests will pass on phantomjs.
* Run `grunt jshint` and `grunt jscs` to confirm that your code meets the dc.js style guidelines
* Commit your changes to `src/*` and `spec/*` but not any build artifacts.  (Build artifacts include `dc.*js*`, `web/docs/*`, `web/js/*`)
* Submit a pull request
* If you merge master or another branch into your patchset, please rebase against master.
* The DC maintainer team will review and build the artifacts when merging
* If you continue making changes to your fork of `dc.js`, create a branch for each pull request

#### Coding Conventions

* Avoid tabs and trailing whitespace
* Please try to follow the existing code formatting
* We use jshint and jscs to verify most of our coding conventions

It helps keep on top of the conventions if you create a git pre-commit hook `.git/hooks/pre-commit`:
```
#!/usr/bin/env sh

grunt jshint
grunt jscs
```

(You also need to make it executable with  `chmod u+x .git/hooks/pre-commit`)

Or you can just run the commands manually before committing.

#### Testing Notes

Running `grunt server` will host the jasmine specs at http://localhost:8888/spec.
Please use `.transitionDuration(0)` for all chart tests.

# Merging Pull Requests

_for maintainers_

Ensure origin looks like this in `.git/config`. The key element here is the second fetch statement
```
[remote "origin"]
  url = git@github.com:dc-js/dc.js.git
  fetch = +refs/heads/*:refs/remotes/origin/*
  fetch = +refs/pull/*/head:refs/remotes/origin/pr/*
```

Run these commands (or their approximation):
```
# clean master branch
git stash

# update node modules that may be pulled into `web/`
npm update

# double check your aren't going to blow away local commits
git fetch origin
git checkout master
git diff origin/master

# Merge - subsitute the PR number for $PR. Warning this runs git reset --hard, ensure you are ready
grunt merge:$PR

# manually verify the changes and review the demos/examples

# deploy
git push origin master

# review changes before site deployment
git diff origin/gh-pages master:web
grunt web
```

If needed, the baseline test for the demos can be rebuilt by running `grunt update-stock-regression`.


text:
local clu = require "clu/prelude"
local lpeg = require "lpeg"
local ast = require "peg/ast"
local pl   = require "pl.pretty"
local util = require "util"
local tableand = util.tableand

-- peg rules. Don't belong here, but this is the
-- only parser we have for awhile.

local p = clu.env.palette

 testrules = { atom           = {"White","Clear"},
  			   pattern        = {"Blue","Clear"},
  			   optional       = {"Green","Clear"},
  			   more_than_one  = {"Green","Clear"},
  			   some_number    = {"Green","Clear"},
  			   some_suffix    = {"Green","Clear"},
  			   which_suffix   = {"Green","Clear"},
  			   maybe          = {"Green","Clear"},
  			   set            = {"Yellow","Clear"},
  			   range          = {"Yellow","Clear"},
  			   literal        = {"Yellow","Clear"},
  			   PEL            = {"Grey","Clear"},
  			   PER            = {"Grey","Clear"},
  			   hidden_rule    = {"Cyan","Clear"},
  			   hidden_pattern = {"Cyan","Clear"},
  			   hidden_match   = {"Cyan","Clear"},
  			   repeats        = {"Red","Clear"},
  			   comment        = {"Grey","Clear"}}

function makerules(rules)
 	local rule_table = {}
 	local p = nil
 		-- this logic belongs in a palette
		-- object which may be called.
 	if clu.env.ansi then
		p = clu.env.palette.default
	else
		p = clu.env.palette.no_color
	end
	for k,v in pairs(rules) do
		if type(v) == "table" then
			rule_table[k] = { p[v[1]] , p[v[2]] }
		else -- string or function
			error "error in makerules, non-table values NYI"
		end
	end
	return rule_table
end

--local testrules = { atom = {"",""}, lhs = {"",""}}

-- wraps a value in a rule, or
-- returns it if the rule is nil.
local function rulewrap_value(ast,rules)
	 if rules[ast.id] then
	 	local rule = rules[ast.id]
	 	if type (rule) == "string" then -- pre only
		 	return rule..ast.val..p.Clear
		elseif type (rule) == "table" then -- pre and post
			return rule[1]..ast.val..rule[2]
		elseif type (rule) == "function" then -- function over value
			print "function reached in rulewrap_value"
			return ""
		end
	 else
	 	return ast.val
	 end
end

local function rulewrap_open(ast,rules)
	if rules[ast.id] then
		local rule = rules[ast.id]
		if type(rule) == "string" then -- pre only
			return rule
		elseif type(rule) == "table" then -- use pre
			return rule[1]
		elseif type(rule) == "function" then -- fn over span
			print "function reached in rulewrap_start"
			return ""
		end
	else
		return ""
	end
end

local function rulewrap_close(ast,rules)
	if rules[ast.id] then
		local rule = rules[ast.id]
		if type(rule) == "string" then
			return ""
		elseif type(rule) == "table" then
			return rule[2]
		elseif type(rule) == "function" then
			print "function reached in rulewrap_close"
			return ""
		end
	else
		return ""
	end
end

--- highlights a Node.
-- uses spans and the original string.
-- anything not collected by the grammar is
-- quoted verbatim, so if the context is Red,
-- it will be Red also.
-- @function light
-- @param ast the parsed string
-- @param rules the rule table
-- @return highlighted string
local function light(ast, rules)
	if rules then
		rules = makerules(rules)
	else
		rules = makerules(testrules)
	end

	local source = ast:root().str
	local queue = {}
	local phrase = ""
	local cursor = 1
	local gap = ""
	local ndx, first, last = ast:range()
	local new = true
	for i = first, last do
		local node, close, _ = ndx(i)
		if rules[node.id]
		  and node.val == nil then -- open regional rule
			gap = source:sub(cursor,node.first-1)
			cursor = node.first
			queue[close] = node
			phrase = phrase..gap..rulewrap_open(node,rules)
		elseif node.id and node.val then -- wrap values in rule
			if new then
				phrase = phrase..source:sub(1,ndx[1].first-1)
				new = false
			end
			if cursor <= node.first then
				  gap = source:sub(cursor,node.first-1)
			end
			cursor = node.last+1
			phrase = phrase..gap..rulewrap_value(node,rules)
		end
		if queue[i] then -- close regional rule
			gap = source:sub(cursor,queue[i].last-1)
			cursor = queue[i].last
			phrase = phrase
			         ..rulewrap_open(queue[i],rules)
			         ..gap
			         ..rulewrap_close(queue[i],rules)
		end
	end
	phrase = phrase..source:sub(cursor,-1)
	return phrase
end

--- generates a highlighter from a rule table
-- @function Highlighter
-- @param parser a parser
-- @param rules a palette
-- @return a function: λ (string|Node) -> string
local function Highlighter(parser, rules)
	local function lighter(source)
		if type(source) == "string" then
			source = ast.parse(parser,source)
		end
		return light(source, rules)
	end
	return lighter
end

return {Highlighter = Highlighter,
		light = light}


text:
class DisabledAction(Exception):
    """
    Disallowed action when overriding
    """
    pass

class InvalidInputFormData(Exception):
    """
    malformed syntax in the form input data
    """
    pass

class NotInstructorError(Exception):
    """
    Unauthorized (not instructor of the course)
    """
    pass


text:
/* LCM type definition class file
 * This file was automatically generated by lcm-gen
 * DO NOT MODIFY BY HAND!!!!
 */

package forseti2;

import java.io.*;
import java.util.*;
import lcm.lcm.*;

public final class ConfigData implements lcm.lcm.LCMEncodable
{
    public String ConfigFile;
    public boolean IsBlueAlliance;
    public int TeamNumber;
    public String TeamName;
    public String FieldObjects;

    public ConfigData()
    {
    }

    public static final long LCM_FINGERPRINT;
    public static final long LCM_FINGERPRINT_BASE = 0xc15df5794e626493L;

    static {
        LCM_FINGERPRINT = _hashRecursive(new ArrayList<Class<?>>());
    }

    public static long _hashRecursive(ArrayList<Class<?>> classes)
    {
        if (classes.contains(forseti2.ConfigData.class))
            return 0L;

        classes.add(forseti2.ConfigData.class);
        long hash = LCM_FINGERPRINT_BASE
            ;
        classes.remove(classes.size() - 1);
        return (hash<<1) + ((hash>>63)&1);
    }

    public void encode(DataOutput outs) throws IOException
    {
        outs.writeLong(LCM_FINGERPRINT);
        _encodeRecursive(outs);
    }

    public void _encodeRecursive(DataOutput outs) throws IOException
    {
        char[] __strbuf = null;
        __strbuf = new char[this.ConfigFile.length()]; this.ConfigFile.getChars(0, this.ConfigFile.length(), __strbuf, 0); outs.writeInt(__strbuf.length+1); for (int _i = 0; _i < __strbuf.length; _i++) outs.write(__strbuf[_i]); outs.writeByte(0);

        outs.writeByte( this.IsBlueAlliance ? 1 : 0);

        outs.writeInt(this.TeamNumber);

        __strbuf = new char[this.TeamName.length()]; this.TeamName.getChars(0, this.TeamName.length(), __strbuf, 0); outs.writeInt(__strbuf.length+1); for (int _i = 0; _i < __strbuf.length; _i++) outs.write(__strbuf[_i]); outs.writeByte(0);

        __strbuf = new char[this.FieldObjects.length()]; this.FieldObjects.getChars(0, this.FieldObjects.length(), __strbuf, 0); outs.writeInt(__strbuf.length+1); for (int _i = 0; _i < __strbuf.length; _i++) outs.write(__strbuf[_i]); outs.writeByte(0);

    }

    public ConfigData(byte[] data) throws IOException
    {
        this(new LCMDataInputStream(data));
    }

    public ConfigData(DataInput ins) throws IOException
    {
        if (ins.readLong() != LCM_FINGERPRINT)
            throw new IOException("LCM Decode error: bad fingerprint");

        _decodeRecursive(ins);
    }

    public static forseti2.ConfigData _decodeRecursiveFactory(DataInput ins) throws IOException
    {
        forseti2.ConfigData o = new forseti2.ConfigData();
        o._decodeRecursive(ins);
        return o;
    }

    public void _decodeRecursive(DataInput ins) throws IOException
    {
        char[] __strbuf = null;
        __strbuf = new char[ins.readInt()-1]; for (int _i = 0; _i < __strbuf.length; _i++) __strbuf[_i] = (char) (ins.readByte()&0xff); ins.readByte(); this.ConfigFile = new String(__strbuf);

        this.IsBlueAlliance = ins.readByte()!=0;

        this.TeamNumber = ins.readInt();

        __strbuf = new char[ins.readInt()-1]; for (int _i = 0; _i < __strbuf.length; _i++) __strbuf[_i] = (char) (ins.readByte()&0xff); ins.readByte(); this.TeamName = new String(__strbuf);

        __strbuf = new char[ins.readInt()-1]; for (int _i = 0; _i < __strbuf.length; _i++) __strbuf[_i] = (char) (ins.readByte()&0xff); ins.readByte(); this.FieldObjects = new String(__strbuf);

    }

    public forseti2.ConfigData copy()
    {
        forseti2.ConfigData outobj = new forseti2.ConfigData();
        outobj.ConfigFile = this.ConfigFile;

        outobj.IsBlueAlliance = this.IsBlueAlliance;

        outobj.TeamNumber = this.TeamNumber;

        outobj.TeamName = this.TeamName;

        outobj.FieldObjects = this.FieldObjects;

        return outobj;
    }

}


text:
require "minitest/autorun"
require "webmock/minitest"
require "rule_io"

def fixture_path
  File.expand_path("../fixtures", __FILE__)
end

def fixture(file)
  File.read(fixture_path + "/" + file)
end


text:
package base.mvp;

import android.support.annotation.NonNull;

import base.domain.UseCaseExecutor;

public abstract class BaseCleanPresenter<VM extends BaseContract.ViewModel> extends BasePresenter<VM> {

    @NonNull
    protected final UseCaseExecutor mUseCaseExecutor;

    protected BaseCleanPresenter(
            @NonNull VM viewModel,
            @NonNull UseCaseExecutor useCaseExecutor) {
        super(viewModel);
        mUseCaseExecutor = useCaseExecutor;
    }
}


text:
package com.saasxx.framework.dao.finder.vo;

import java.util.List;

import com.saasxx.framework.Lang;
import com.saasxx.framework.dao.finder.impl.JoinPathImpl;

/**
 * From信息
 *
 * @author lujijiang
 *
 */
public class FromInfo {
	/**
	 * 实体信息
	 */
	EntityInfo<?> entityInfo;

	/**
	 * Join信息
	 */
	List<JoinPathImpl<?>> joinPaths = Lang.newList();

	public EntityInfo<?> getEntityInfo() {
		return entityInfo;
	}

	public List<JoinPathImpl<?>> getJoinPaths() {
		return joinPaths;
	}

	public FromInfo(EntityInfo<?> entityInfo) {
		super();
		this.entityInfo = entityInfo;
	}

}


text:
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).

```ts

import { AfterContentInit } from '@angular/core';
import { AfterViewInit } from '@angular/core';
import { BooleanInput } from '@angular/cdk/coercion';
import { ContentObserver } from '@angular/cdk/observers';
import { DoCheck } from '@angular/core';
import { ElementRef } from '@angular/core';
import { EventEmitter } from '@angular/core';
import * as i0 from '@angular/core';
import * as i4 from '@angular/cdk/observers';
import { InjectionToken } from '@angular/core';
import { NgZone } from '@angular/core';
import { Observable } from 'rxjs';
import { OnChanges } from '@angular/core';
import { OnDestroy } from '@angular/core';
import { Platform } from '@angular/cdk/platform';
import { QueryList } from '@angular/core';
import { SimpleChanges } from '@angular/core';
import { Subject } from 'rxjs';

// @public (undocumented)
export class A11yModule {
    constructor(highContrastModeDetector: HighContrastModeDetector);
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<A11yModule, never>;
    // (undocumented)
    static ɵinj: i0.ɵɵInjectorDeclaration<A11yModule>;
    // (undocumented)
    static ɵmod: i0.ɵɵNgModuleDeclaration<A11yModule, [typeof i1.CdkAriaLive, typeof i2.CdkTrapFocus, typeof i3.CdkMonitorFocus], [typeof i4.ObserversModule], [typeof i1.CdkAriaLive, typeof i2.CdkTrapFocus, typeof i3.CdkMonitorFocus]>;
}

// @public (undocumented)
export class ActiveDescendantKeyManager<T> extends ListKeyManager<Highlightable & T> {
    setActiveItem(index: number): void;
    setActiveItem(item: T): void;
}

// @public
export class AriaDescriber implements OnDestroy {
    constructor(_document: any,
    _platform?: Platform | undefined);
    describe(hostElement: Element, message: string, role?: string): void;
    describe(hostElement: Element, message: HTMLElement): void;
    ngOnDestroy(): void;
    removeDescription(hostElement: Element, message: string, role?: string): void;
    removeDescription(hostElement: Element, message: HTMLElement): void;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<AriaDescriber, never>;
    // (undocumented)
    static ɵprov: i0.ɵɵInjectableDeclaration<AriaDescriber>;
}

// @public
export type AriaLivePoliteness = 'off' | 'polite' | 'assertive';

// @public @deprecated
export const CDK_DESCRIBEDBY_HOST_ATTRIBUTE = "cdk-describedby-host";

// @public @deprecated
export const CDK_DESCRIBEDBY_ID_PREFIX = "cdk-describedby-message";

// @public
export class CdkAriaLive implements OnDestroy {
    constructor(_elementRef: ElementRef, _liveAnnouncer: LiveAnnouncer, _contentObserver: ContentObserver, _ngZone: NgZone);
    duration: number;
    // (undocumented)
    ngOnDestroy(): void;
    get politeness(): AriaLivePoliteness;
    set politeness(value: AriaLivePoliteness);
    // (undocumented)
    static ɵdir: i0.ɵɵDirectiveDeclaration<CdkAriaLive, "[cdkAriaLive]", ["cdkAriaLive"], { "politeness": "cdkAriaLive"; "duration": "cdkAriaLiveDuration"; }, {}, never, never, false, never>;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<CdkAriaLive, never>;
}

// @public
export class CdkMonitorFocus implements AfterViewInit, OnDestroy {
    constructor(_elementRef: ElementRef<HTMLElement>, _focusMonitor: FocusMonitor);
    // (undocumented)
    readonly cdkFocusChange: EventEmitter<FocusOrigin>;
    // (undocumented)
    get focusOrigin(): FocusOrigin;
    // (undocumented)
    ngAfterViewInit(): void;
    // (undocumented)
    ngOnDestroy(): void;
    // (undocumented)
    static ɵdir: i0.ɵɵDirectiveDeclaration<CdkMonitorFocus, "[cdkMonitorElementFocus], [cdkMonitorSubtreeFocus]", ["cdkMonitorFocus"], {}, { "cdkFocusChange": "cdkFocusChange"; }, never, never, false, never>;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<CdkMonitorFocus, never>;
}

// @public
export class CdkTrapFocus implements OnDestroy, AfterContentInit, OnChanges, DoCheck {
    constructor(_elementRef: ElementRef<HTMLElement>, _focusTrapFactory: FocusTrapFactory,
    _document: any);
    get autoCapture(): boolean;
    set autoCapture(value: BooleanInput);
    get enabled(): boolean;
    set enabled(value: BooleanInput);
    focusTrap: FocusTrap;
    // (undocumented)
    ngAfterContentInit(): void;
    // (undocumented)
    ngDoCheck(): void;
    // (undocumented)
    ngOnChanges(changes: SimpleChanges): void;
    // (undocumented)
    ngOnDestroy(): void;
    // (undocumented)
    static ɵdir: i0.ɵɵDirectiveDeclaration<CdkTrapFocus, "[cdkTrapFocus]", ["cdkTrapFocus"], { "enabled": "cdkTrapFocus"; "autoCapture": "cdkTrapFocusAutoCapture"; }, {}, never, never, false, never>;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<CdkTrapFocus, never>;
}

// @public
export class ConfigurableFocusTrap extends FocusTrap implements ManagedFocusTrap {
    constructor(_element: HTMLElement, _checker: InteractivityChecker, _ngZone: NgZone, _document: Document, _focusTrapManager: FocusTrapManager, _inertStrategy: FocusTrapInertStrategy, config: ConfigurableFocusTrapConfig);
    destroy(): void;
    _disable(): void;
    _enable(): void;
    get enabled(): boolean;
    set enabled(value: boolean);
}

// @public
export interface ConfigurableFocusTrapConfig {
    defer: boolean;
}

// @public
export class ConfigurableFocusTrapFactory {
    constructor(_checker: InteractivityChecker, _ngZone: NgZone, _focusTrapManager: FocusTrapManager, _document: any, _inertStrategy?: FocusTrapInertStrategy);
    create(element: HTMLElement, config?: ConfigurableFocusTrapConfig): ConfigurableFocusTrap;
    // @deprecated (undocumented)
    create(element: HTMLElement, deferCaptureElements: boolean): ConfigurableFocusTrap;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<ConfigurableFocusTrapFactory, [null, null, null, null, { optional: true; }]>;
    // (undocumented)
    static ɵprov: i0.ɵɵInjectableDeclaration<ConfigurableFocusTrapFactory>;
}

// @public
export class EventListenerFocusTrapInertStrategy implements FocusTrapInertStrategy {
    allowFocus(focusTrap: ConfigurableFocusTrap): void;
    preventFocus(focusTrap: ConfigurableFocusTrap): void;
}

// @public
export const FOCUS_MONITOR_DEFAULT_OPTIONS: InjectionToken<FocusMonitorOptions>;

// @public
export const FOCUS_TRAP_INERT_STRATEGY: InjectionToken<FocusTrapInertStrategy>;

// @public
export interface FocusableOption extends ListKeyManagerOption {
    focus(origin?: FocusOrigin): void;
}

// @public (undocumented)
export class FocusKeyManager<T> extends ListKeyManager<FocusableOption & T> {
    setActiveItem(index: number): void;
    setActiveItem(item: T): void;
    setFocusOrigin(origin: FocusOrigin): this;
}

// @public
export class FocusMonitor implements OnDestroy {
    constructor(_ngZone: NgZone, _platform: Platform, _inputModalityDetector: InputModalityDetector,
    document: any | null, options: FocusMonitorOptions | null);
    protected _document?: Document;
    focusVia(element: HTMLElement, origin: FocusOrigin, options?: FocusOptions_2): void;
    focusVia(element: ElementRef<HTMLElement>, origin: FocusOrigin, options?: FocusOptions_2): void;
    monitor(element: HTMLElement, checkChildren?: boolean): Observable<FocusOrigin>;
    monitor(element: ElementRef<HTMLElement>, checkChildren?: boolean): Observable<FocusOrigin>;
    // (undocumented)
    ngOnDestroy(): void;
    _onBlur(event: FocusEvent, element: HTMLElement): void;
    stopMonitoring(element: HTMLElement): void;
    stopMonitoring(element: ElementRef<HTMLElement>): void;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<FocusMonitor, [null, null, null, { optional: true; }, { optional: true; }]>;
    // (undocumented)
    static ɵprov: i0.ɵɵInjectableDeclaration<FocusMonitor>;
}

// @public
export const enum FocusMonitorDetectionMode {
    EVENTUAL = 1,
    IMMEDIATE = 0
}

// @public
export interface FocusMonitorOptions {
    // (undocumented)
    detectionMode?: FocusMonitorDetectionMode;
}

// @public
interface FocusOptions_2 {
    preventScroll?: boolean;
}
export { FocusOptions_2 as FocusOptions }

// @public (undocumented)
export type FocusOrigin = 'touch' | 'mouse' | 'keyboard' | 'program' | null;

// @public @deprecated
export class FocusTrap {
    constructor(_element: HTMLElement, _checker: InteractivityChecker, _ngZone: NgZone, _document: Document, deferAnchors?: boolean);
    attachAnchors(): boolean;
    destroy(): void;
    // (undocumented)
    readonly _document: Document;
    // (undocumented)
    readonly _element: HTMLElement;
    get enabled(): boolean;
    set enabled(value: boolean);
    // (undocumented)
    protected _enabled: boolean;
    // (undocumented)
    protected endAnchorListener: () => boolean;
    focusFirstTabbableElement(options?: FocusOptions): boolean;
    focusFirstTabbableElementWhenReady(options?: FocusOptions): Promise<boolean>;
    focusInitialElement(options?: FocusOptions): boolean;
    focusInitialElementWhenReady(options?: FocusOptions): Promise<boolean>;
    focusLastTabbableElement(options?: FocusOptions): boolean;
    focusLastTabbableElementWhenReady(options?: FocusOptions): Promise<boolean>;
    hasAttached(): boolean;
    // (undocumented)
    readonly _ngZone: NgZone;
    // (undocumented)
    protected startAnchorListener: () => boolean;
    protected toggleAnchors(enabled: boolean): void;
}

// @public @deprecated
export class FocusTrapFactory {
    constructor(_checker: InteractivityChecker, _ngZone: NgZone, _document: any);
    create(element: HTMLElement, deferCaptureElements?: boolean): FocusTrap;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<FocusTrapFactory, never>;
    // (undocumented)
    static ɵprov: i0.ɵɵInjectableDeclaration<FocusTrapFactory>;
}

// @public
export interface FocusTrapInertStrategy {
    allowFocus(focusTrap: FocusTrap): void;
    preventFocus(focusTrap: FocusTrap): void;
}

// @public
export const enum HighContrastMode {
    // (undocumented)
    BLACK_ON_WHITE = 1,
    // (undocumented)
    NONE = 0,
    // (undocumented)
    WHITE_ON_BLACK = 2
}

// @public
export class HighContrastModeDetector implements OnDestroy {
    constructor(_platform: Platform, document: any);
    _applyBodyHighContrastModeCssClasses(): void;
    getHighContrastMode(): HighContrastMode;
    // (undocumented)
    ngOnDestroy(): void;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<HighContrastModeDetector, never>;
    // (undocumented)
    static ɵprov: i0.ɵɵInjectableDeclaration<HighContrastModeDetector>;
}

// @public
export interface Highlightable extends ListKeyManagerOption {
    setActiveStyles(): void;
    setInactiveStyles(): void;
}

// @public
export const INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS: InputModalityDetectorOptions;

// @public
export const INPUT_MODALITY_DETECTOR_OPTIONS: InjectionToken<InputModalityDetectorOptions>;

// @public
export type InputModality = 'keyboard' | 'mouse' | 'touch' | null;

// @public
export class InputModalityDetector implements OnDestroy {
    constructor(_platform: Platform, ngZone: NgZone, document: Document, options?: InputModalityDetectorOptions);
    readonly modalityChanged: Observable<InputModality>;
    readonly modalityDetected: Observable<InputModality>;
    get mostRecentModality(): InputModality;
    _mostRecentTarget: HTMLElement | null;
    // (undocumented)
    ngOnDestroy(): void;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<InputModalityDetector, [null, null, null, { optional: true; }]>;
    // (undocumented)
    static ɵprov: i0.ɵɵInjectableDeclaration<InputModalityDetector>;
}

// @public
export interface InputModalityDetectorOptions {
    ignoreKeys?: number[];
}

// @public
export class InteractivityChecker {
    constructor(_platform: Platform);
    isDisabled(element: HTMLElement): boolean;
    isFocusable(element: HTMLElement, config?: IsFocusableConfig): boolean;
    isTabbable(element: HTMLElement): boolean;
    isVisible(element: HTMLElement): boolean;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<InteractivityChecker, never>;
    // (undocumented)
    static ɵprov: i0.ɵɵInjectableDeclaration<InteractivityChecker>;
}

// @public
export function isFakeMousedownFromScreenReader(event: MouseEvent): boolean;

// @public
export function isFakeTouchstartFromScreenReader(event: TouchEvent): boolean;

// @public
export class IsFocusableConfig {
    ignoreVisibility: boolean;
}

// @public
export class ListKeyManager<T extends ListKeyManagerOption> {
    constructor(_items: QueryList<T> | T[]);
    get activeItem(): T | null;
    get activeItemIndex(): number | null;
    cancelTypeahead(): this;
    readonly change: Subject<number>;
    destroy(): void;
    isTyping(): boolean;
    onKeydown(event: KeyboardEvent): void;
    setActiveItem(index: number): void;
    setActiveItem(item: T): void;
    setFirstItemActive(): void;
    setLastItemActive(): void;
    setNextItemActive(): void;
    setPreviousItemActive(): void;
    skipPredicate(predicate: (item: T) => boolean): this;
    readonly tabOut: Subject<void>;
    updateActiveItem(index: number): void;
    updateActiveItem(item: T): void;
    withAllowedModifierKeys(keys: ListKeyManagerModifierKey[]): this;
    withHomeAndEnd(enabled?: boolean): this;
    withHorizontalOrientation(direction: 'ltr' | 'rtl' | null): this;
    withPageUpDown(enabled?: boolean, delta?: number): this;
    withTypeAhead(debounceInterval?: number): this;
    withVerticalOrientation(enabled?: boolean): this;
    withWrap(shouldWrap?: boolean): this;
}

// @public
export type ListKeyManagerModifierKey = 'altKey' | 'ctrlKey' | 'metaKey' | 'shiftKey';

// @public
export interface ListKeyManagerOption {
    disabled?: boolean;
    getLabel?(): string;
}

// @public
export const LIVE_ANNOUNCER_DEFAULT_OPTIONS: InjectionToken<LiveAnnouncerDefaultOptions>;

// @public (undocumented)
export const LIVE_ANNOUNCER_ELEMENT_TOKEN: InjectionToken<HTMLElement | null>;

// @public
export function LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY(): null;

// @public (undocumented)
export class LiveAnnouncer implements OnDestroy {
    constructor(elementToken: any, _ngZone: NgZone, _document: any, _defaultOptions?: LiveAnnouncerDefaultOptions | undefined);
    announce(message: string): Promise<void>;
    announce(message: string, politeness?: AriaLivePoliteness): Promise<void>;
    announce(message: string, duration?: number): Promise<void>;
    announce(message: string, politeness?: AriaLivePoliteness, duration?: number): Promise<void>;
    clear(): void;
    // (undocumented)
    ngOnDestroy(): void;
    // (undocumented)
    static ɵfac: i0.ɵɵFactoryDeclaration<LiveAnnouncer, [{ optional: true; }, null, null, { optional: true; }]>;
    // (undocumented)
    static ɵprov: i0.ɵɵInjectableDeclaration<LiveAnnouncer>;
}

// @public
export interface LiveAnnouncerDefaultOptions {
    duration?: number;
    politeness?: AriaLivePoliteness;
}

// @public @deprecated
export const MESSAGES_CONTAINER_ID = "cdk-describedby-message-container";

// @public
export interface RegisteredMessage {
    messageElement: Element;
    referenceCount: number;
}

// (No @packageDocumentation comment for this package)

```


text:
<!DOCTYPE html>
<html>
  <head>
    <title>
      audiobuffersource-playbackrate-zero.html
    </title>
    <script src="/resources/testharness.js"></script>
    <script src="/resources/testharnessreport.js"></script>
    <script src="/webaudio/resources/audit-util.js"></script>
    <script src="/webaudio/resources/audit.js"></script>
  </head>
  <body>
    <script id="layout-test-code">
      // Sample rate should be power of 128 to observe the change of AudioParam
      // at the beginning of rendering quantum. (playbackRate is k-rate) This is
      // the minimum sample rate in the valid sample rate range.
      let sampleRate = 8192;

      // The render duration in seconds, and the length in samples.
      let renderDuration = 1.0;
      let renderLength = renderDuration * sampleRate;

      let context = new OfflineAudioContext(1, renderLength, sampleRate);
      let audit = Audit.createTaskRunner();

      // Task: Render the actual buffer and compare with the reference.
      audit.define('synthesize-verify', (task, should) => {
        let ramp = context.createBufferSource();
        let rampBuffer = createLinearRampBuffer(context, renderLength);
        ramp.buffer = rampBuffer;

        ramp.connect(context.destination);
        ramp.start();

        // Leave the playbackRate as 1 for the first half, then change it
        // to zero at the exact half. The zero playback rate should hold the
        // sample value of the buffer index at the moment. (sample-and-hold)
        ramp.playbackRate.setValueAtTime(1.0, 0.0);
        ramp.playbackRate.setValueAtTime(0.0, renderDuration / 2);

        context.startRendering()
            .then(function(renderedBuffer) {
              let data = renderedBuffer.getChannelData(0);
              let rampData = rampBuffer.getChannelData(0);
              let half = rampData.length / 2;
              let passed = true;
              let i;

              for (i = 1; i < rampData.length; i++) {
                if (i < half) {
                  // Before the half position, the actual should match with the
                  // original ramp data.
                  if (data[i] !== rampData[i]) {
                    passed = false;
                    break;
                  }
                } else {
                  // From the half position, the actual value should not change.
                  if (data[i] !== rampData[half]) {
                    passed = false;
                    break;
                  }
                }
              }

              should(passed, 'The zero playbackRate')
                  .message(
                      'held the sample value correctly',
                      'should hold the sample value. ' +
                          'Expected ' + rampData[half] + ' but got ' + data[i] +
                          ' at the index ' + i);
            })
            .then(() => task.done());
      });

      audit.define('subsample start with playback rate 0', (task, should) => {
        let context = new OfflineAudioContext(1, renderLength, sampleRate);
        let rampBuffer = new AudioBuffer(
            {length: renderLength, sampleRate: context.sampleRate});
        let data = new Float32Array(renderLength);
        let startValue = 5;
        for (let k = 0; k < data.length; ++k) {
          data[k] = k + startValue;
        }
        rampBuffer.copyToChannel(data, 0);

        let src = new AudioBufferSourceNode(
            context, {buffer: rampBuffer, playbackRate: 0});

        src.connect(context.destination);

        // Purposely start the source between frame boundaries
        let startFrame = 27.3;
        src.start(startFrame / context.sampleRate);

        context.startRendering()
            .then(audioBuffer => {
              let actualStartFrame = Math.ceil(startFrame);
              let audio = audioBuffer.getChannelData(0);

              should(
                  audio.slice(0, actualStartFrame),
                  `output[0:${actualStartFrame - 1}]`)
                  .beConstantValueOf(0);
              should(
                  audio.slice(actualStartFrame), `output[${actualStartFrame}:]`)
                  .beConstantValueOf(startValue);
            })
            .then(() => task.done());
      });

      audit.run();
    </script>
  </body>
</html>


text:
[![Codacy Badge](https://api.codacy.com/project/badge/Grade/97a997a5aaad418a974e01c2fe02d7cf)](https://www.codacy.com/app/robinm8/LMSGrabber?utm_source=github.com&utm_medium=referral&utm_content=LMSGrabber/LMSGrabber&utm_campaign=badger)
[![Build Status](https://img.shields.io/travis/LMSGrabber/LMSGrabber/master.svg)](https://travis-ci.org/LMSGrabber/LMSGrabber)
[![Codecov](https://img.shields.io/codecov/c/github/LMSGrabber/LMSGrabber.svg)](https://codecov.io/gh/LMSGrabber/LMSGrabber/)
[![Code Climate](https://img.shields.io/codeclimate/github/LMSGrabber/LMSGrabber.svg)](https://codeclimate.com/github/LMSGrabber/LMSGrabber)
[![Code Climate](https://img.shields.io/codeclimate/issues/github/LMSGrabber/LMSGrabber.svg)](https://codeclimate.com/github/LMSGrabber/LMSGrabber)

## Overview ##

This program is designed to create offline archives of various Learning Management Systems (LMS). It is created as a part of the [Rensselaer Center for Open Source](https://rcos.io/projects/lmsgrabber/lmsgrabber/profile) and [Software Design and Documentation](https://sites.google.com/site/rpisdd/) courses.

Currently being worked on by [Jacob Lane](https://github.com/Jacob-Lane), [Colin Atkinson](https://github.com/colatkinson), [Daniel Zhu](https://github.com/zhuguotian), [Chris Vecchio](https://github.com/ChrisVech), [Mark Robinson](https://github.com/robinm8), and [Adeet Phanse](https://github.com/phansa).

Inspired by the [Original Python version](https://github.com/slegec/LMS_Grabber) by [Craig Slegel](https://github.com/slegec).

## Compiling/Running

### Class Files ###

```bash
cd LMSGrabber
mvn exec:java -D exec.mainClass=rpi.lmsgrabber.App
```

### JAR ###

```bash
cd LMSGrabber
mvn package
java -jar target/lmsgrabber-0.0.1-SNAPSHOT-jar-with-dependencies.jar
```

## Contributing ##

Please see our [Contributor's Guide](https://github.com/LMSGrabber/LMSGrabber/wiki/Contributing) and [wiki pages](https://github.com/LMSGrabber/LMSGrabber/wiki) for information on how to contribute towards the project.

Builds are automatically triggered and placed under the release section for any [tags](https://git-scm.com/book/en/v2/Git-Basics-Tagging).

## Other notes ##

Please check your LMS's user agreements and your school's policies on automated web crawling before using LMS Grabber.


text:
import * as React from "react"
import { lock, unlock } from "../helpers/lock-body"
import a11yTrap from "../helpers/focus-trap"

function Backdrop() {
  return

}

export function VisuallyHidden({ children }) {
  return (
    <span
      style={{
        border: 0,
        clip: `rect(0 0 0 0)`,
        height: `1px`,
        margin: `-1px`,
        overflow: `hidden`,
        padding: 0,
        position: `absolute`,
        width: `1px`,
        whiteSpace: `nowrap`,
        wordWrap: `normal`,
      }}
    >
      {children}

  )
}

export function Overlay({ children }) {
  React.useEffect(() => {
    lock()

    return () => {
      unlock()
    }
  }, [])

  const [overlay, setOverlay] = React.useState(null)
  const onOverlay = React.useCallback(el => {
    setOverlay(el)
  }, [])

  React.useEffect(() => {
    if (overlay === null) {
      return
    }

    const handle = a11yTrap({ context: overlay })

    // eslint-disable-next-line consistent-return
    return () => {
      handle.disengage()
    }
  }, [overlay])

  return (

      <Backdrop />

        {children}

  )
}

export function CloseButton({ dismiss }) {
  return (
    <button data-gatsby-overlay="close-button" onClick={dismiss}>
      <VisuallyHidden>Close</VisuallyHidden>
      <svg
        aria-hidden={true}
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path
          d="M18 6L6 18"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
        <path
          d="M6 6L18 18"
          stroke="currentColor"
          strokeWidth="2"
          strokeLinecap="round"
          strokeLinejoin="round"
        />
      </svg>
    </button>
  )
}

export function HeaderOpenClose({ open, dismiss, children, ...rest }) {
  return (

      {children}

        {open && (
          <button onClick={open} data-gatsby-overlay="primary-button">
            Open in editor
          </button>
        )}
        {dismiss && <CloseButton dismiss={dismiss} />}

  )
}

export function Header({ children, ...rest }) {
  return (

      {children}

  )
}

export function Body({ children, ...rest }) {
  return (

      {children}

  )
}

export function Footer({ children, ...rest }) {
  return (

      {children}

  )
}


text:
<?php

namespace Aliyun\OSS\Commands;

use Aliyun\Common\Utilities\HttpMethods;

use Aliyun\OSS\Utilities\OSSHeaders;

use Aliyun\OSS\Models\OSSOptions;

use Aliyun\Common\Utilities\AssertUtils;

use Aliyun\OSS\Utilities\OSSRequestBuilder;

use Aliyun\OSS\Utilities\OSSUtils;

class InitiateMultipartUploadCommand extends OSSCommand {

    protected function checkOptions($options) {
        $options = parent::checkOptions($options);
        AssertUtils::assertSet(array(
            OSSOptions::BUCKET,
            OSSOptions::KEY,
        ), $options);

        OSSUtils::assertBucketName($options[OSSOptions::BUCKET]);
        OSSUtils::assertObjectKey($options[OSSOptions::KEY]);

        return $options;
    }

    protected function commandOptions() {
        return array(
            OSSOptions::CONTENT_TYPE => OSSUtils::DEFAULT_CONTENT_TYPE,
        );
    }

    protected function getRequest($options) {

        return OSSRequestBuilder::factory()
            ->addObjectMetadataHeaders($options)
            ->setEndpoint($options[OSSOptions::ENDPOINT])
            ->setMethod(HttpMethods::POST)
            ->setBucket($options[OSSOptions::BUCKET])
            ->setKey($options[OSSOptions::KEY])
            ->addParameter(OSSUtils::SUBRESOURCE_UPLOADS, null)
            ->setContent('')
            ->build();
    }
}


text:
namespace King.Mapper.Tests
{
    using King.Mapper;
    using King.Mapper.Tests.Models;
    using NUnit.Framework;
    using System;

    [TestFixture]
    public class ActionNameAttributeTests
    {
        [Test]
        public void ConstructorInvalidName()
        {
            Assert.That(() => new ActionNameAttribute(null), Throws.TypeOf<ArgumentException>());
        }

        [Test]
        public void Constructor()
        {
            new ActionNameAttribute(Guid.NewGuid().ToString(), ActionFlags.Execute);
        }

        [Test]
        public void Name()
        {
            var data = Guid.NewGuid().ToString();
            var actionName = new ActionNameAttribute(data, ActionFlags.Load);
            Assert.AreEqual(data, actionName.Name);
        }

        [Test]
        public void Action()
        {
            var data = ActionFlags.Execute;
            var actionName = new ActionNameAttribute(Guid.NewGuid().ToString(), data);
            Assert.AreEqual(data, actionName.Action);
        }

        [Test]
        public void ActionDefault()
        {
            var actionName = new ActionNameAttribute(Guid.NewGuid().ToString());
            Assert.AreEqual(ActionFlags.Load, actionName.Action);
        }

        [Test]
        public void ValueMappingTestActionNames()
        {
            var random = new Random();
            var getValues = new TestActionNames()
            {
                Band = Guid.NewGuid().ToString(),
                Id = random.Next(),
                Song = Guid.NewGuid(),
            };

            var mappings = getValues.ValueMapping(new string[] { "Id", "Band", "Song" }, ActionFlags.Load);
            Assert.AreEqual(5, mappings.Count);
            Assert.AreEqual(getValues.Band, (string)mappings["Band"]);
            Assert.AreEqual(getValues.Band, (string)mappings["CheckBandDude"]);
            Assert.AreEqual(getValues.Id, (int)mappings["Id"]);
            Assert.AreEqual(getValues.Song, (Guid)mappings["Song"]);
            Assert.AreEqual(getValues.Song, (Guid)mappings["GuidGuid"]);
        }
    }
}


text:
using Moq;
using NUnit.Framework;
using SFA.DAS.EmployerFinance.Data;
using SFA.DAS.EmployerFinance.Queries.GetEmployerAccount;
using SFA.DAS.Validation;
using System;
using System.Threading.Tasks;
using SFA.DAS.EmployerFinance.Models.Account;
using SFA.DAS.HashingService;

namespace SFA.DAS.EmployerFinance.UnitTests.Queries.GetEmployerAccountTests
{
    public class WhenIGetEmployerAccountsByHashedKey : QueryBaseTest<GetEmployerAccountHashedHandler, GetEmployerAccountHashedQuery, GetEmployerAccountResponse>
    {
        private Mock<IEmployerAccountRepository> _employerAccountRepository;
        public override GetEmployerAccountHashedQuery Query { get; set; }
        public override GetEmployerAccountHashedHandler RequestHandler { get; set; }
        public override Mock<IValidator<GetEmployerAccountHashedQuery>> RequestValidator { get; set; }
        private const string ExpectedUserId = "asdsa445";
        private const string ExpectedHashedId = "jfjfdjf444";
        private const long ExpectedAccountId = 32450;
        private Mock<IHashingService> _hashingService;
        private Account ExpectedAccount;

        [SetUp]
        public void Arrange()
        {
            base.SetUp();

            _hashingService = new Mock<IHashingService>();
            _hashingService.Setup(x => x.DecodeValue(ExpectedHashedId)).Returns(ExpectedAccountId);

            ExpectedAccount = new Account();

            _employerAccountRepository = new Mock<IEmployerAccountRepository>();
            _employerAccountRepository.Setup(x => x.Get(ExpectedAccountId)).ReturnsAsync(ExpectedAccount);

            RequestHandler = new GetEmployerAccountHashedHandler(_employerAccountRepository.Object, RequestValidator.Object, _hashingService.Object);
            Query = new GetEmployerAccountHashedQuery { HashedAccountId = ExpectedHashedId, UserId = ExpectedUserId };

        }

        [Test]
        public override async Task ThenIfTheMessageIsValidTheRepositoryIsCalled()
        {
            //Act
            await RequestHandler.Handle(new GetEmployerAccountHashedQuery
            {
                HashedAccountId = ExpectedHashedId,
                UserId = ExpectedUserId
            });

            //Assert
            _employerAccountRepository.Verify(x => x.Get(ExpectedAccountId));
        }

        [Test]
        public override async Task ThenIfTheMessageIsValidTheValueIsReturnedInTheResponse()
        {
            //Act
            var result = await RequestHandler.Handle(new GetEmployerAccountHashedQuery
            {
                HashedAccountId = ExpectedHashedId,
                UserId = ExpectedUserId
            });

            //Assert
            Assert.IsNotNull(result);
            Assert.AreSame(ExpectedAccount, result.Account);
        }

        [Test]
        public void ThenIfValidationResponseIsUnauthorizedAnUnauthorizedAccessExceptionIsThrown()
        {
            //Arrange
            RequestValidator.Setup(x => x.ValidateAsync(It.IsAny<GetEmployerAccountHashedQuery>())).ReturnsAsync(new ValidationResult { IsUnauthorized = true });

            //Act Assert
            Assert.ThrowsAsync<UnauthorizedAccessException>(async () => await RequestHandler.Handle(new GetEmployerAccountHashedQuery()));

        }
    }
}


text:
angular
    .module("${moduleName}")
    .controller("${name}", ${name});

function ${name}() {
    var vm = this;
}


text:
package mqtt

import "fmt"
import "time"
import "bytes"

import "io/ioutil"
import "crypto/tls"
import "crypto/x509"
import "testing"

func Test_Start(t *testing.T) {
	ops := NewClientOptions().SetClientID("Start").
		AddBroker(FVTTCP).
		SetStore(NewFileStore("/tmp/fvt/Start"))
	c := NewClient(ops)

	token := c.Connect()
	if token.Wait() && token.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", token.Error())
	}

	c.Disconnect(250)
}

/* uncomment this if you have connection policy disallowing FailClientID
func Test_InvalidConnRc(t *testing.T) {
	ops := NewClientOptions().SetClientID("FailClientID").
		AddBroker("tcp://" + FVT_IP + ":17003").
		SetStore(NewFileStore("/tmp/fvt/InvalidConnRc"))

	c := NewClient(ops)
	_, err := c.Connect()
	if err != ErrNotAuthorized {
		t.Fatalf("Did not receive error as expected, got %v", err)
	}
	c.Disconnect(250)
}
*/

// Helper function for Test_Start_Ssl
func NewTLSConfig() *tls.Config {
	certpool := x509.NewCertPool()
	pemCerts, err := ioutil.ReadFile("samples/samplecerts/CAfile.pem")
	if err == nil {
		certpool.AppendCertsFromPEM(pemCerts)
	}

	cert, err := tls.LoadX509KeyPair("samples/samplecerts/client-crt.pem", "samples/samplecerts/client-key.pem")
	if err != nil {
		panic(err)
	}

	return &tls.Config{
		RootCAs:            certpool,
		ClientAuth:         tls.NoClientCert,
		ClientCAs:          nil,
		InsecureSkipVerify: true,
		Certificates:       []tls.Certificate{cert},
	}
}

/* uncomment this if you have ssl setup
func Test_Start_Ssl(t *testing.T) {
	tlsconfig := NewTlsConfig()
	ops := NewClientOptions().SetClientID("StartSsl").
		AddBroker(FVT_SSL).
		SetStore(NewFileStore("/tmp/fvt/Start_Ssl")).
		SetTlsConfig(tlsconfig)

	c := NewClient(ops)

	_, err := c.Connect()
	if err != nil {
		t.Fatalf("Error on Client.Connect(): %v", err)
	}

	c.Disconnect(250)
}
*/

func Test_Publish_1(t *testing.T) {
	ops := NewClientOptions()
	ops.AddBroker(FVTTCP)
	ops.SetClientID("Publish_1")
	ops.SetStore(NewFileStore("/tmp/fvt/Publish_1"))

	c := NewClient(ops)
	token := c.Connect()
	if token.Wait() && token.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", token.Error())
	}

	c.Publish("test/Publish", 0, false, "Publish qo0")

	c.Disconnect(250)
}

func Test_Publish_2(t *testing.T) {
	ops := NewClientOptions()
	ops.AddBroker(FVTTCP)
	ops.SetClientID("Publish_2")
	ops.SetStore(NewFileStore("/tmp/fvt/Publish_2"))

	c := NewClient(ops)
	token := c.Connect()
	if token.Wait() && token.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", token.Error())
	}

	c.Publish("/test/Publish", 0, false, "Publish1 qos0")
	c.Publish("/test/Publish", 0, false, "Publish2 qos0")

	c.Disconnect(250)
}

func Test_Publish_3(t *testing.T) {
	ops := NewClientOptions()
	ops.AddBroker(FVTTCP)
	ops.SetClientID("Publish_3")
	ops.SetStore(NewFileStore("/tmp/fvt/Publish_3"))

	c := NewClient(ops)
	token := c.Connect()
	if token.Wait() && token.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", token.Error())
	}

	c.Publish("/test/Publish", 0, false, "Publish1 qos0")
	c.Publish("/test/Publish", 1, false, "Publish2 qos1")
	c.Publish("/test/Publish", 2, false, "Publish2 qos2")

	c.Disconnect(250)
}

func Test_Subscribe(t *testing.T) {
	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("Subscribe_tx")
	pops.SetStore(NewFileStore("/tmp/fvt/Subscribe/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("Subscribe_rx")
	sops.SetStore(NewFileStore("/tmp/fvt/Subscribe/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
	}
	sops.SetDefaultPublishHandler(f)
	s := NewClient(sops)

	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	s.Subscribe("/test/sub", 0, nil)

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}

	p.Publish("/test/sub", 0, false, "Publish qos0")

	p.Disconnect(250)
	s.Disconnect(250)
}

func Test_Will(t *testing.T) {
	willmsgc := make(chan string)

	sops := NewClientOptions().AddBroker(FVTTCP)
	sops.SetClientID("will-giver")
	sops.SetWill("/wills", "good-byte!", 0, false)
	sops.SetConnectionLostHandler(func(client *Client, err error) {
		fmt.Println("OnConnectionLost!")
	})
	c := NewClient(sops)

	wops := NewClientOptions()
	wops.AddBroker(FVTTCP)
	wops.SetClientID("will-subscriber")
	wops.SetStore(NewFileStore("/tmp/fvt/Will"))
	wops.SetDefaultPublishHandler(func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		willmsgc <- string(msg.Payload())
	})
	wsub := NewClient(wops)

	wToken := wsub.Connect()
	if wToken.Wait() && wToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", wToken.Error())
	}

	wsub.Subscribe("/wills", 0, nil)

	token := c.Connect()
	if token.Wait() && token.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", token.Error())
	}
	time.Sleep(time.Duration(1) * time.Second)

	c.forceDisconnect()

	wsub.Disconnect(250)

	if <-willmsgc != "good-byte!" {
		t.Fatalf("will message did not have correct payload")
	}
}

func Test_Binary_Will(t *testing.T) {
	willmsgc := make(chan []byte)
	will := []byte{
		0xDE,
		0xAD,
		0xBE,
		0xEF,
	}

	sops := NewClientOptions().AddBroker(FVTTCP)
	sops.SetClientID("will-giver")
	sops.SetBinaryWill("/wills", will, 0, false)
	sops.SetConnectionLostHandler(func(client *Client, err error) {
	})
	c := NewClient(sops)

	wops := NewClientOptions().AddBroker(FVTTCP)
	wops.SetClientID("will-subscriber")
	wops.SetStore(NewFileStore("/tmp/fvt/Binary_Will"))
	wops.SetDefaultPublishHandler(func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %v\n", msg.Payload())
		willmsgc <- msg.Payload()
	})
	wsub := NewClient(wops)

	wToken := wsub.Connect()
	if wToken.Wait() && wToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", wToken.Error())
	}

	wsub.Subscribe("/wills", 0, nil)

	token := c.Connect()
	if token.Wait() && token.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", token.Error())
	}
	time.Sleep(time.Duration(1) * time.Second)

	c.forceDisconnect()

	wsub.Disconnect(250)

	if !bytes.Equal(<-willmsgc, will) {
		t.Fatalf("will message did not have correct payload")
	}
}

/**
"[...] a publisher is responsible for determining the maximum QoS a
message can be delivered at, but a subscriber is able to downgrade
the QoS to one more suitable for its usage.
The QoS of a message is never upgraded."
**/

/***********************************
 * Tests to cover the 9 QoS combos *
 ***********************************/

func wait(c chan bool) {
	fmt.Println("choke is waiting")
	<-c
}

// Pub 0, Sub 0

func Test_p0s0(t *testing.T) {
	store := "/tmp/fvt/p0s0"
	topic := "/test/p0s0"
	choke := make(chan bool)

	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("p0s0-pub")
	pops.SetStore(NewFileStore(store + "/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("p0s0-sub")
	sops.SetStore(NewFileStore(store + "/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		choke <- true
	}
	sops.SetDefaultPublishHandler(f)

	s := NewClient(sops)
	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	sToken = s.Subscribe(topic, 0, nil)
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
	}

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}
	p.Publish(topic, 0, false, "p0s0 payload 1")
	p.Publish(topic, 0, false, "p0s0 payload 2")

	wait(choke)
	wait(choke)

	p.Publish(topic, 0, false, "p0s0 payload 3")
	wait(choke)

	p.Disconnect(250)
	s.Disconnect(250)

	chkcond(isemptydir(store + "/p"))
	chkcond(isemptydir(store + "/s"))
}

// Pub 0, Sub 1

func Test_p0s1(t *testing.T) {
	store := "/tmp/fvt/p0s1"
	topic := "/test/p0s1"
	choke := make(chan bool)

	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("p0s1-pub")
	pops.SetStore(NewFileStore(store + "/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("p0s1-sub")
	sops.SetStore(NewFileStore(store + "/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		choke <- true
	}
	sops.SetDefaultPublishHandler(f)

	s := NewClient(sops)
	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	sToken = s.Subscribe(topic, 1, nil)
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
	}

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}
	p.Publish(topic, 0, false, "p0s1 payload 1")
	p.Publish(topic, 0, false, "p0s1 payload 2")

	wait(choke)
	wait(choke)

	p.Publish(topic, 0, false, "p0s1 payload 3")
	wait(choke)

	p.Disconnect(250)
	s.Disconnect(250)

	chkcond(isemptydir(store + "/p"))
	chkcond(isemptydir(store + "/s"))
}

// Pub 0, Sub 2

func Test_p0s2(t *testing.T) {
	store := "/tmp/fvt/p0s2"
	topic := "/test/p0s2"
	choke := make(chan bool)

	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("p0s2-pub")
	pops.SetStore(NewFileStore(store + "/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("p0s2-sub")
	sops.SetStore(NewFileStore(store + "/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		choke <- true
	}
	sops.SetDefaultPublishHandler(f)

	s := NewClient(sops)
	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	sToken = s.Subscribe(topic, 2, nil)
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
	}

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}
	p.Publish(topic, 0, false, "p0s2 payload 1")
	p.Publish(topic, 0, false, "p0s2 payload 2")

	wait(choke)
	wait(choke)

	p.Publish(topic, 0, false, "p0s2 payload 3")

	wait(choke)

	p.Disconnect(250)
	s.Disconnect(250)

	chkcond(isemptydir(store + "/p"))
	chkcond(isemptydir(store + "/s"))
}

// Pub 1, Sub 0

func Test_p1s0(t *testing.T) {
	store := "/tmp/fvt/p1s0"
	topic := "/test/p1s0"
	choke := make(chan bool)

	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("p1s0-pub")
	pops.SetStore(NewFileStore(store + "/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("p1s0-sub")
	sops.SetStore(NewFileStore(store + "/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		choke <- true
	}
	sops.SetDefaultPublishHandler(f)

	s := NewClient(sops)
	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	sToken = s.Subscribe(topic, 0, nil)
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
	}

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}
	p.Publish(topic, 1, false, "p1s0 payload 1")
	p.Publish(topic, 1, false, "p1s0 payload 2")

	wait(choke)
	wait(choke)

	p.Publish(topic, 1, false, "p1s0 payload 3")

	wait(choke)

	p.Disconnect(250)
	s.Disconnect(250)

	chkcond(isemptydir(store + "/p"))
	chkcond(isemptydir(store + "/s"))
}

// Pub 1, Sub 1

func Test_p1s1(t *testing.T) {
	store := "/tmp/fvt/p1s1"
	topic := "/test/p1s1"
	choke := make(chan bool)

	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("p1s1-pub")
	pops.SetStore(NewFileStore(store + "/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("p1s1-sub")
	sops.SetStore(NewFileStore(store + "/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		choke <- true
	}
	sops.SetDefaultPublishHandler(f)

	s := NewClient(sops)
	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	sToken = s.Subscribe(topic, 1, nil)
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
	}

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}
	p.Publish(topic, 1, false, "p1s1 payload 1")
	p.Publish(topic, 1, false, "p1s1 payload 2")

	wait(choke)
	wait(choke)

	p.Publish(topic, 1, false, "p1s1 payload 3")
	wait(choke)

	p.Disconnect(250)
	s.Disconnect(250)

	chkcond(isemptydir(store + "/p"))
	chkcond(isemptydir(store + "/s"))
}

// Pub 1, Sub 2

func Test_p1s2(t *testing.T) {
	store := "/tmp/fvt/p1s2"
	topic := "/test/p1s2"
	choke := make(chan bool)

	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("p1s2-pub")
	pops.SetStore(NewFileStore(store + "/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("p1s2-sub")
	sops.SetStore(NewFileStore(store + "/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		choke <- true
	}
	sops.SetDefaultPublishHandler(f)

	s := NewClient(sops)
	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	sToken = s.Subscribe(topic, 2, nil)
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
	}

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}
	p.Publish(topic, 1, false, "p1s2 payload 1")
	p.Publish(topic, 1, false, "p1s2 payload 2")

	wait(choke)
	wait(choke)

	p.Publish(topic, 1, false, "p1s2 payload 3")

	wait(choke)

	p.Disconnect(250)
	s.Disconnect(250)

	chkcond(isemptydir(store + "/p"))
	chkcond(isemptydir(store + "/s"))
}

// Pub 2, Sub 0

func Test_p2s0(t *testing.T) {
	store := "/tmp/fvt/p2s0"
	topic := "/test/p2s0"
	choke := make(chan bool)

	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("p2s0-pub")
	pops.SetStore(NewFileStore(store + "/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("p2s0-sub")
	sops.SetStore(NewFileStore(store + "/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		choke <- true
	}
	sops.SetDefaultPublishHandler(f)

	s := NewClient(sops)
	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	sToken = s.Subscribe(topic, 0, nil)
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
	}

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}
	p.Publish(topic, 2, false, "p2s0 payload 1")
	p.Publish(topic, 2, false, "p2s0 payload 2")
	wait(choke)
	wait(choke)

	p.Publish(topic, 2, false, "p2s0 payload 3")
	wait(choke)

	p.Disconnect(250)
	s.Disconnect(250)

	chkcond(isemptydir(store + "/p"))
	chkcond(isemptydir(store + "/s"))
}

// Pub 2, Sub 1

func Test_p2s1(t *testing.T) {
	store := "/tmp/fvt/p2s1"
	topic := "/test/p2s1"
	choke := make(chan bool)

	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("p2s1-pub")
	pops.SetStore(NewFileStore(store + "/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("p2s1-sub")
	sops.SetStore(NewFileStore(store + "/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		choke <- true
	}
	sops.SetDefaultPublishHandler(f)

	s := NewClient(sops)
	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	sToken = s.Subscribe(topic, 1, nil)
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
	}

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}
	p.Publish(topic, 2, false, "p2s1 payload 1")
	p.Publish(topic, 2, false, "p2s1 payload 2")

	wait(choke)
	wait(choke)

	p.Publish(topic, 2, false, "p2s1 payload 3")

	wait(choke)

	p.Disconnect(250)
	s.Disconnect(250)

	chkcond(isemptydir(store + "/p"))
	chkcond(isemptydir(store + "/s"))
}

// Pub 2, Sub 2

func Test_p2s2(t *testing.T) {
	store := "/tmp/fvt/p2s2"
	topic := "/test/p2s2"
	choke := make(chan bool)

	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("p2s2-pub")
	pops.SetStore(NewFileStore(store + "/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("p2s2-sub")
	sops.SetStore(NewFileStore(store + "/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		choke <- true
	}
	sops.SetDefaultPublishHandler(f)

	s := NewClient(sops)
	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	sToken = s.Subscribe(topic, 2, nil)
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
	}

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}
	p.Publish(topic, 2, false, "p2s2 payload 1")
	p.Publish(topic, 2, false, "p2s2 payload 2")

	wait(choke)
	wait(choke)

	p.Publish(topic, 2, false, "p2s2 payload 3")

	wait(choke)

	p.Disconnect(250)
	s.Disconnect(250)

	chkcond(isemptydir(store + "/p"))
	chkcond(isemptydir(store + "/s"))
}

func Test_PublishMessage(t *testing.T) {
	store := "/tmp/fvt/PublishMessage"
	topic := "/test/pubmsg"
	choke := make(chan bool)

	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("pubmsg-pub")
	pops.SetStore(NewFileStore(store + "/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("pubmsg-sub")
	sops.SetStore(NewFileStore(store + "/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		if string(msg.Payload()) != "pubmsg payload" {
			fmt.Println("Message payload incorrect", msg.Payload(), len("pubmsg payload"))
			t.Fatalf("Message payload incorrect")
		}
		choke <- true
	}
	sops.SetDefaultPublishHandler(f)

	s := NewClient(sops)
	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	sToken = s.Subscribe(topic, 2, nil)
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
	}

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}

	text := "pubmsg payload"
	p.Publish(topic, 0, false, text)
	p.Publish(topic, 0, false, text)
	wait(choke)
	wait(choke)

	p.Publish(topic, 0, false, text)
	wait(choke)

	p.Disconnect(250)
	s.Disconnect(250)

	chkcond(isemptydir(store + "/p"))
	chkcond(isemptydir(store + "/s"))
}

func Test_PublishEmptyMessage(t *testing.T) {
	store := "/tmp/fvt/PublishEmptyMessage"
	topic := "/test/pubmsgempty"
	choke := make(chan bool)

	pops := NewClientOptions()
	pops.AddBroker(FVTTCP)
	pops.SetClientID("pubmsgempty-pub")
	pops.SetStore(NewFileStore(store + "/p"))
	p := NewClient(pops)

	sops := NewClientOptions()
	sops.AddBroker(FVTTCP)
	sops.SetClientID("pubmsgempty-sub")
	sops.SetStore(NewFileStore(store + "/s"))
	var f MessageHandler = func(client *Client, msg Message) {
		fmt.Printf("TOPIC: %s\n", msg.Topic())
		fmt.Printf("MSG: %s\n", msg.Payload())
		if string(msg.Payload()) != "" {
			t.Fatalf("Message payload incorrect")
		}
		choke <- true
	}
	sops.SetDefaultPublishHandler(f)

	s := NewClient(sops)
	sToken := s.Connect()
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
	}

	sToken = s.Subscribe(topic, 2, nil)
	if sToken.Wait() && sToken.Error() != nil {
		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
	}

	pToken := p.Connect()
	if pToken.Wait() && pToken.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
	}

	p.Publish(topic, 0, false, "")
	p.Publish(topic, 0, false, "")
	wait(choke)
	wait(choke)

	p.Publish(topic, 0, false, "")
	wait(choke)

	p.Disconnect(250)
}

// func Test_Cleanstore(t *testing.T) {
// 	store := "/tmp/fvt/cleanstore"
// 	topic := "/test/cleanstore"

// 	pops := NewClientOptions()
// 	pops.AddBroker(FVTTCP)
// 	pops.SetClientID("cleanstore-pub")
// 	pops.SetStore(NewFileStore(store + "/p"))
// 	p := NewClient(pops)

// 	var s *Client
// 	sops := NewClientOptions()
// 	sops.AddBroker(FVTTCP)
// 	sops.SetClientID("cleanstore-sub")
// 	sops.SetCleanSession(false)
// 	sops.SetStore(NewFileStore(store + "/s"))
// 	var f MessageHandler = func(client *Client, msg Message) {
// 		fmt.Printf("TOPIC: %s\n", msg.Topic())
// 		fmt.Printf("MSG: %s\n", msg.Payload())
// 		// Close the connection after receiving
// 		// the first message so that hopefully
// 		// there is something in the store to be
// 		// cleaned.
// 		s.ForceDisconnect()
// 	}
// 	sops.SetDefaultPublishHandler(f)

// 	s = NewClient(sops)
// 	sToken := s.Connect()
// 	if sToken.Wait() && sToken.Error() != nil {
// 		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
// 	}

// 	sToken = s.Subscribe(topic, 2, nil)
// 	if sToken.Wait() && sToken.Error() != nil {
// 		t.Fatalf("Error on Client.Subscribe(): %v", sToken.Error())
// 	}

// 	pToken := p.Connect()
// 	if pToken.Wait() && pToken.Error() != nil {
// 		t.Fatalf("Error on Client.Connect(): %v", pToken.Error())
// 	}

// 	text := "test message"
// 	p.Publish(topic, 0, false, text)
// 	p.Publish(topic, 0, false, text)
// 	p.Publish(topic, 0, false, text)

// 	p.Disconnect(250)

// 	s2ops := NewClientOptions()
// 	s2ops.AddBroker(FVTTCP)
// 	s2ops.SetClientID("cleanstore-sub")
// 	s2ops.SetCleanSession(true)
// 	s2ops.SetStore(NewFileStore(store + "/s"))
// 	s2ops.SetDefaultPublishHandler(f)

// 	s2 := NewClient(s2ops)
// 	sToken = s2.Connect()
// 	if sToken.Wait() && sToken.Error() != nil {
// 		t.Fatalf("Error on Client.Connect(): %v", sToken.Error())
// 	}

// 	// at this point existing state should be cleared...
// 	// how to check?
// }

func Test_MultipleURLs(t *testing.T) {
	ops := NewClientOptions()
	ops.AddBroker("tcp://127.0.0.1:10000")
	ops.AddBroker(FVTTCP)
	ops.SetClientID("MutliURL")
	ops.SetStore(NewFileStore("/tmp/fvt/MultiURL"))

	c := NewClient(ops)
	token := c.Connect()
	if token.Wait() && token.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", token.Error())
	}

	token = c.Publish("/test/MultiURL", 0, false, "Publish qo0")
	token.Wait()

	c.Disconnect(250)
}

/*
// A test to make sure ping mechanism is working
// This test can be left commented out because it's annoying to wait for
func Test_ping3_idle10(t *testing.T) {
	ops := NewClientOptions()
	ops.AddBroker(FVTTCP)
	//ops.AddBroker("tcp://test.mosquitto.org:1883")
	ops.SetClientID("p3i10")
	ops.SetKeepAlive(4)

	c := NewClient(ops)
	token := c.Connect()
	if token.Wait() && token.Error() != nil {
		t.Fatalf("Error on Client.Connect(): %v", token.Error())
	}
	time.Sleep(time.Duration(10) * time.Second)
	c.Disconnect(250)
}
*/


text:
require 'tsort'

module Bundler
  class SpecSet
    include TSort, Enumerable

    def initialize(specs)
      @specs = specs.sort_by { |s| s.name }
    end

    def each
      sorted.each { |s| yield s }
    end

    def length
      @specs.length
    end

    def for(dependencies, skip = [], check = false, match_current_platform = false)
      handled, deps, specs = {}, dependencies.dup, []

      until deps.empty?
        dep = deps.shift
        next if handled[dep] || skip.include?(dep.name)

        spec = lookup[dep.name].find do |s|
          match_current_platform ?
            Gem::Platform.match(s.platform) :
            s.match_platform(dep.__platform)
        end

        handled[dep] = true

        if spec
          specs << spec

          spec.dependencies.each do |d|
            next if d.type == :development
            d = DepProxy.new(d, dep.__platform) unless match_current_platform
            deps << d
          end
        elsif check
          return false
        end
      end

      check ? true : SpecSet.new(specs)
    end

    def valid_for?(deps)
      self.for(deps, [], true)
    end

    def [](key)
      key = key.name if key.respond_to?(:name)
      lookup[key].reverse
    end

    def to_a
      sorted.dup
    end

    def to_hash
      lookup.dup
    end

    def materialize(deps, missing_specs = nil)
      materialized = self.for(deps, [], false, true).to_a
      materialized.map! do |s|
        next s unless s.is_a?(LazySpecification)
        spec = s.__materialize__
        if missing_specs
          missing_specs << s unless spec
        else
          raise GemNotFound, "Could not find #{s.full_name} in any of the sources" unless spec
        end
        spec if spec
      end
      SpecSet.new(materialized.compact)
    end

    def names
      lookup.keys
    end

    def select!(names)
      @lookup = nil
      @sorted = nil

      @specs.delete_if { |s| !names.include?(s.name) }
      self
    end

  private

    def sorted
      rake = @specs.find { |s| s.name == 'rake' }
      @sorted ||= ([rake] + tsort).compact.uniq
    end

    def lookup
      @lookup ||= begin
        lookup = Hash.new { |h,k| h[k] = [] }
        specs = @specs.sort_by do |s|
          s.platform.to_s == 'ruby' ? "\0" : s.platform.to_s
        end
        specs.reverse_each do |s|
          lookup[s.name] << s
        end
        lookup
      end
    end

    def tsort_each_node
      @specs.each { |s| yield s }
    end

    def tsort_each_child(s)
      s.dependencies.sort_by { |d| d.name }.each do |d|
        next if d.type == :development
        lookup[d.name].each { |s| yield s }
      end
    end
  end
end