text:
typedef enum : NSUInteger {
    TransitPopViewController = 0,
    TransitPopTillRoot = 1,
    TransitPush = 2,
} UINavigationControllerTransition;

typedef void(^PopCompletionBlock)();

@interface SmartPopNavigationController () <UINavigationControllerDelegate>

@property (nonatomic, strong) NSMutableArray *completionBlocks;
@property (nonatomic, weak) id<UINavigationControllerDelegate>escalatedDelegate;
@property (nonatomic) BOOL pushing;

@end

@implementation SmartPopNavigationController {
    BOOL completionAwareCall;
}

- (SmartPopNavigationController *) deepestSmartPopNavigationController
{
    for (UIViewController *vc = self.parentViewController; vc; vc = vc.parentViewController) {
        if (vc.navigationController && [vc.navigationController isKindOfClass:[SmartPopNavigationController class]]) {
            return [((SmartPopNavigationController *)vc.navigationController) deepestSmartPopNavigationController];
        }
    }
    return self;
}

- (NSArray *) superPopToRootViewControllerAnimated:(BOOL) animated
{
    return [super popToRootViewControllerAnimated:animated];
}

- (NSArray *) superPopViewControllerAnimated:(BOOL) animated
{
    id res = [super popViewControllerAnimated:animated];
    if (res) {
        return @[res];
    }
    return nil;
}

- (NSArray *) popViewControllerAnimated:(BOOL) animated completion:(void (^)()) completion tillRoot:(BOOL) tillRoot
{
    return [self transitViewControllerAnimated:animated
                                    completion:completion
                                        action:tillRoot?TransitPopTillRoot:TransitPopViewController
                                      targetVC:nil];
}

- (NSArray *) transitViewControllerAnimated:(BOOL) animated completion:(void (^)()) completion action:(UINavigationControllerTransition) action targetVC:(UIViewController *) targetVC
{
    if (self.delegate) {
        if (![self.delegate isEqual:self]) {
            self.escalatedDelegate = self.delegate;
            self.delegate = self;
        }
    } else {
        self.delegate = self;
    }
    NSMutableDictionary *info = [@{@"animated": @(animated), @"action": @(action), @"target": self} mutableCopy];
    if (completion) {
        info[@"completion"] = completion;
    }
    if (targetVC) {
        info[@"ViewController"] = targetVC;
    }
    SmartPopNavigationController *deepest = [self deepestSmartPopNavigationController];
    if (deepest.completionBlocks && (deepest.completionBlocks.count > 0)) {
        [deepest.completionBlocks addObject:info];
        return nil;
    } else {
        if (action == TransitPush) {
            [super pushViewController:targetVC animated:animated];
            return nil;
        }
        if (self.viewControllers.count == 1) {
            if (completion)
                completion();
            return nil;
        }
        deepest.completionBlocks = [NSMutableArray arrayWithObject:info];
        if (action == TransitPopTillRoot) {
            return [super popToRootViewControllerAnimated:animated];
        }
        return [self superPopViewControllerAnimated:animated];
    }
}

- (UIViewController *) popViewControllerAnimated:(BOOL)animated
{
    return [[self transitViewControllerAnimated:animated completion:nil action:TransitPopViewController targetVC:nil] firstObject];
}

- (NSArray *)popToRootViewControllerAnimated:(BOOL)animated
{
    return [self transitViewControllerAnimated:animated completion:nil action:TransitPopTillRoot targetVC:nil];
}

#pragma mark - UINavigationControllerDelegate methods

- (void) navigationController:(UINavigationController *) navigationController didShowViewController:(UIViewController *) viewController animated:(BOOL) animated
{
    SmartPopNavigationController *deepest = [self deepestSmartPopNavigationController];
    NSDictionary *info = [deepest.completionBlocks firstObject];
    PopCompletionBlock completion = info[@"completion"];
    if (completion) {
        completion();
    }
    if (self.escalatedDelegate && [self.escalatedDelegate respondsToSelector:@selector(navigationController:didShowViewController:animated:)]) {
        [self.escalatedDelegate navigationController:navigationController didShowViewController:viewController animated:animated];
    }
    if (info) {
        [deepest.completionBlocks removeObjectAtIndex:0];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        if (deepest.completionBlocks.count > 0) {
            NSDictionary *info = [deepest.completionBlocks firstObject]; // next object in the queue
            SmartPopNavigationController *target = info[@"target"];
            if (target.viewControllers.count == 1) { // next VC have popped already to the last VC
                PopCompletionBlock completion = info[@"completion"];
                if (completion) {
                    completion();
                }
                [deepest.completionBlocks removeObjectAtIndex:0];
                for (NSInteger i = 0; i < deepest.completionBlocks.count;) {
                    info = deepest.completionBlocks[i];
                    if ([info[@"target"] isEqual:target]) {
                        completion = info[@"completion"];
                        if (completion) {
                            completion();
                        }
                        [deepest.completionBlocks removeObjectAtIndex:i];
                    } else
                        i++;
                }
            } else {
                BOOL animated = [info[@"animated"] boolValue];
                switch ([info[@"action"] integerValue]) {
                    case TransitPopTillRoot:
                        [target superPopToRootViewControllerAnimated:animated];
                        break;
                    case TransitPopViewController:
                        [target superPopViewControllerAnimated:animated];
                        break;
                    case TransitPush:
                        [target pushViewController:info[@"ViewController"] animated:animated];
                        break;
                    default:
                        break;
                }
            }
        }
    });
}

- (void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (self.escalatedDelegate && [self.escalatedDelegate respondsToSelector:@selector(navigationController:willShowViewController:animated:)]) {
        [self.escalatedDelegate navigationController:navigationController willShowViewController:viewController animated:animated];
    }
}

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    [self transitViewControllerAnimated:animated completion:nil action:TransitPush targetVC:viewController];
}

//- (NSUInteger)navigationControllerSupportedInterfaceOrientations:(UINavigationController *)navigationController
//{}
//
//- (UIInterfaceOrientation)navigationControllerPreferredInterfaceOrientationForPresentation:(UINavigationController *)navigationController
//{}
//
//- (id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
//                          interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController
//{}
//
//- (id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
//                                   animationControllerForOperation:(UINavigationControllerOperation)operation
//                                                fromViewController:(UIViewController *)fromVC
//                                                  toViewController:(UIViewController *)toVC
//{}

@end


text:
module GitHub
  module Markup
    VERSION = '1.4.0'
    Version = VERSION
  end
end

redpajama_set_name: RedPajamaGithub


text:
import threading
import time

import npyscreen

from vent.api.tools import Tools
from vent.helpers.meta import ManifestTools

class ChooseToolsForm(npyscreen.ActionForm):
    """ For picking which tools to add """
    tools_tc = {}

    def repo_tools(self, branch):
        """ Set the appropriate repo dir and get the tools available of it """
        tools = []
        m_helper = Tools()
        repo = self.parentApp.repo_value['repo']
        version = self.parentApp.repo_value['versions'][branch]
        status = m_helper.repo_tools(repo, branch, version)
        if status[0]:
            r_tools = status[1]
            for tool in r_tools:
                tools.append(tool[0])
        return tools

    def create(self):
        """ Update with current tools for each branch at the version chosen """
        self.add_handlers({'^Q': self.quit})
        self.add(npyscreen.TitleText,
                 name='Select which tools to add from each branch selected:',
                 editable=False)
        self.add(npyscreen.Textfield,
                 value='NOTE tools you have already installed will be ignored',
                 color='STANDOUT',
                 editable=False)

        i = 6
        for branch in self.parentApp.repo_value['versions']:
            self.tools_tc[branch] = {}
            self.add(npyscreen.TitleText,
                     name='Branch: ' + branch,
                     editable=False,
                     rely=i,
                     relx=5,
                     max_width=25)
            tools = self.repo_tools(branch)
            i += 1
            for tool in tools:
                value = True
                if tool.startswith('/dev'):
                    value = False
                # tool in base directory
                if tool == '' or tool.startswith(':'):
                    tool = '/' + tool
                self.tools_tc[branch][tool] = self.add(npyscreen.CheckBox,
                                                       name=tool,
                                                       value=value,
                                                       relx=10)
                i += 1
            i += 2

    def quit(self, *args, **kwargs):
        self.parentApp.switchForm('MAIN')

    def on_ok(self):
        """
        Take the tool selections and add them as plugins
        """
        def diff(first, second):
            """
            Get the elements that exist in the first list and not in the second
            """
            second = set(second)
            return [item for item in first if item not in second]

        def popup(original_tools, branch, thr, title):
            """
            Start the thread and display a popup of the tools being added until
            the thread is finished
            """
            thr.start()
            tool_str = 'Adding tools...'
            npyscreen.notify_wait(tool_str, title=title)
            while thr.is_alive():
                tools = diff(ManifestTools(), original_tools)
                if tools:
                    tool_str = ''
                for tool in tools:
                    pre_tool = 'Added: ' + branch + '/' + tool + '\n'
                    tool_str = pre_tool + tool_str
                npyscreen.notify_wait(tool_str, title=title)
                time.sleep(1)
            return

        original_tools = ManifestTools()
        for branch in self.tools_tc:
            tools = []
            for tool in self.tools_tc[branch]:
                if self.tools_tc[branch][tool].value:
                    # get rid of temporary show for multiple tools in same
                    # directory
                    if tool == '/':
                        tools.append(('.', ''))
                    else:
                        tools.append((tool, ''))
            repo = self.parentApp.repo_value['repo']
            version = self.parentApp.repo_value['versions'][branch]
            api_action = Tools(version=version, branch=branch)
            thr = threading.Thread(target=api_action.new, args=(),
                                   kwargs={'tool_type': 'repo',
                                           'uri': repo,
                                           'tools': tools})
            popup(original_tools, branch, thr,
                  'Please wait, adding tools for the ' + branch + ' branch...')
        npyscreen.notify_confirm('Done adding repository: ' +
                                 self.parentApp.repo_value['repo'],
                                 title='Added Repository')
        self.quit()

    def on_cancel(self):
        self.quit()


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;

namespace BrightcoveOS.NET_MAPI_Wrapper.Tests.IntegrationTests.PlaylistRead
{
	[TestFixture]
	public class FindAllPlaylistsTests : PlaylistReadTestBase
	{
		[Test]
		public void FindAllPlaylists_Test_Basic()
		{
			_playlists = _api.FindAllPlaylists();

			Assert.Greater(_playlists.Count, 0);
			Assert.Greater(_playlists[0].VideoIds.Count, 0);
			Assert.Greater(_playlists[0].Videos.Count, 0);
		}
	}
}


text:
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
	margin: 0;
	padding: 0;
	border: 0;
	font-size: 100%;
	font: inherit;
	vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
	display: block;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}

/* Basic elements */
.down{
float:right;
}
#q {
width: 100%;
  display: table-cell;
  opacity: 1;
 font-weight:bold;
font-family: 'Quicksand', sans-serif;
 color:#004169;
 font-size:1.3em;
}

.navbar {
	position:fixed;
	top:0;
	background: #FF9900;
	padding-top:10px;
	padding-bottom: 10px;
	width:100%;
	margin:0;
}
#stuffInNavbar {
	padding-right:5%;
	padding-left:5%;
	margin-left:0 auto;
	margin-right:0 auto;
}
.navbar h2{
	text-align:right;
	float:right;
	color:#ff7700;
	margin-top:5px;
}

footer {
	bottom:0;
	position: fixed;
}

/* Songs list */
#tracks_list span, #tracks_list h4 {
	margin-top:4px;
	color:white;
font-family: 'Quicksand', sans-serif;
	font-weight:bold;
}
#tracks_list span {
	color:gray;
}
#tracks_list span b {
	font-weight: 800;
}
#tracks_list h4 {
	letter-spacing: 2px;
}
#tracks_list h2{
font-family: 'Quicksand', sans-serif;
	font-weight:bold;
	color:#f95a00;
	font-size:20px;
	text-decoration: none;

}
#tracks_list a {
	text-decoration: none;
}
#tracks_list li:hover {
	background:#FFC09D;
}

#tracks_list li {
	padding-right:5%;
	padding-left:5%;
	list-style: none;
	transition:.3s;
	min-height:100px;
}
#tracks_list li:hover {
	padding-left:6%;

}

.plays {
	font-style: italic;
}
#sounds {
	margin-top:80px;
}
.playedSong li {
	background:black;
}
.playedSong li h2, .playedSong li span{
	color:#ff7700 !important;
}
@media screen and (max-width: 900px) {
	#tracks_list h2 {
		font-size:26px;
	}
	#navbar h2 {
		display:none;
	}
}
@media screen and (max-width: 500px) {
	img {
	width:70px;
	margin:5px;
	}
	#tracks_list h2 {
		font-size:18px;
	}
	#tracks_list li, #stuffInNavbar {
		padding-left:5px;
		padding-right:5px;
	}
	#tracks_list li:hover {
	padding-left:5px;
	padding-right:5px;
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <base href="{{ base }}">

    <title>FeedND | Order Pickup Online</title>

    <link href="css/main.css" rel="stylesheet">
    <link href="css/userregistration.css" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Feed ND

Restaurants

Orders

Account

Feed ND

Keep yourself fed by ordering online and picking food up or getting it delivered from great establishments nearby.

User Registration

        <form id="user-add-form" class="form-horizontal" role="form" method="POST" action="users/registration" enctype="application/json" target="">

            Name:

              <input type="text" class="form-control" id="user-name-input" name="name" placeholder="Enter name" required>

            Email:

              <input type="email" class="form-control" id="user-email-input" name="email" placeholder="Enter email" required>

            Password:

              <input type="password" class="form-control" id="user-password-input" name="password" placeholder="Enter password" required>

            Confirm Password:

              <input type="password" class="form-control" id="user-confirm-password-input" name="password" placeholder="Confirm password" required>

            Phone:

              <input type="tel" class="form-control" id="user-phone-input" name="phone" placeholder="Enter phone number" required>

              <button type="submit" class="btn btn-default">Submit</button>

        </form>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>MostracTec</title>

    <?php $this->load->view("includes/header_sources");//carregamos arquivos de estilo ?>

Projeto Mostratec

Iniciação Científica

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                Business Casual

                        <a href="<?= base_url()?>">Home

                        <a href="<?= base_url("blog/home/1")?>">Blog

                        About

                        <a href="<?= base_url('cadastro')?>">Cadastro

                        <a href="<?= base_url('grupos/home/1') ?>">Grupos

                        Logoff


text:
Some matlab scripts used in different projects.

## Install

Using bower

```sh
$ bower install matlab-utils
```

or Cloning

```sh
$ git clone https://github.com/bmelo/matlab-utils.git
```

### Usage

```matlab
% Adding scripts to path
%   change [matlab-utils path] to the full installation path of this library

run( fullfile('[matlab-utils path]', 'libsetup.m') );

% ... your script

```


text:
<?php
namespace Giosh94mhz\GeonamesBundle\Import\StepBuilder;

use Doctrine\Common\Persistence\ObjectManager;
use Giosh94mhz\GeonamesBundle\Entity\Feature;
use Giosh94mhz\GeonamesBundle\Model\Import\DownloadAdapter;
use Giosh94mhz\GeonamesBundle\Import\FileReader\TxtReader;
use Giosh94mhz\GeonamesBundle\Exception\SkipImportException;

/**
 *
 * @author Premi Giorgio <giosh94mz@gmail.com>
 */
class FeatureImportStepBuilder extends AbstractImportStepBuilder
{
    private $om;

    private $locale;

    private $file;
    /**
     * @var \Doctrine\Common\Persistence\ObjectRepository
     */
    private $repository;

    public function __construct(ObjectManager $om)
    {
        $this->om = $om;
        $this->repository = $this->om->getRepository('Giosh94mhzGeonamesBundle:Feature');
        $this->locale = 'en';
    }

    /**
     * Get the locale used for feature name and description
     *
     * @return string locale
     */
    public function getLocale()
    {
        return $this->locale;
    }

    /**
     * Set the locale used for feature name and description
     *
     * @param string $locale Locale
     */
    public function setLocale($locale)
    {
        $this->locale = $locale ?: 'en';

        return $this;
    }

    public function download(DownloadAdapter $download)
    {
        $this->file = $download->add(self::GEONAME_DUMP_URL .  "featureCodes_{$this->locale}.txt");
    }

    public function getClass()
    {
        return 'Feature';
    }

    public function buildReader()
    {
        return new TxtReader($this->file);
    }

    public function buildEntity($value)
    {
        if ( mb_strtolower($value[0]) === 'null' )
            throw new SkipImportException("Well-known null feature");

        list($class, $code) = explode('.', $value[0], 2);

        /* @var $feature \Giosh94mhz\GeonamesBundle\Entity\Feature */
        $feature = $this->repository->find(array('code' => $code, 'class' => $class)) ?: new Feature($class, $code);

        $feature
            ->setName($value[1])
            ->setDescription($value[2]);

        return $feature;
    }
}


text:
#ifdef CONFIG_ARCH_MSM7X27A
#include <mach/rpc_pmapp.h>
#else
#include <linux/device.h>
#include <linux/regulator/consumer.h>
#include <linux/gpio.h>
#include <linux/err.h>
#include <linux/platform_device.h>
/* replace with plaftform specific changes */
#endif

#include "core.h"

/* BeginMMC polling stuff */
#ifdef CONFIG_ARCH_MSM7X27A
#define MMC_PLATFORM_DEV "msm_sdcc.2"
#else
#define MMC_PLATFORM_DEV "sdcc"
#endif

/* End MMC polling stuff */

#define GET_INODE_FROM_FILEP(filp) \
	((filp)->f_path.dentry->d_inode)

#define ATH6KL_INIT_TIMEOUT	(3 * HZ)

wait_queue_head_t init_wq;
static atomic_t init_done = ATOMIC_INIT(0);

int android_readwrite_file(const char *filename,
			   char *rbuf, const char *wbuf, size_t length)
{
	int ret = 0;
	struct file *filp = (struct file *)-ENOENT;
	mm_segment_t oldfs;
	oldfs = get_fs();
	set_fs(KERNEL_DS);

	do {
		int mode = (wbuf) ? O_RDWR : O_RDONLY;
		filp = filp_open(filename, mode, S_IRUSR);

		if (IS_ERR(filp) || !filp->f_op) {
			ret = -ENOENT;
			break;
		}

		if (length == 0) {
			/* Read the length of the file only */
			struct inode    *inode;

			inode = GET_INODE_FROM_FILEP(filp);
			if (!inode) {
				printk(KERN_ERR "android_readwrite_file: Error 2\n");
				ret = -ENOENT;
				break;
			}
			ret = i_size_read(inode->i_mapping->host);
			break;
		}

		if (wbuf) {
			ret = filp->f_op->write(filp, wbuf, length, &filp->f_pos);
			if (ret < 0) {
				printk(KERN_ERR
				       "android_readwrite_file: Error 3\n");
				break;
			}
		} else {
			ret = filp->f_op->read(filp, rbuf, length, &filp->f_pos);
			if (ret < 0) {
				printk(KERN_ERR
				       "android_readwrite_file: Error 4\n");
				break;
			}
		}
	} while (0);

	if (!IS_ERR(filp))
		filp_close(filp, NULL);

	set_fs(oldfs);
	printk(KERN_ERR "android_readwrite_file: ret=%d\n", ret);

	return ret;
}

static int ath6kl_pm_probe(struct platform_device *pdev)
{
#ifdef CONFIG_ARCH_MSM7X27A
	int (*plat_setup_power)(int on);
	plat_setup_power = pdev->dev.platform_data;
	printk(KERN_ERR "%s () enter and will invoke power-up sequence\n",
	       __func__);
	if (plat_setup_power)
		plat_setup_power(1);
#else
	/* replace with plaftform specific changes */
#endif
	return 0;
}

static int ath6kl_pm_remove(struct platform_device *pdev)
{
#ifdef CONFIG_ARCH_MSM7X27A
	int (*plat_setup_power)(int on);
	plat_setup_power = pdev->dev.platform_data;
	printk(KERN_ERR "%s () enter and will invoke power-down sequence\n",
	       __func__);
	if (plat_setup_power)
		plat_setup_power(0);
#else
	/* replace with plaftform specific changes */
#endif
	return 0;
}

static int ath6kl_pm_suspend(struct platform_device *pdev, pm_message_t state)
{
	return 0;
}

static inline void *ar6k_priv(struct net_device *dev)
{
	return wdev_priv(dev->ieee80211_ptr);
}

static int ath6kl_pm_resume(struct platform_device *pdev)
{
	return 0;
}

static struct platform_driver ath6kl_pm_device = {
	.probe      = ath6kl_pm_probe,
	.remove     = ath6kl_pm_remove,
	.suspend    = ath6kl_pm_suspend,
	.resume     = ath6kl_pm_resume,
	.driver     = {
		.name = "wlan_ar6000_pm_dev",
	},
};

void __init ath6kl_sdio_init_platform(void)
{
	char buf[3];
	int length;

	platform_driver_register(&ath6kl_pm_device);

	length = snprintf(buf, sizeof(buf), "%d\n", 1 ? 1 : 0);
	android_readwrite_file("/sys/devices/platform/" MMC_PLATFORM_DEV
			       "/polling", NULL, buf, length);
	length = snprintf(buf, sizeof(buf), "%d\n", 0 ? 1 : 0);
	android_readwrite_file("/sys/devices/platform/" MMC_PLATFORM_DEV
			       "/polling", NULL, buf, length);

	mdelay(50);
}

void __exit ath6kl_sdio_exit_platform(void)
{
	char buf[3];
	int length;
	platform_driver_unregister(&ath6kl_pm_device);

	length = snprintf(buf, sizeof(buf), "%d\n", 1 ? 1 : 0);
	/* fall back to polling */
	android_readwrite_file("/sys/devices/platform/" MMC_PLATFORM_DEV
			       "/polling", NULL, buf, length);
	length = snprintf(buf, sizeof(buf), "%d\n", 0 ? 1 : 0);
	/* fall back to polling */
	android_readwrite_file("/sys/devices/platform/" MMC_PLATFORM_DEV
			       "/polling", NULL, buf, length);
	mdelay(1000);

}

int ath6kl_wait_for_init_comp(void)
{
	int left;

	if (atomic_read(&init_done) == 1)
		return 0;

	left = wait_event_interruptible_timeout(init_wq,
						atomic_read(&init_done) == 1,
						ATH6KL_INIT_TIMEOUT);
	if (left == 0)
		printk(KERN_ERR "timeout while waiting for init operation\n");
	else if (left < 0)
		printk(KERN_ERR "wait for init operation failed: %d\n", left);

	return 0;
}
void ath6kl_notify_init_done(void)
{
	atomic_set(&init_done, 1);
	wake_up(&init_wq);
}


text:
package org.apache.flink.table.runtime.functions.table;

import org.apache.flink.annotation.Internal;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.data.ArrayData;
import org.apache.flink.table.data.GenericRowData;
import org.apache.flink.table.data.MapData;
import org.apache.flink.table.functions.BuiltInFunctionDefinitions;
import org.apache.flink.table.functions.UserDefinedFunction;
import org.apache.flink.table.runtime.functions.BuiltInSpecializedFunction;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.logical.ArrayType;
import org.apache.flink.table.types.logical.LogicalType;
import org.apache.flink.table.types.logical.MapType;
import org.apache.flink.table.types.logical.MultisetType;
import org.apache.flink.table.types.logical.RowType;

/**
 * Flattens ARRAY, MAP, and MULTISET using a table function. It does this by another level of
 * specialization using a subclass of {@link UnnestTableFunctionBase}.
 */
@Internal
public class UnnestRowsFunction extends BuiltInSpecializedFunction {

    public UnnestRowsFunction() {
        super(BuiltInFunctionDefinitions.INTERNAL_UNNEST_ROWS);
    }

    @Override
    public UserDefinedFunction specialize(SpecializedContext context) {
        final LogicalType argType =
                context.getCallContext().getArgumentDataTypes().get(0).getLogicalType();
        switch (argType.getTypeRoot()) {
            case ARRAY:
                final ArrayType arrayType = (ArrayType) argType;
                return new CollectionUnnestTableFunction(
                        context,
                        arrayType.getElementType(),
                        ArrayData.createElementGetter(arrayType.getElementType()));
            case MULTISET:
                final MultisetType multisetType = (MultisetType) argType;
                return new CollectionUnnestTableFunction(
                        context,
                        multisetType.getElementType(),
                        ArrayData.createElementGetter(multisetType.getElementType()));
            case MAP:
                final MapType mapType = (MapType) argType;
                return new MapUnnestTableFunction(
                        context,
                        RowType.of(false, mapType.getKeyType(), mapType.getValueType()),
                        ArrayData.createElementGetter(mapType.getKeyType()),
                        ArrayData.createElementGetter(mapType.getValueType()));
            default:
                throw new UnsupportedOperationException("Unsupported type for UNNEST: " + argType);
        }
    }

    public static LogicalType getUnnestedType(LogicalType logicalType) {
        switch (logicalType.getTypeRoot()) {
            case ARRAY:
                return ((ArrayType) logicalType).getElementType();
            case MULTISET:
                return ((MultisetType) logicalType).getElementType();
            case MAP:
                final MapType mapType = (MapType) logicalType;
                return RowType.of(false, mapType.getKeyType(), mapType.getValueType());
            default:
                throw new UnsupportedOperationException("Unsupported UNNEST type: " + logicalType);
        }
    }

    // --------------------------------------------------------------------------------------------
    // Runtime Implementation
    // --------------------------------------------------------------------------------------------

    private abstract static class UnnestTableFunctionBase extends BuiltInTableFunction<Object> {

        private final transient DataType outputDataType;

        UnnestTableFunctionBase(SpecializedContext context, LogicalType outputType) {
            super(BuiltInFunctionDefinitions.INTERNAL_UNNEST_ROWS, context);
            // The output type in the context is already wrapped, however, the result of the
            // function is not. Therefore, we need a custom output type.
            outputDataType = DataTypes.of(outputType).toInternal();
        }

        @Override
        public DataType getOutputDataType() {
            return outputDataType;
        }
    }

    /** Table function that unwraps the elements of a collection (array or multiset). */
    public static final class CollectionUnnestTableFunction extends UnnestTableFunctionBase {

        private static final long serialVersionUID = 1L;

        private final ArrayData.ElementGetter elementGetter;

        public CollectionUnnestTableFunction(
                SpecializedContext context,
                LogicalType outputType,
                ArrayData.ElementGetter elementGetter) {
            super(context, outputType);
            this.elementGetter = elementGetter;
        }

        public void eval(ArrayData arrayData) {
            if (arrayData == null) {
                return;
            }
            final int size = arrayData.size();
            for (int pos = 0; pos < size; pos++) {
                collect(elementGetter.getElementOrNull(arrayData, pos));
            }
        }

        public void eval(MapData mapData) {
            if (mapData == null) {
                return;
            }
            final int size = mapData.size();
            final ArrayData keys = mapData.keyArray();
            final ArrayData values = mapData.valueArray();
            for (int pos = 0; pos < size; pos++) {
                final int multiplier = values.getInt(pos);
                final Object key = elementGetter.getElementOrNull(keys, pos);
                for (int i = 0; i < multiplier; i++) {
                    collect(key);
                }
            }
        }
    }

    /** Table function that unwraps the elements of a map. */
    public static final class MapUnnestTableFunction extends UnnestTableFunctionBase {

        private static final long serialVersionUID = 1L;

        private final ArrayData.ElementGetter keyGetter;

        private final ArrayData.ElementGetter valueGetter;

        public MapUnnestTableFunction(
                SpecializedContext context,
                LogicalType outputType,
                ArrayData.ElementGetter keyGetter,
                ArrayData.ElementGetter valueGetter) {
            super(context, outputType);
            this.keyGetter = keyGetter;
            this.valueGetter = valueGetter;
        }

        public void eval(MapData mapData) {
            if (mapData == null) {
                return;
            }
            final int size = mapData.size();
            final ArrayData keyArray = mapData.keyArray();
            final ArrayData valueArray = mapData.valueArray();
            for (int i = 0; i < size; i++) {
                collect(
                        GenericRowData.of(
                                keyGetter.getElementOrNull(keyArray, i),
                                valueGetter.getElementOrNull(valueArray, i)));
            }
        }
    }
}


text:
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private Q_SLOTS:
    void onProtocolActivate(const QUrl& url);
private:
    Ui::MainWindow *ui;
    win32::QUrlProtocolHandler urlProtocolHandler;
};

#endif // MAINWINDOW_H


text:
class WikiHouse::UPegPassThruConnector < WikiHouse::PocketConnector

  def initialize(thickness: nil, count: 1)
    super(length_in_t: 9, width_in_t: 2, thickness: thickness, rows: 1, count: count)

  end

  def draw!(bounding_origin: nil, part_length: nil, part_width: nil)
    pockets_list = []
    self.class.drawing_points(bounding_origin: bounding_origin,
                              count: count,
                              rows: self.respond_to?(:rows) ? rows : 1,
                              part_length: part_length,
                              part_width: part_width,
                              item_length: thickness,
                              item_width: width) { |row, col, location|
      pockets_list << draw_pocket!(location: [location.x ,
                                              location.y - (4 * thickness),
                                              location.z])
    }
    pockets_list
  end

  def rows
    1
  end

  def upeg?
    true
  end

  def upeg_pass_thru?
    true
  end

  def name
    :upeg_pass_thru
  end
end


text:
Django Version Collaboration System for Courselets
---------------------------------------------------------------------

Basic goals
+++++++++++++++

* Git-like VCS for text+metadata rather than code
* Application model is community-remix-forest rather than code-pyramid.
* stored in standard database (rather than files)
* Integrates VCS capabilities into standard online platform (Django)
* KISS: sweetspot of core VCS benefits without Git's complexity, for non-Git-users
* Designed for courselets active-learning materials, which consists of one datatype (Lesson) and two levels of container (Unit and Course), all three under VC.

VCS layers
++++++++++++

* **Lesson**

  * Lesson is a *commit*
  * UnitLesson is a *branch* (HEAD pointer)

* **Unit**: a repository of UnitLessons

  * Unit is a commit
  * CourseUnit is branch

* **Course**: a repository of CourseUnits

  * Course is a commit
  * CourseBranch is a branch

Some simplifying assumptions:

* In general, we store VCS tree structure directly on commit objects (with **parent** and **mergeParent** pointers).

* In general, commits are "snapshots" of content (i.e. exact same form as the "working tree"), with no special attempt to compress or diff its storage.  Our content is typically a short text (<8k?), so this seems like a reasonable simplification in the era of cheap big storage.

* it follows that branch (HEAD) can point to content that is not yet permanently committed, i.e. owner can go on modifying that content until they decide it's ready to commit (or another event, e.g. fork, forces a commit).

Collaboration Philosophy
+++++++++++++++++++++++++

* Instructors are not expected to understand the Git version control model, especially complex concepts like branches and rebasing.

* instead, Unit provides intuitive freedom to modify a lesson however you want for this Unit, without affecting any other units.

* anyone can fork anything (creating new branch within that repository), but only the "master" branch owned by the instructor is shown to users as the "official version" of that repository.

* user can fork to create a new branch at several different levels

  * fork a Lesson either within same Unit or a different Unit.
  * fork a Unit either within same Course or a different Course.  Forking a Unit in turn forks all the Lessons within that Unit.
  * fork a Course either as new public course or private branch.  Forking a Course in turns forks all the Units within that Course.

* in general, searches will operate only on "master" content (e.g. Lessons pointed to by UnitLessons with isMaster=True).

* following the Git model of "fine-grained" commit history will make automatic merge much more useful (by giving users easy control over what changes to accept).  This seems like the Git sweet-spot, i.e. the part that's both easiest for users to understand, and most useful for them.  Besides, disk-space is not really an issue...  Policy:

  * if user provides a Commit Message after modifying an object, commit it permanently.
  * various views should warn the instructor: "you have not committed a snapshot of the current version.  If you are done changing it (for the moment), please commit it by entering a Commit Message on the Edit tab".

* automatically commit when operationally appropriate.  While the user should be encouraged to commit fine-grained changes, we will commit automatically on various events:

  * checkout by someone other than Lesson owner (addedBy) will commit it, since otherwise changes by different people would get mixed in the same commit.
  * fork
  * publish
  * Response
  * course over (future commitTime): consider allowing commitTime to be set to a future date, so that it will automatically be considered committed at that time.  Also consider inheriting future commitTime from container (e.g. if Unit has future commitTime, creating a new UnitLesson in this Unit should inherit that future commitTime).

* when someone first forks a lesson, ask them to review it carefully for typos or errors, and to make corrections (on the parent branch).  Hopefully this will mostly eliminate the need for propagating pull requests to "upstream" branches.  (Then ask them if they want to change the focus, audience or substance significantly, which adds a "cut" edge.)

* in general, everyone on "the same branch" (see bridge-cut description below) will receive pull requests for each other's changes.

* goal is for auto-merge with manual resolution: top-down view of diffs lets you drill down.  If you need to intervene manually for some parts of the merge, you do so for those specific part(s).  Finally you can just accept the top-level merge and it will merge everything else automatically.

Proposed data model
---------------------

* **commitTime** indicates commit status

  * NULL indicates uncommitted
  * commitTime in the future indicates uncommitted.  If container has future commitTime, new HEADs created in this container should inherit this future commitTime.
  * commitTime in the past indicates committed.

* **treeID, isMaster, branch** multiple-HEAD model: within a given container (e.g. Unit) we can have many versions of something (with same treeID), one of which will have isMaster=True, and also distinguished by owner (addedBy) and branch name.  This model applies at several levels:

  * UnitLesson: represents HEAD pointer for a Lesson
  * CourseUnit: represents HEAD pointer for a Unit
  * CourseBranch: represents HEAD pointer for a Course

* in a given course, master Unit, UnitLesson, Course IDs will not change.  I.e. when we add a Unit to a course with isMaster=True, we create a new Unit object (possibly cloned from an existing Unit in another course), and we keeping using that object in that course thereafter (unless of course the user deletes the unit from the course).  Similarly, whenever we add a UnitLesson with isMaster=True to a Unit (e.g. cloned from another Unit), we always add it as a newly created UnitLesson object, and we keep using that object in that Unit thereafter (unless of course the user deletes it).

* UnitLesson **isMaster=True** indicates what version will actually be shown in that Unit.  This allows many alternate versions (including student users') in the same Unit, all but one of which have isMaster=False.  This field must be indexed in the db properly!!  Note that to keep public IDs stable, once a UnitLesson has isMaster=True, it becomes the public ID.  Another way of saying this: you will never reset it to isMaster=False (in order to set some other UnitLesson.isMaster=True), because that would change the public ID of this Lesson in this Unit.  Instead you just change what Lesson this UnitLesson points to (and possibly its branch name).

* Unit and Course should use **commitID** as the key value for pointing to parent(s), rather than just using primary key in the usual way.  This is a solid technical solution for allowing us to keep stable both the public ID and the parent pointer(s).  commitID rules:

  * for an uncommitted object, commitID=NULL.
  * for a newly committed object, commitID=self.pk
  * when a committed object is cloned for checkout (see below), the commitID is copied to the commit-clone, and the original object (now checked out) is set to commitID=NULL to reflect that it is now checked out (uncommitted).

  We will have to supply a get_parent() method that looks up parent object by commitID.

  Note this issue does not apply to Lesson, because Lesson ID is never public (what's publicly visible is the UnitLesson ID).

* Implies a fork-commit-checkout-clone pattern for Unit and Course if isMaster=True:

  * when someone forks an object, we must commit it.
  * when the owner wants to modify (checkout) the committed object, if it has isMaster=True, then we must clone it in a special way to preserve the HEAD ID.  Specifically, we create a clone of the committed HEAD object, remove the commit lock from our HEAD object, and make it point to the clone as its parent.  This preserves the tree structure while allowing us to continue editing the same HEAD ID.  Note that we only have to do this in the specific case where owner wants to modify (checkout) a *committed* isMaster=True object.

Structural Segmentation Policies
---------------------------------

The Git/GitHub pull-request model is not suitable for Courselets, because its "code-pyramid" model is all about convergence to a "master" who can be relied on to decide what changes to accept.  In the Courselets community-remix-forest, by contrast, that will not work, because there is no such "master"; even more fundamentally, divergence (segmentation) is as valuable as convergence.  What we want is for segmentation to emerge naturally and with minimal effort from users, e.g. I should automatically receive pull-requests from within my "segment", but not outside.

We will achieve this via a mechanism of edges added onto a VCS tree that explicitly represent what "pull policy" a user wants to apply in the future to a given subtree:

* emergent segmentation via bridge vs. cut edges: generalize Git's concept of "merge strategy" to indicate whether you want to receive future pull requests or not.  E.g.

  * suggest merging future pull-requests from this subtree (typically this would be associated with merging in last state of this subtree)
  * offer option to merge ...
  * hide ... (typically this would be associated with merge -s ours operation)
  * NULL (no preference)

  You could also suggest flow the other direction:

  * suggest merging my commits to this subtree
  * offer option to merge ...
  * hide ...
  * NULL (no preference)

  For a given user considering possible things to merge into his branch, his PULL setting always overrides other people's PUSH settings.

  Operates the same as recursive merge search, i.e. backtrack both HEADS until you find a common merge origin, bridge, or cut, whichever comes first.  Bridge propagates the pull-request; cut blocks it.

* useful to extract the clique-structure of which HEADs are convergent (get each other's changes) vs. divergent (do not).

* can consider the PUSH-edge version of this to be a generalization of pull-requests.  That is, you can either suggest your changes to everyone (by adding PUSH edge from your HEAD to root of the tree), or to a specific branch / subtree.

Automatic Merge
---------------------

Use my Word interval nested containment list 3-way merge algorithm.

* line-based diff (e.g. Git) cannot merge changes in the same paragraph
* Git cannot handle re-ordering / remixing; after a block of text is moved, changes within it can no longer be merged.

VCS User Interface
---------------------

* presumably there will be a new tab "Versions" or "History" that shows gitg-like diagram of commits and HEADs.  Allows user to click to view a diff, or switch branches etc.

* user who gets a pull-request can of course reject changes (selectively). (imagine this as table of commits with checkboxes so you can accept all, none, or subset.

* can propagate pull requests to downstream branches, but only if they map cleanly onto that branch.


text:
require 'net/http'
require 'json'
require 'time'

module Terminal

  # The gem version.
  VERSION = '1.0.1'

  # The Terminal.com API version.
  API_VERSION = 'v0.1'

  # The default headers for the requests.
  HEADERS = {'Content-Type' => 'application/json'}

  # Any network error that can potentially occur in Terminal.call
  # should be encapsulated in this. See {Terminal.call} for implementation
  # details.
  #
  # @api plugin
  class NetworkError < StandardError
    attr_reader :original_error

    # @param original_error [Exception] The exception raised by an HTTP library.
    # @see Terminal.call
    def initialize(original_error)
      @original_error = original_error
      super <<-EOF
Network error (#{original_error.class}): #{original_error.message}
      EOF
    end
  end

  # @!group BROWSE SNAPSHOTS & USERS

  # Get information on a snapshot.
  #
  # @param snapshot_id [String] Snapshot ID (the last part of the snapshot URL).
  # @return [Hash] The response data parsed from JSON.
  # @raise [Terminal::NetworkError] Any network-layer error.
  #
  # @example
  #   Terminal.get_snapshot('987f8d702dc0a6e8158b48ccd3dec24f819a7ccb2756c396ef1fd7f5b34b7980')
  #   # {"snapshot" => {"title" => "Official Ubuntu 14.04", "tags" => "ubuntu", "createdAt" => "2014-07-23T20:27:41.743Z", ...}}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#get-snapshot Terminal.com API docs
  def self.get_snapshot(snapshot_id)
    call('/get_snapshot', snapshot_id: snapshot_id)
  end

  # Get information on a user.
  #
  # @param username [String] Any valid username (i. e. `botanicus`).
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   Terminal.get_profile('botanicus')
  #   # {"user" => {"name" => "James C Russell", "url" => "https://twitter.com/botanicus", "location" => "London, UK", ...}}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#get-profile Terminal.com API docs
  def self.get_profile(username)
    call('/get_profile', username: username)
  end

  # Get a count of public snapshots, optionally filtered.
  #
  # @param options [Hash] Filtering options.
  # @option options :username [String] Any valid username (i. e. `botanicus`).
  # @option options :tag [String] Any tag (i. e. `ubuntu`).
  # @option options :featured [true, false] Search only for featured (or non-featured).
  # @option options :title [String] Title to be *matched* against the existing snapshots.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example Count of all the public snapshots.
  #   Terminal.count_public_snapshots
  #   # {"snapshot_count" => 474}
  #
  # @example Count of all the featured snapshots.
  #   Terminal.count_public_snapshots(featured: true)
  #   # {"snapshot_count" => 135}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#count-public-snapshots Terminal.com API docs
  def self.count_public_snapshots(**options)
    ensure_options_validity(options,
      :username, :tag, :featured, :title)

    call('/count_public_snapshots', options)
  end

  # Get a list of public snapshots, optionally filtered
  # and/or paginated.
  #
  # @param options [Hash] Filtering and pagination options.
  # @option options (see .count_public_snapshots)
  # @option options :page [String] Use with `perPage` for pagination.
  # @option options :perPage [String] Use with `page` for pagination.
  # @option options :sortby [String] Either `popularity` or `date`.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example Return all the public snapshots.
  #   Terminal.list_public_snapshots
  #   # {"snapshots" => [{"title" => "Decision Tree", "tags" => "python,ipython", ...}, {...}]}
  #
  # @example Return all the featured snapshots from user botanicus.
  #   Terminal.list_public_snapshots(username: 'botanicus', featured: true)
  #
  # @example Return the first page of the search results with 10 items per page, sorted by date.
  #   Terminal.list_public_snapshots(tag: 'ubuntu', page: 1, perPage: 10, sortby: 'date')
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#list-public-snapshots Terminal.com API docs
  def self.list_public_snapshots(**options)
    ensure_options_validity(options,
      :username, :tag, :featured, :title, :page, :perPage, :sortby)

    call('/list_public_snapshots', options)
  end

  # @!endgroup
  # @!group CREATE AND MANAGE TERMINALS

  # Get a list of all Terminal instances owned by your account.
  #
  # @param user_token [String] Your user token.
  # @param access_token [String] Your access token.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   Terminal.list_terminals(user_token, access_token)
  #   # {"terminals" => [{"name" => "Coding Interview: John Doe Jr", "ram" => "256", ...}, {...}]}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#list-terminals Terminal.com API docs
  def self.list_terminals(user_token, access_token)
    call('/list_terminals',
      user_token: user_token, access_token: access_token)
  end

  # Get info about a Terminal instance of yours. You can
  # specify either `container_key` or `subdomain`.
  #
  # @param (see .list_terminals)
  # @param options [Hash] Provide either `container_key` or `subdomain`.
  # @option options :container_key [String] A valid container key.
  #   You can get it through {.list_terminals}.
  # @option options :subdomain [String] Subdomain of your Terminal (i. e. `johndoe117`).
  #   You can see it in the address bar when you're in the Terminal IDE or through {.list_terminals}.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example Get Terminal info with a container_key.
  #   # Using get_terminal directly with list_terminals doesn't really
  #   # make sense, since you get all the data in list_terminals, so there
  #   # is no need to call get_terminal. This is just to show how you
  #   # can get your container key. It works the same with a subdomain.
  #   terminals = Terminal.list_terminals(user_token, access_token)
  #   container_key = terminals['terminals'].first['container_key']
  #
  #   Terminal.get_terminal(user_token, access_token, container_key: container_key)
  #   # {"terminal" => {"name" => "Coding Interview: John Doe Jr", "ram" => "256", ...}}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#get-terminal Terminal.com API docs
  def self.get_terminal(user_token, access_token, **options)
    ensure_options_validity(options, :container_key, :subdomain)

    options.merge!(user_token: user_token, access_token: access_token)

    call('/get_terminal', options)
  end

  # Start a Terminal instance based on a snapshot.
  #
  # @param (see .list_terminals)
  # @param snapshot_id (see .get_snapshot)
  # @param options [Hash] Configuration of the new Terminal.
  # @option options :cpu [String] How much CPU is required.
  #   Has to be one of the available {https://www.terminal.com/faq#instanceTypes instance types}
  #   and corresponding `:ram` option has to be provided.
  # @option options :ram [String] How much RAM is required.
  #   Has to be one of the available {https://www.terminal.com/faq#instanceTypes instance types}
  #   and corresponding `:cpu` option has to be provided.
  # @option options :temporary [String] If the Terminal is supposed to be temporary or not.
  #   {https://www.terminal.com/faq#temporaryTerminals Temporary Terminals} are automatically
  #   deleted on inactivity.
  # @option options :name [String] Terminal name.
  # @option options :autopause [String] Whether the Terminal should be {https://www.terminal.com/faq#idleSettings auto-paused on inactivity}.
  #   This can be edited later using {.set_terminal_idle_settings}.
  # @option options :startup_script [String] Shell script to be run once the Terminal is ready.
  #   As of now it cannot contain newlines, so setting a different interpreter than `/bin/sh` is impossible.
  # @option options :custom_data [String] Metadata of your Terminal. Anything you need. It will be accessible through {.get_terminal},
  #   but not from within the Terminal itself.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  # @raise [ArgumentError] If either `ram` or `cpu` is specified. These options has to come together.
  #
  # @example
  #   response = Terminal.start_snapshot(user_token, access_token, "57eff3574ac8d438224dc3aa1c6431a0dbac849a0c254e89be2e758d8113c234", name: "Test")
  #   # {"request_id" => "1418068796272::james@101ideas.cz:create:234509::333c43ab-f6cc-41a3-8307-0fcc4ea3cfb5"}
  #   Terminal.request_progress(response['request_id'])
  #   # {"operation" => "create", "status" => "success", ... }
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#start-snapshot Terminal.com API docs
  # @see https://www.terminal.com/faq#instanceTypes Terminal Instance types
  # @see .edit_terminal
  # @see .set_terminal_idle_settings
  def self.start_snapshot(user_token, access_token, snapshot_id, **options)
    ensure_both_cpu_and_ram_are_provided(options)
    ensure_options_validity(options,
      :cpu, :ram, :temporary, :name, :autopause, :startup_script, :custom_data)

    options.merge!(user_token: user_token, access_token: access_token, snapshot_id: snapshot_id)

    call('/start_snapshot', options)
  end

  # Delete a Terminal instance.
  #
  # @param (see .list_terminals)
  # @param container_key [String] A valid container key.
  #   You can get it through {.list_terminals}.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#delete-terminal Terminal.com API docs
  def self.delete_terminal(user_token, access_token, container_key)
    call('/delete_terminal',
      user_token: user_token, access_token: access_token, container_key: container_key)
  end

  # Reboot a Terminal instance.
  #
  # @param (see .delete_terminal)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#restart-terminal Terminal.com API docs
  def self.restart_terminal(user_token, access_token, container_key)
    call('/restart_terminal',
      user_token: user_token, access_token: access_token, container_key: container_key)
  end

  # Pause a Terminal instance. The instance will be offline
  # and inaccessible, and you will not be charged as long as
  # it remains paused.
  #
  # @param (see .delete_terminal)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#pause-terminal Terminal.com API docs
  def self.pause_terminal(user_token, access_token, container_key)
    call('/pause_terminal',
      user_token: user_token, access_token: access_token, container_key: container_key)
  end

  # Continue running a Terminal instance. The Terminal will
  # continue being charged, and will keep running so long
  # as you maintain a positive balance in your account.
  #
  # @param (see .delete_terminal)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#resume-terminal Terminal.com API docs
  def self.resume_terminal(user_token, access_token, container_key)
    call('/resume_terminal',
      user_token: user_token, access_token: access_token, container_key: container_key)
  end

  # Edit the resources and/or name of a Terminal instance.
  #
  # @param (see .delete_terminal)
  # @param options [Hash] New Terminal configuration.
  # @option options :cpu [String] How much CPU is required.
  #   Has to be one of the available {https://www.terminal.com/faq#instanceTypes instance types}
  #   and corresponding `:ram` option has to be provided.
  #   This option is required.
  # @option options :ram [String] How much RAM is required.
  #   Has to be one of the available {https://www.terminal.com/faq#instanceTypes instance types}
  #   and corresponding `:cpu` option has to be provided.
  #   This option is required.
  # @option options :diskspace [String] How much diskspace is required.
  #   If you want to set to more than 20 GB, you need 25 MB of ram per GB.
  #   This option is required.
  # @option options :name [String] Terminal name.
  # @return (see .get_snapshot)
  # @raise (see .start_snapshot)
  #
  # @example
  #   Terminal.edit_terminal(user_token, access_token, "f9954bd3-5da1-4e17-a688-7791d87ceb6e", cpu: "50", ram: "800", diskspace: "10")
  #   # {"status": "success", "request_id": "1418071005245::james@101ideas.cz:edit:234583::d86c5b44-f716-45d1-85d2-9968fdda15d6"}

  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#edit-terminal Terminal.com API docs
  # @see https://www.terminal.com/faq#instanceTypes Terminal Instance types
  def self.edit_terminal(user_token, access_token, container_key, **options)
    ensure_both_cpu_and_ram_are_provided(options)
    ensure_options_present(options, :cpu, :ram, :diskspace)

    ensure_options_validity(options,
      :cpu, :ram, :diskspace, :name)

    options.merge!(user_token: user_token, access_token: access_token, container_key: container_key)

    call('/edit_terminal', options)
  end

  # @!endgroup
  # @!group CREATE AND MANAGE SNAPSHOTS

  # Get a list of snapshots owned by your account, optionally
  # filtered by the owner's username, a tag, or the snapshot's
  # featured status. You may use a combination of filters.
  #
  # @param (see .list_terminals)
  # @param options [Hash] Filtering and pagination options.
  # @option options (see .list_public_snapshots)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example Return all the snapshots owned by your account.
  #   Terminal.list_snapshots(user_token, access_token)
  #   # {"snapshots" => [{"title" => "Decision Tree", "tags" => "python,ipython", ...}, {...}]}
  #
  # @example Return all the featured snapshots owned by your account.
  #   Terminal.list_snapshots(user_token, access_token, featured: true)
  #
  # @example Return the first page of the search results with 10 items per page, sorted by date.
  #   Terminal.list_snapshots(user_token, access_token, tag: 'ubuntu', page: 1, perPage: 10, sortby: 'date')
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#list-snapshots Terminal.com API docs
  def self.list_snapshots(user_token, access_token, **options)
    ensure_options_validity(options,
      :username, :tag, :featured, :title, :page, :perPage)

    options.merge!(user_token: user_token, access_token: access_token)

    call('/list_snapshots', options)
  end

  # Get a count of snapshots owned by your account, optionally
  # filtered by the owner's username, a tag, or the snapshot's
  # featured status. You may use a combination of filters.
  #
  # @param (see .list_terminals)
  # @param options [Hash] Filtering options.
  # @option options (see .count_public_snapshots)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example Number of all the snapshots owned by your account.
  #   Terminal.count_snapshots(user_token, access_token)
  #   # {"snapshot_count" => 12}
  #
  # @example Number of all the featured snapshots owned by your account.
  #   Terminal.count_public_snapshots(user_token, access_token, featured: true)
  #   # {"snapshot_count" => 2}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#count-snapshots Terminal.com API docs
  def self.count_snapshots(user_token, access_token, **options)
    ensure_options_validity(options,
      :username, :tag, :featured, :title)

    options.merge!(user_token: user_token, access_token: access_token)

    call('/count_snapshots', options)
  end

  # Delete a snapshot from your account. This cannot be undone.
  #
  # @param (see .list_terminals)
  # @param snapshot_id (see .get_snapshot)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#delete-snapshot Terminal.com API docs
  def self.delete_snapshot(user_token, access_token, snapshot_id)
    call('/delete_snapshot',
      user_token: user_token,
      access_token: access_token,
      snapshot_id: snapshot_id)
  end

  # Edit the metadata of a snapshot owned by your account.
  #
  # @param (see .delete_snapshots)
  # @param options [Hash] New snapshot metadata.
  # @option options :body [String] The snapshot description.
  # @option options :title [String] The snapshot title.
  # @option options :readme [String] The README.
  # @option options :tags [String] Comma-separated list of tags (i. e. `ubuntu,ruby`).
  # @option options :public [Boolean] Whether the snapshot will be accessible by other users.
  # @option options :custom_data [String] Metadata of your Terminal. Anything you need.
  #   It will be accessible through {.get_terminal}, but not from within the Terminal itself.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#edit-snapshot Terminal.com API docs
  def self.edit_snapshot(user_token, access_token, snapshot_id, **options)
    ensure_options_validity(options,
      :body, :title, :readme, :tags, :public, :custom_data)

    options.merge!(user_token: user_token, access_token: access_token, snapshot_id: snapshot_id)

    call('/edit_snapshot', options)
  end

  # Create a snapshot of a Terminal instance.
  #
  # @param (see .delete_terminal)
  # @param options [Hash] Snapshot metadata.
  # @option options (see .edit_snapshot)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#snapshot-terminal Terminal.com API docs
  def self.snapshot_terminal(user_token, access_token, container_key, **options)
    ensure_options_validity(options,
      :body, :title, :readme, :tags, :public)

    options.merge!(user_token: user_token, access_token: access_token, container_key: container_key)

    call('/snapshot_terminal', options)
  end

  # @!endgroup
  # @!group MANAGE TERMINAL ACCESS

  # Add to the list of your other Terminals who have access
  # to one of your Terminal instances.
  #
  # Currently this feature doesn't have GUI, so don't be surprised
  # if you haven't come across it yet.
  #
  # @param (see .delete_terminal)
  # @param links [Array<Hash>] Links are hashes with keys `port` and `source`.
  #   Port is any port number and source is any subdomain (i. e. `botanicus117`).
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   container_key = "1123587c-7aec-4b91-90c1-2de534033989"
  #   link = {port: 3000, source: "botanicus117"}
  #   Terminal.add_terminal_links(user_token, access_token, container_key, link)
  #   # {"status":"success"}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#add-terminal-links Terminal.com API docs
  def self.add_terminal_links(user_token, access_token, container_key, *links)
    call('/add_terminal_links',
      user_token: user_token,
      access_token: access_token,
      container_key: container_key,
      links: links)
  end

  # Remove from the list of Terminals who have access to one
  # of your Terminal instances.
  #
  # @param (see .add_terminal_links)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#remove-terminal-links Terminal.com API docs
  def self.remove_terminal_links(user_token, access_token, container_key, *links)
    call('/remove_terminal_links',
      user_token: user_token,
      access_token: access_token,
      container_key: container_key,
      links: links)
  end

  # List users and emails with view or edit access to one
  # of your Terminal instances.
  #
  # @param (see .delete_terminal)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   Terminal.list_terminal_access(user_token, access_token, "268b0082-c96c-4c74-bf0a-a5d6d4c16b01")
  #   # {"is_public_list" => ["80", "3000"],
  #   #  "access_rules" => ["3000::*@cloudlabs.io", "*::james@101ideas.cz", "IDE::james@101ideas.cz", "IDE::terminal@cloudlabs.io"],
  #   #  "links"=>["3000::botanicus117"]}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#list-terminal-access Terminal.com API docs
  # @see https://www.terminal.com/faq#terminalAccess Terminal.com FAQ: Terminal access
  def self.list_terminal_access(user_token, access_token, container_key)
    call('/list_terminal_access',
      user_token: user_token,
      access_token: access_token,
      container_key: container_key)
  end

  # Edit the list of users and emails who have access to one
  # of your Terminal instances.
  #
  # @param (see .delete_terminal)
  # @param options [Hash] Access rules.
  # @option options :is_public_list [Array] List of open ports.
  #   Port `80` is open by default, you can add additional ports.
  # @option options :access_rules [Array] Array of access rules.
  #   An access rule is `<port>::<email>`. Port can be a port number,
  #   `IDE` or an asterisk and email can contain asterisks.
  #   **Examples:** `"3000::*@cloudlabs.io"`, `"*::james@101ideas.cz",
  #   `"IDE::james@101ideas.cz"`.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#edit-terminal-access Terminal.com API docs
  # @see https://www.terminal.com/faq#terminalAccess Terminal.com FAQ: Terminal access
  # @see https://www.terminal.com/faq#openPorts Terminal.com FAQ: Opening additional ports
  def self.edit_terminal_access(user_token, access_token, container_key, **options)
    ensure_options_validity(options, :is_public_list, :access_rules)

    options.merge!(user_token: user_token, access_token: access_token, container_key: container_key)

    call('/edit_terminal_access', options)
  end

  # @!endgroup
  # @!group MANAGE TERMINAL DNS & DOMAINS

  # Get a list of domains in your CNAME record pool. Domains
  # returned by this call can be associated to your Terminal
  # instances.
  #
  # @param (see .list_terminals)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   Terminal.get_cname_records(user_token, access_token)
  #   # {"available" => ["101ideas.cz", "terminal.101ideas.cz"]], "assigned": []}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#get-cname-records Terminal.com API docs
  # @see https://www.terminal.com/faq#cname Terminal.com FAQ: Using my own domains for my Terminals?
  def self.get_cname_records(user_token, access_token)
    call('/get_cname_records',
      user_token: user_token, access_token: access_token)
  end

  # Add a domain or subdomain of Terminal.com to your CNAME
  # record pool, making it available to be associated with
  # one of your Terminal instances.
  #
  # @param (see .list_terminals)
  # @param domain [String] A domain (i. e. `101ideas.cz`).
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#add-domain-to-pool Terminal.com API docs
  # @see https://www.terminal.com/faq#cname Terminal.com FAQ: Using my own domains for my Terminals?
  def self.add_domain_to_pool(user_token, access_token, domain)
    call('/add_domain_to_pool',
      user_token: user_token, access_token: access_token, domain: domain)
  end

  # Remove a domain or subdomain of Terminal.com from your
  # CNAME record pool.
  #
  # @param (see .add_domain_to_pool)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#remove-domain-from-pool Terminal.com API docs
  # @see https://www.terminal.com/faq#cname Terminal.com FAQ: Using my own domains for my Terminals?
  def self.remove_domain_from_pool(user_token, access_token, domain)
    call('/remove_domain_from_pool',
      user_token: user_token, access_token: access_token, domain: domain)
  end

  # Map a domain in your CNAME record pool to one of your
  # Terminal instances, making it accessible via that domain.
  #
  # @param (see .add_domain_to_pool)
  # @param subdomain [String] Subdomain of the Terminal you want the domain assigned to.
  # @param port [String] Which port on the Terminal should it point to?
  #   This will typically be either `80` if you're using Apache or Nginx
  #   or any other number if you're using say Thin or Puma.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   Terminal.add_cname_record(user_token, access_token, 'terminal.101ideas.cz', 'botanicus117', 3000)
  #   # {"available" => [...], "assigned" => [{"domain" => "terminal.101ideas.cz", "subdomain" => "botanicus117", "port" => "3000"}]}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#add-cname-record Terminal.com API docs
  # @see https://www.terminal.com/faq#cname Terminal.com FAQ: Using my own domains for my Terminals?
  def self.add_cname_record(user_token, access_token, domain, subdomain, port)
    call('/add_cname_record',
      user_token: user_token,
      access_token: access_token,
      domain: domain,
      subdomain: subdomain,
      port: port)
  end

  # Remove a domain mapping to one of your Terminal instances.
  # This will mean you can no longer access the Terminal instance
  # from that domain.
  #
  # @param (see .add_domain_to_pool)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#remove-cname-record Terminal.com API docs
  # @see https://www.terminal.com/faq#cname Terminal.com FAQ: Using my own domains for my Terminals?
  def self.remove_cname_record(user_token, access_token, domain)
    call('/remove_cname_record',
      user_token: user_token,
      access_token: access_token,
      domain: domain)
  end

  # @!endgroup
  # @!group MANAGE TERMINAL IDLE SETTINGS

  # Set the {https://www.terminal.com/faq#idleSettings idle settings} for your Terminal.
  #
  # @param (see .delete_terminal)
  # @param action [String] Either `downgrade` or `pause`.
  # @param triggers [Hash<Hash>] Keys can be `cpu_load` or `last_request`.
  #   Keys of those can be `timeout` and `last_request`
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   Terminal.set_terminal_idle_settings(user_token, access_token, 'b878c064-fc2b-4f14-81fa-ca10ac9385ff', 'pause', cpu_load: {timeout: 5600})
  #   # {"success" => true}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#set-terminal-idle-settings Terminal.com API docs
  # @see https://www.terminal.com/faq#idleSettings Terminal.com FAQ: Idle settings
  def self.set_terminal_idle_settings(user_token, access_token, container_key, action, triggers)
    call('/set_terminal_idle_settings',
      user_token: user_token,
      access_token: access_token,
      container_key: container_key,
      action: action,
      triggers: triggers)
  end

  # Get the {https://www.terminal.com/faq#idleSettings idle settings} for your terminal.
  #
  # @param (see .delete_terminal)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   container_key = 'b878c064-fc2b-4f14-81fa-ca10ac9385ff'
  #   Terminal.get_terminal_idle_settings(user_token, access_token, container_key)
  #   # {"success": true,
  #   #  "settings": {
  #   #    "action": "pause",
  #   #    "triggers": {
  #   #      "cpu_load": {
  #   #        "timeout": 3600,
  #   #        "threshold": 10
  #   #      },
  #   #      "last_request": {
  #   #        "timeout": 3600
  #   #      }
  #   #    }
  #   #  }
  #   # }
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#get-terminal-idle-settings Terminal.com API docs
  # @see https://www.terminal.com/faq#idleSettings Terminal.com FAQ: Idle settings
  def self.get_terminal_idle_settings(user_token, access_token, container_key)
    call('/get_terminal_idle_settings',
      user_token: user_token,
      access_token: access_token,
      container_key: container_key)
  end

  # @!endgroup
  # @!group MANAGE USAGE & CREDITS

  # Get a list of the types of Terminals that may be started,
  # and the specifications for each type (CPU, RAM, and pricing).
  #
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   Terminal.instance_types
  #   # {"instance_types" => {
  #   #   "micro" => {"cpu" => "2 (max)", "ram" => 256, "price" => 0.006},
  #   #   "mini" => {"cpu" => 50, "ram" => 800, "price" => 0.031},
  #   #   "small" => {"cpu" => 100, "ram" => 1600, "price" => 0.062},
  #   #   "medium" => {"cpu" => 200, "ram" => 3200, "price" => 0.124},
  #   #   "xlarge" => {"cpu" => 400, "ram" => 6400, "price" => 0.248},
  #   #   "2xlarge" => {"cpu" => 800, "ram" => 12800, "price" => 0.496},
  #   #   "4xlarge" => {"cpu" => 1600, "ram" => 25600, "price" => 0.992},
  #   #   "8xlarge" => {"cpu" => 3200, "ram" => 51200, "price" => 1.984}}}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#instance-types Terminal.com API docs
  def self.instance_types
    call('/instance_types', Hash.new)
  end

  # Get the hourly pricing for a Terminal instance of a given type.
  # If a instance is stopped, price will be zero.
  #
  # @param instance_type [String] desc.
  # @param status [String] Defaults to `running`. It doesn't make
  #   sense to set it to anything else: pause instances are not billed.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   Terminal.instance_price('micro')
  #   # {"price" => 0.006, "units" => "dollars per hour"}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#instance-price Terminal.com API docs
  def self.instance_price(instance_type, status = 'running')
    call('/instance_price', instance_type: instance_type, status: status)
  end

  # Get the current balance of your account.
  #
  # @param (see .list_terminals)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   Terminal.balance(user_token, access_token)
  #   # {"balance" => 675.879}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#balance Terminal.com API docs
  def self.balance(user_token, access_token)
    call('/balance', user_token: user_token, access_token: access_token)
  end

  # Get a history of credits added to your account balance.
  #
  # @param (see .list_terminals)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   Terminal.balance_added(user_token, access_token)
  #   # {"events" => [{"reason" => "Terminal.com sign up gift!", "amount" => 5, "time" => 1411652507924}], "total" => 5}
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#balance-added Terminal.com API docs
  def self.balance_added(user_token, access_token)
    call('/balance_added', user_token: user_token, access_token: access_token)
  end

  # Gift some of your credits to another user. Denominated in whole
  # integer US cents ($0.01). You may only gift credits if you have
  # previously purchased credits.
  #
  # @param (see .list_terminals)
  # @param email [String] User email.
  # @param cents [String] US cents.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#gift Terminal.com API docs
  def self.gift(user_token, access_token, email, cents)
    call('/gift',
      user_token: user_token,
      access_token: access_token,
      email: email,
      cents: cents)
  end

  # Get a history of charges to your account balance.
  #
  # @param (see .list_terminals)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#burn-history Terminal.com API docs
  def self.burn_history(user_token, access_token)
    call('/burn_history', user_token: user_token, access_token: access_token)
  end

  # Get a history of your Terminal usage.
  #
  # @param (see .list_terminals)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#terminal-usage-history Terminal.com API docs
  def self.terminal_usage_history(user_token, access_token)
    call('/terminal_usage_history', user_token: user_token, access_token: access_token)
  end

  # Get a summary of current active charges being billed to your account.
  #
  # @param (see .list_terminals)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#burn-state Terminal.com API docs
  def self.burn_state(user_token, access_token)
    call('/burn_state', user_token: user_token, access_token: access_token)
  end

  # Get a summary of the charges to your account, based on each
  # Terminal instance that you have provisioned. Note that inactive
  # and paused terminals do not incur charges.
  #
  # @param (see .list_terminals)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#burn-estimates Terminal.com API docs
  def self.burn_estimates(user_token, access_token)
    call('/burn_estimates', user_token: user_token, access_token: access_token)
  end

  # @!endgroup
  # @!group MANAGE SSH PUBLIC KEYS

  # Add an SSH public key to a given Terminal's root user.
  #
  # @param (see .delete_terminal)
  # @param publicKey [String] desc.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#add-authorized-key-to-terminal Terminal.com API docs
  # @see https://www.terminal.com/faq#ssh Using SSH to connect to your Terminals
  def self.add_authorized_key_to_terminal(user_token, access_token, container_key, publicKey)
    call('/add_authorized_key_to_terminal',
      user_token: user_token,
      access_token: access_token,
      container_key: container_key,
      publicKey: publicKey)
  end

  # Add an SSH public key to our SSH proxy.
  #
  # @param (see .list_terminals)
  # @param name [String] desc.
  # @param publicKey [String] desc.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#add-authorized-key-to-ssh-proxy Terminal.com API docs
  # @see https://www.terminal.com/faq#ssh Using SSH to connect to your Terminals
  def self.add_authorized_key_to_ssh_proxy(user_token, access_token, name, publicKey)
    call('/add_authorized_key_to_ssh_proxy',
      user_token: user_token,
      access_token: access_token,
      name: name,
      publicKey: publicKey)
  end

  # Delete an SSH public key from our SSH proxy.
  #
  # @param (see .list_terminals)
  # @param name         [String] TODO.
  # @param fingerprint  [String] TODO.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#del-authorized-key-from-ssh-proxy Terminal.com API docs
  # @see https://www.terminal.com/faq#ssh Using SSH to connect to your Terminals
  def self.del_authorized_key_from_ssh_proxy(user_token, access_token, name, fingerprint)
    call('/del_authorized_key_from_ssh_proxy',
      user_token: user_token,
      access_token: access_token,
      name: name,
      fingerprint: fingerprint)
  end

  # List the SSH public key on our SSH proxy.
  #
  # @param (see .list_terminals)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#get-authorized-keys-from-ssh-proxy Terminal.com API docs
  # @see https://www.terminal.com/faq#ssh Using SSH to connect to your Terminals
  def self.get_authorized_keys_from_ssh_proxy(user_token, access_token)
    call('/get_authorized_keys_from_ssh_proxy',
      user_token: user_token, access_token: access_token)
  end

  # @!endgroup
  # @!group TERMINAL PASSWORDS

  # Assign login/password to a Terminal/port combination.
  #
  # @param (see .remove_terminal_password)
  # @param password [String] An arbitrary password.
  # @param port [String] A number, 'IDE' or '*'.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.4
  # @see TODO: So far this is undocumented.
  def self.add_terminal_password(user_token, access_token, container_key, name, password, port)
    call('/add_terminal_password',
      user_token: user_token,
      access_token: access_token,
      container_key: container_key,
      name: name,
      password: password,
      port: port)
  end

  # List all the assigned Terminal logins and the ports they are assigned to.
  #
  # @param (see .delete_terminal)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.4
  # @see TODO: So far this is undocumented.
  def self.list_terminal_passwords(user_token, access_token, container_key)
    call('/list_terminal_passwords',
      user_token: user_token,
      access_token: access_token,
      container_key: container_key)
  end

  # Remove given login/password from a Terminal.
  #
  # @param (see .delete_terminal)
  # @param name [String] An arbitrary identifier.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.4
  # @see TODO: So far this is undocumented.
  def self.remove_terminal_password(user_token, access_token, container_key, name)
    call('/remove_terminal_password',
      user_token: user_token,
      access_token: access_token,
      container_key: container_key,
      name: name)
  end

  # @!endgroup
  # @!group OTHER

  # Get information about yourself!  If invalid access/user token
  # provided, returns null (but not an error).
  #
  # @param (see .list_terminals)
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @example
  #   Terminal.who_am_i(user_token, access_token)
  #   # {
  #   #   "user": {
  #   #     "name": "James C Russell",
  #   #     "username": "botanicus",
  #   #     "url": "https://twitter.com/botanicus",
  #   #     "company": "",
  #   #     "location": "London, United Kingdom",
  #   #     "balance": 675.879,
  #   #     "email": "james@101ideas.cz",
  #   #     "is_admin": false,
  #   #     "profile_image": "//www.gravatar.com/avatar/74c419a50563fa9e5044820c2697ffd6.jpg?s=400&d=mm"
  #   #   }
  #   # }
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#who-am-i Terminal.com API docs
  def self.who_am_i(user_token, access_token)
    call('/who_am_i', user_token: user_token, access_token: access_token)
  end

  # Get info and status of an API request.
  #
  # @param request_id [String] desc.
  # @return (see .get_snapshot)
  # @raise (see .get_snapshot)
  #
  # @since 0.0.1
  # @see https://www.terminal.com/api/docs#request-progress Terminal.com API docs
  def self.request_progress(request_id)
    call('/request_progress', request_id: request_id)
  end

  # @!endgroup
  # @!group IMPLEMENTATION

  # @api private
  def self.request
    @request ||= Net::HTTP.new('api.terminal.com')
  end

  # Make the HTTP call, retrieve and parse the JSON response.
  # Rewrite this method if you wish to use a different HTTP library.
  #
  # @raise [Terminal::NetworkError] Any network-layer error.
  #   It's important that plugins make sure to wrap their potential
  #   exceptions in Terminal::NetworkError for predictable behaviour.
  #
  # @api plugin
  # @since 0.0.1
  def self.call(path, data)
    path = "/#{API_VERSION}#{path}"
    json = data.to_json

    curl_debug(path, data.to_json)

    response = request.post(path, json, HEADERS)
    status   = response.code.to_i

    return parse_json(response.body) if status == 200

    raise "Unexpected status #{status}: #{response.inspect}"
  rescue SocketError => error
    raise NetworkError.new(error)
  end

  # @api private
  def self.curl_debug(path, json)
    return if ENV['DBG'].nil?

    headers = HEADERS.reduce(Array.new) do |buffer, (key, value)|
      buffer << "#{key}: #{value}"
    end.join(' ')

    STDERR.puts <<-EOF
curl -L -X POST -H '#{headers}' -d '#{json}' https://api.terminal.com#{path}
    EOF
  end

  # @api private
  def self.parse_json(json)
    convert_timestamps_to_time(JSON.parse(json))
  end

  # We are ignoring timestamps in arrays since there are none in the API.
  # Also, JSON document doesn't have to be an object, but in Terminal.com API,
  # they all are.
  # @api private
  # TODO: Test it.
  def self.convert_timestamps_to_time(hash)
    hash.each do |key, value|
      if value.is_a?(Hash)
        convert_timestamps_to_time(value)
      elsif value.is_a?(String) && value.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z$/)
        hash[key] = Time.parse(value)
      end
    end
  end

  # @api private
  def self.ensure_options_validity(options, *valid_keys)
    unrecognised_options = (options.keys - valid_keys)

    unless unrecognised_options.empty?
      raise ArgumentError.new("Unrecognised options: #{unrecognised_options.inspect[1..-2]}")
    end
  end

  # @api private
  def self.ensure_both_cpu_and_ram_are_provided(options)
    if (options[:cpu] && ! options[:ram]) || (options[:ram] && ! options[:cpu])
      raise ArgumentError.new('You have to specify both cpu and ram of the corresponding instance type as described at https://www.terminal.com/faq#instanceTypes')
    end
  end

  def self.ensure_options_present(options, *required_keys)
    required_keys.each do |key|
      unless options.has_key?(key)
        raise ArgumentError.new("Option #{key} is required, but is missing.")
      end
    end
  end

  # @!endgroup
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
HdfsConstants (Hadoop-Hdfs 0.21.0 API)
</TITLE>

<META NAME="date" CONTENT="2010-08-17">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.hadoop.hdfs.server.common

Interface HdfsConstants

@InterfaceAudience.Private
public interface HdfsConstants

Some handy internal HDFS constants

Nested Class Summary

static class
HdfsConstants.BlockUCState

          States, which a block can go through while it is under construction.

static class
HdfsConstants.NamenodeRole

          Defines the NameNode role.

static class
HdfsConstants.NodeType

          Type of the node

static class
HdfsConstants.ReplicaState

          Block replica states, which it can go through while being constructed.

static class
HdfsConstants.StartupOption

          Startup options

Field Summary

static int
READ_TIMEOUT

static int
READ_TIMEOUT_EXTENSION

static int
WRITE_TIMEOUT

static int
WRITE_TIMEOUT_EXTENSION

Field Detail

READ_TIMEOUT

static final int READ_TIMEOUT

See Also:
Constant Field Values

READ_TIMEOUT_EXTENSION

static final int READ_TIMEOUT_EXTENSION

See Also:
Constant Field Values

WRITE_TIMEOUT

static final int WRITE_TIMEOUT

See Also:
Constant Field Values

WRITE_TIMEOUT_EXTENSION

static final int WRITE_TIMEOUT_EXTENSION

See Also:
Constant Field Values

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2009 The Apache Software Foundation


text:
import re
import logging

from functools import partial

from py4jdbc.utils import CachedAttr
from py4jdbc.resultset import ResultSet, ColumnResultSet
from py4jdbc.gateway_process import GatewayProcess
from py4jdbc.exceptions import dbapi2 as dbapi2_exc
from py4jdbc.exceptions.py4j import reraise_jvm_exception

paramstyle = 'qmark'

# DB-API 2.0 Module Interface connect constructor
def connect(jdbc_url, user=None, password=None, gateway=None, autocommit=None):
    return Connection(jdbc_url, user, password, gateway, autocommit=None)

class _ExceptionMixin:
    '''Exposes dbapi2 exceptions classes as class-level attributes.
    '''
    Error = dbapi2_exc.Error
    Warning = dbapi2_exc.Warning
    InterfaceError = dbapi2_exc.InterfaceError
    DatabaseError = dbapi2_exc.DatabaseError
    InternalError = dbapi2_exc.InternalError
    OperationalError = dbapi2_exc.OperationalError
    ProgrammingError = dbapi2_exc.ProgrammingError
    IntegrityError = dbapi2_exc.IntegrityError
    DataError = dbapi2_exc.DataError
    NotSupportedError = dbapi2_exc.NotSupportedError

class _JdbcPropertyAlias:

    def __init__(self, property_name):
        self.name = property_name

    def __get__(self, inst, Cls):
        return inst.get_property(self.name)

    def __set__(self, inst, value):
        inst.set_property(self.name, value)

# DB-API 2.0 Connection Object
class Connection(_ExceptionMixin):

    autocommit = _JdbcPropertyAlias('AutoCommit')

    def __init__(self, jdbc_url, user=None, password=None, gateway=None, autocommit=None):
        self._gateway_arg = gateway
        self._jdbc_url = jdbc_url
        self._user = user
        self._password = password
        self._closed = False
        self._logger = logging.getLogger('py4jdbc')
        self._autostarted_gateway = False

        # Set autocommit
        if autocommit is not None:
            self.autocommit = autocommit

    def __enter__(self):
        if not self._gateway.is_running:
            self._gateway.run()
            self._autostarted_gateway = True
        return self

    def __exit__(self, *args):
        if not self._closed:
            self.close()
        # If this connection started a gateway server, shut it down now.
        if self._gateway.is_running and self._autostarted_gateway:
            msg = "Shutting down GatewayProcess auto-started by connection %r"
            self._logger.info(msg, self)
            self._gateway.shutdown()
        else:
            msg = ("GatewayProcess wasn't auto-started by connection. "
                   "Leaving it up.")
            self._logger.info(msg)

    # -----------------------------------------------------------------------
    # Py4j accessors.
    # -----------------------------------------------------------------------
    @property
    def _entry_point(self):
        return self._gateway.entry_point

    _ep = _entry_point

    @CachedAttr
    def _gateway_process(self):
        proc = GatewayProcess(require_ctx_manager=False)
        return proc

    @CachedAttr
    def _gateway(self):
        gw = self._gateway_arg
        if gw is not None:
            # If a gateway process was passed in, get the actual gateway.
            if isinstance(gw, GatewayProcess):
                gw = self._gateway_arg.gateway
            self._gateway = gw
            return gw
        return self._gateway_process.gateway

    # -----------------------------------------------------------------------
    # Java connection accessors.
    # -----------------------------------------------------------------------
    def get_property(self, name: str):
        method_name = 'get' + name
        if method_name in dir(self._jconn):
            method = getattr(self._jconn, method_name)
        else:
            method = partial(self._jconn.getProperty, name)
        with reraise_jvm_exception(self._gateway):
            return method()

    def set_property(self, name: str, value: str):
        method_name = 'set' + name
        if method_name in dir(self._jconn):
            method = getattr(self._jconn, method_name)
        else:
            method = partial(self._jconn.setProperty, name)
        with reraise_jvm_exception(self._gateway):
            return method(value)

    @CachedAttr
    def _py4jdbc_connection(self):
        self._logger.debug('Connecting as: %r', self._user, self._jdbc_url)
        return self._ep.getConnection(self._jdbc_url, self._user, self._password)

    @property
    def _conn(self):
        return self._py4jdbc_connection

    @CachedAttr
    def _jdbc_connection(self):
        return self._py4jdbc_connection.getJdbcConnection()

    @property
    def _jconn(self):
        return self._jdbc_connection

    def close(self):
        if self._closed:
            raise self.Error("Connection is already closed.")
        with reraise_jvm_exception(self._gateway):
            self._jconn.close()
            self._closed = True

    def commit(self):
        with reraise_jvm_exception(self._gateway):
            self._jconn.commit()

    def rollback(self):
        with reraise_jvm_exception(self._gateway):
            self._jconn.rollback()

    def cursor(self):
        return Cursor(self)

    # ------------------------------------------------------------------------
    # Introspection
    # ------------------------------------------------------------------------
    @CachedAttr
    def _metadata(self):
        return self._jdbc_connection.getMetaData()

    def get_tables(self, catalog=None, schema=None, table='%'):
        rs = self._metadata.getTables(catalog, schema, table, None)
        rs = self._ep.mkPyResultSet(rs)
        return ResultSet(rs, gateway=self._gateway, case_insensitive=True)

    def get_columns(self, catalog=None, schema=None, table='%', column=None):
        rs = self._metadata.getColumns(catalog, schema, table, column)
        rs = self._ep.mkPyResultSet(rs)
        return ColumnResultSet(rs, gateway=self._gateway)

    def get_primary_keys(self, catalog=None, schema=None, table='%', column=None):
        rs = self._metadata.getPrimaryKeys(catalog, schema, table)
        rs = self._ep.mkPyResultSet(rs)
        return ColumnResultSet(rs, gateway=self._gateway)

    def get_imported_keys(self, catalog=None, schema=None, table='%', column=None):
        rs = self._metadata.getImportedKeys(catalog, schema, table)
        rs = self._ep.mkPyResultSet(rs)
        return ColumnResultSet(rs, gateway=self._gateway)

    def get_exported_keys(self, catalog=None, schema=None, table='%', column=None):
        rs = self._metadata.getExportedKeys(catalog, schema, table)
        rs = self._ep.mkPyResultSet(rs)
        return ColumnResultSet(rs, gateway=self._gateway)

    def get_privileges(self, catalog=None, schema=None, table='%', column=None):
        rs = self._metadata.getTablePrivileges(catalog, schema, table)
        rs = self._ep.mkPyResultSet(rs)
        return ColumnResultSet(rs, gateway=self._gateway)

# DB-API 2.0 Cursor Object
class Cursor(_ExceptionMixin):

    def __init__(self, connection):
        self.connection = connection
        self._reset()
        self._logger = logging.getLogger('py4jdbc')

    def _reset(self):
        self._closed = False
        self._rs = None
        self._description = None

    # ------------------------------------------------------------------------
    # Shortcuts for reaching java objects.
    # ------------------------------------------------------------------------
    @property
    def _gateway(self):
        return self.connection._gateway

    @property
    def _entrypoint(self):
        return self.connection._entry_point

    _ep = _entrypoint

    @property
    def _jdbc_connection(self):
        return self.connection._jdbc_connection

    _jconn = _jdbc_connection

    # ------------------------------------------------------------------------
    # Actual dbapi 2.0 methods.
    # ------------------------------------------------------------------------
    @property
    def description(self):
        if self._description is None:
            self._description = self._rs.description()
        return self._description

    def close(self):
        if self._closed:
            raise self.Error("Connection is already closed.")
        self._logger.info('Closing cursor')
        self._close_last()
        self._closed = True

    def _close_last(self):
        if self._rs is not None:
            with reraise_jvm_exception(self._gateway):
                self._rs.close()

    def execute(self, operation, parameters=None):
        if self._closed:
            raise self.Error("Connection is closed.")
        with reraise_jvm_exception(self._gateway):
            if parameters is None:
                rs = self.connection._conn.execute(operation)
            else:
                rs = self.connection._conn.execute(operation, parameters)
            if rs is None:
                del self._rs
                return
            self._rs = ResultSet(rs, gateway=self._gateway)
            return self._rs

    def executemany(self, operation, parameter_seq):
        if self._closed:
            raise self.Error("Connection is closed.")
        with reraise_jvm_exception(self._gateway):
            rs = self.connection._conn.executeMany(operation, parameter_seq)
            if rs is None:
                del self._rs
                return
            self._rs = ResultSet(rs, gateway=self._gateway)
            return self._rs

    def fetchone(self):
        if self._closed:
            raise self.Error("Connection is closed.")
        return self._rs.fetchone()

    def fetchmany(self, size=None):
        if self._closed:
            raise self.Error("Connection is closed.")
        return self._rs.fetchmany(size)

    def fetchall(self):
        if self._closed:
            raise self.Error("Connection is closed.")
        return self._rs.fetchall()