text:
package io.clickhandler.web.materialUiGwt.client.styles.theme;

import jsinterop.annotations.JsType;

@JsType(isNative = true)
public class ButtonMuiTheme {
    public int height;
    public int minWidth;
    public int iconButtonSize;
}

redpajama_set_name: RedPajamaGithub


text:
package ixias.persistence.model

import scala.reflect.ClassTag
import scala.collection.immutable.ListMap

/** The data converter. */
trait Converter[-A, B] {
  def convert(o: A): B
}

/** The factory object for converter. */
object Converter extends TableDefaultConverter {
  def apply[A, B](f: A => B): Converter[A, B] = new Converter[A, B] {
    def convert(o: A): B = f(o)
  }
}

/** Default Serializers. */
trait TableDefaultConverter {
  /** Convert to Same Type. */
  implicit def SameTypeConv[A <: AnyVal]: Converter[A, A] = new Converter[A, A] {
    def convert(v: A) = v
  }

  /** Serializer for Option. */
  implicit def OptionConv[A, B](implicit fmt: Converter[A, B]): Converter[Option[A], Option[B]] =
    new Converter[Option[A], Option[B]] {
      def convert(v: Option[A]) = v match {
        case Some(value) => Some(fmt.convert(value))
        case None        => None
      }
    }

  /** Serializer for Seq[T] types. */
  implicit def SeqConv[A: ClassTag, B: ClassTag](implicit fmt: Converter[A, B]): Converter[Seq[A], Seq[B]] =
    new Converter[Seq[A], Seq[B]] {
      def convert(itr: Seq[A]) = itr.foldLeft(Seq.empty[B]){
        (prev, v) => prev :+ fmt.convert(v)
      }
    }

  /**
   * Serializer for Map[String, T] types.
   */
  implicit def MapConv[A, B](implicit fmt: Converter[A, B]): Converter[Map[String, A], Map[String, B]] =
    new Converter[Map[String, A], Map[String, B]] {
      def convert(itr: Map[String, A]) = itr.foldLeft(ListMap.empty[String, B]){
        case (prev, (k, v)) => prev + (k -> fmt.convert(v))
      }
    }
}


text:
__author__ = 'helios'

'''
    该类作为用户系统帮助工具
'''

import uuid, time
from Gyrfalcon.tools.database.DBSession import DBSession

class GFUserSystem:

    session = DBSession()

    def __init__(self):
        self.tableName = "Gyrfalcon_usersystem"

    #单例设计模式
    def __new__(cls, *args, **kwargs):
        if not hasattr(cls,'_inst'):
            cls._inst=super(GFUserSystem,cls).__new__(cls,*args,**kwargs)
        return cls._inst

    def validateInfo(self, condition):

        queryList = ["userid"]
        rows = self.session.get(self.tableName, queryList, condition)
        if len(rows) > 0:
            return True
        else:
            return False

    def validateUsername(self,username):

        condition = "username='{username}'".format(username=username)
        return self.validateInfo(condition)

    def validateEmail(self,email):

        condition = "email='{email}'".format(email=email)
        return self.validateInfo(condition)


text:
namespace webdriver {

WindowUtilities::WindowUtilities() {
}

WindowUtilities::~WindowUtilities() {
}

void WindowUtilities::Wait(long wait_in_milliseconds) {
  clock_t end = clock() + wait_in_milliseconds;
  do {
    MSG msg;
    if (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
      ::TranslateMessage(&msg);
      ::DispatchMessage(&msg);
    }
    ::Sleep(0);
  } while (clock() < end);
}

void WindowUtilities::WaitWithoutMsgPump(long wait_in_milliseconds) {
  ::Sleep(wait_in_milliseconds);
}

HWND WindowUtilities::GetChildWindow(HWND parent_window_handle,
                                     std::wstring window_class) {
  std::vector<wchar_t> class_name_buffer(window_class.size() + 1);
  HWND hwndtmp = GetWindow(parent_window_handle, GW_CHILD);
  while (hwndtmp != NULL) {
    ::GetClassName(hwndtmp,
                   &class_name_buffer[0],
                   static_cast<int>(class_name_buffer.size()));
    std::wstring actual_class = &class_name_buffer[0];
    if (window_class == actual_class) {
      return hwndtmp;
    }
    hwndtmp = GetWindow(hwndtmp, GW_HWNDNEXT);
  }
  return NULL;
}

std::string WindowUtilities::GetWindowCaption(HWND window_handle) {
  std::wstring window_caption = L"";
  std::vector<wchar_t> buffer(256);
  int success = ::GetWindowText(window_handle, &buffer[0], 256);
  if (success > 0) {
    window_caption = &buffer[0];
  }
  return StringUtilities::ToString(window_caption);
}

} // namespace webdriver


text:
@interface JWEmojisKeyBoards()
@property (nonatomic,assign)NSInteger keyboardsStates;

@end

@implementation JWEmojisKeyBoards

- (instancetype)initWithCoder:(NSCoder *)coder{
    self = [super initWithCoder:coder];
    if (self) {
        [self getEmotionArr];
        self.oneLengthStrArr = @[@"☺",@"✨",@"✊",@"✌",@"✋",@"☝",@"❤"];
        self.keyboardsStates = 1;
    }
    return self;
}

- (void)awakeFromNib{
    [super awakeFromNib];
    self.frame = CGRectMake(0.f, 0.f, kScreen_Width, 216.f);
    [self makeKeyboards];
    self.pageControl.numberOfPages = [self.pageNumberArr[0] integerValue];
}

- (void)getEmotionArr{
    self.dataArr = [NSMutableArray arrayWithCapacity:0];
    self.keyboardTypeArr = [NSMutableArray arrayWithArray:@[@"🙂",@"\\(^o^)/"]];
    self.pageStateArr = [NSMutableArray arrayWithCapacity:0];
    self.pageNumberArr = [NSMutableArray arrayWithCapacity:0];
    self.keyboardArr = [NSMutableArray arrayWithCapacity:0];

    [self dataArrSet];
    [self pageStateArrSet];
    [self keyboardArrSet];
}
#pragma mark - Arr Set
- (void)dataArrSet{
    NSMutableDictionary * faceEmotionDic = [[NSMutableDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"EmojisList" ofType:@"plist"]];
    [self.dataArr addObject:[NSMutableArray arrayWithArray:faceEmotionDic[@"People"]]];

    NSMutableArray * textEmotionArr = [[NSMutableArray alloc] initWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"EmotionTextKeys" ofType:@"plist"]];
    [self.dataArr addObject:textEmotionArr];
}

- (void)pageStateArrSet{
    for (int i = 0; i<self.keyboardTypeArr.count; i++) {
        [self.pageStateArr addObject:@(0)];
    }
}

- (void)keyboardArrSet{
    NSMutableArray * dataArrTemp = [self.dataArr mutableCopy];
    __block NSArray * widthArr = @[@(44),@(80)];
    [dataArrTemp enumerateObjectsUsingBlock:^(NSMutableArray  * _Nonnull keyboardDataArr, NSUInteger idx, BOOL * _Nonnull stop) {
        [self.dataArr replaceObjectAtIndex:idx withObject:[self keyboardArrSetWithWidth:[widthArr[idx] floatValue] withArr:keyboardDataArr withIdx:idx]];
    }];
}
- (NSMutableArray *)keyboardArrSetWithWidth:(CGFloat)width withArr:(NSMutableArray *)arr withIdx:(NSInteger)idx{
    NSInteger oneLineMaxNumber = kScreen_Width/width;
    NSInteger onePageMaxNumber = oneLineMaxNumber * 3 - 1;
    NSInteger pageNumber = arr.count / onePageMaxNumber + 1;
    [self.pageNumberArr addObject:@(pageNumber)];

    UIScrollView * keyboardsScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0.f, 28.f, kScreen_Width, 132.f)];
    keyboardsScrollView.bounces = NO;
    keyboardsScrollView.showsVerticalScrollIndicator = NO;
    keyboardsScrollView.showsHorizontalScrollIndicator = NO;
    keyboardsScrollView.delegate = self;
    keyboardsScrollView.pagingEnabled = YES;
    keyboardsScrollView.contentSize = CGSizeMake(kScreen_Width * pageNumber, 1.f);

    keyboardsScrollView.hidden = idx==0?NO:YES;

    __block NSMutableArray * emojionArr = [NSMutableArray arrayWithCapacity:0];
    [arr enumerateObjectsUsingBlock:^(NSString * _Nonnull str, NSUInteger idx, BOOL * _Nonnull stop) {
        if (idx != 0&&(idx%onePageMaxNumber == 0))[emojionArr addObject:DeleteEmojionStr];
        [emojionArr addObject:str];
        if (idx == (arr.count - 1))[emojionArr addObject:DeleteEmojionStr];
    }];

    CGFloat btnWidth = width;
    CGFloat btnEndge = (kScreen_Width - btnWidth * oneLineMaxNumber)/2;
    CGFloat btnHeight = 44.f;
    __block CGFloat btnY = 0.f;
    __block CGFloat btnX = btnEndge;

    __block NSInteger page = 0;
    [emojionArr enumerateObjectsUsingBlock:^(NSString * _Nonnull str, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton * keyboardBtn = [[UIButton alloc]initWithFrame:CGRectMake(btnX, btnY, btnWidth, btnHeight)];
        [keyboardBtn setTitleColor:[UIColor colorWithHexString:@"#acacac"] forState:UIControlStateNormal];
        if ([str isEqualToString:DeleteEmojionStr]) {//删除键,且是最后一个
            [keyboardBtn setImage:[UIImage imageNamed:@"YWfaceDelete"] forState:UIControlStateNormal];
            [keyboardBtn setImage:[UIImage imageNamed:@"YWfaceDelete"] forState:UIControlStateSelected];
            [keyboardBtn addTarget:self action:@selector(deleteStrAction) forControlEvents:UIControlEventTouchUpInside];
            page++;
            btnX = page*kScreen_Width + btnEndge;
            btnY = 0.f;
        }else{
            [keyboardBtn setTitle:str forState:UIControlStateNormal];
            [keyboardBtn setTitle:str forState:UIControlStateSelected];
            [keyboardBtn addTarget:self action:@selector(addStrAction:) forControlEvents:UIControlEventTouchUpInside];

            NSInteger lineIdx = (idx+1)%oneLineMaxNumber;
            if (lineIdx == 0) {
                btnX = page*kScreen_Width + btnEndge;
                btnY += 44.f;
            }else{
                btnX += btnWidth;
            }
        }
        [keyboardsScrollView addSubview:keyboardBtn];
    }];

    [self addSubview:keyboardsScrollView];
    [self.keyboardArr addObject:keyboardsScrollView];

    return emojionArr;
}

#pragma mark - UI
- (void)makeKeyboards{
    CGFloat typeBtnWidth = (kScreen_Width - 60.f)/2;
    for (int i = 1; i<=self.keyboardTypeArr.count; i++) {
        NSString * keyboardsType = self.keyboardTypeArr[i-1];
        UIButton * typeBtn = [[UIButton alloc]initWithFrame:CGRectMake((i-1)*typeBtnWidth, 0.f, typeBtnWidth, 44.f)];
        typeBtn.tag = i;
        [typeBtn setTitle:keyboardsType forState:UIControlStateNormal];
        [typeBtn setTitle:keyboardsType forState:UIControlStateSelected];
        typeBtn.backgroundColor = [UIColor colorWithHexString:self.keyboardsStates==i?@"#acacac":@"#e1e1e1"];
        [typeBtn setTitleColor:[UIColor colorWithHexString:@"#acacac"] forState:UIControlStateNormal];
        [typeBtn addTarget:self action:@selector(typeBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.keyboardsTypeScrollView addSubview:typeBtn];
    }
}

- (void)typeBtnAction:(UIButton *)sender{
    if (self.keyboardsStates == sender.tag)return;
    UIButton * lastTypeBtn = [self.keyboardsTypeScrollView viewWithTag:self.keyboardsStates];
    [self.pageStateArr replaceObjectAtIndex:(self.keyboardsStates - 1) withObject:@(self.pageControl.currentPage)];
    [lastTypeBtn setTitleColor:[UIColor colorWithHexString:@"#acacac"] forState:UIControlStateNormal];
    lastTypeBtn.backgroundColor = [UIColor colorWithHexString:@"#e1e1e1"];

    sender.backgroundColor = [UIColor colorWithHexString:@"#acacac"];
    [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.keyboardsStates = sender.tag;
    self.pageControl.currentPage = 0;
    self.pageControl.numberOfPages = [self.pageNumberArr[self.keyboardsStates-1] integerValue];
    self.pageControl.currentPage = [self.pageStateArr[self.keyboardsStates-1] integerValue];

    [self.keyboardArr enumerateObjectsUsingBlock:^(UIScrollView * _Nonnull keyboardScrollView, NSUInteger idx, BOOL * _Nonnull stop) {
        keyboardScrollView.hidden = idx == (sender.tag-1)?NO:YES;
    }];
}

- (IBAction)sendBtnAction:(id)sender {
    self.sendBlock();
}

- (void)deleteStrAction{
    self.deleteStrBlock();
}
- (void)addStrAction:(UIButton *)sender{
    self.addStrBlock(sender.titleLabel.text);
}

- (BOOL)isOneLengthEmojionithStr:(NSString *)str{
    __block BOOL isOneLengthEmojion = NO;
    for (int i = 0; i<self.oneLengthStrArr.count; i++) {
        if ([str isEqualToString:self.oneLengthStrArr[i]]) {
            isOneLengthEmojion = YES;
            break;
        }
    }
    return !isOneLengthEmojion;
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSInteger pageNumber = scrollView.contentOffset.x/kScreen_Width;
    if (pageNumber != self.pageControl.currentPage)self.pageControl.currentPage = pageNumber;
}

@end


text:
"""Companion to nose.plugins.cover. Enable by adding --with-xcoverage to your
arguments. A Cobertura-style XML file, honoring the options you pass to
--with-coverage, will be generated in coverage.xml

setup(
    name='nosexcover',
    version='1.0.4',
    description='Extends nose.plugins.cover to add Cobertura-style XML reports',
    long_description=desc,
    author='Chris Heisel',
    author_email='chris@heisel.org',
    url='http://github.com/cmheisel/nose-xcover/',
    license='BSD',
    packages=find_packages(),
    include_package_data=True,
    zip_safe=False,
    install_requires=['nose', 'coverage<3.4'])

"""

import logging
import sys
from nose.plugins import cover, Plugin
log = logging.getLogger('nose.plugins.xcover')

class XCoverage(cover.Coverage):
    """
Add Cobertura-style XML coverage reports to the built-in nose.plugins.cover plugin.
"""

    def options(self, parser, env):
        """
Add options to command line.
"""
        Plugin.options(self, parser, env)
        parser.add_option('--xcoverage-file', action='store',
                          default=env.get('NOSE_XCOVER_FILE', 'coverage.xml'),
                          dest='xcoverage_file',
                          metavar="FILE",
                          help='Path to xml file to store the coverage report in. '
                          'Default is coverage.xml in the working directory. '
                          '[NOSE_XCOVERAGE_FILE]')

    def configure(self, options, config):
        super(XCoverage, self).configure(options, config)
        self.xcoverageFile = options.xcoverage_file

    def report(self, stream):
        """
Output code coverage report.
"""
        import coverage
        coverage.stop()
        modules = [ module
                    for name, module in sys.modules.items()
                    if self.wantModuleCoverage(name, module) ]
        log.debug("Coverage report will cover modules: %s", modules)
        morfs = [ m.__file__ for m in modules if hasattr(m, '__file__') ]
        coverage._the_coverage.xml_report(morfs, outfile=self.xcoverageFile)


text:
package com.idacchi.cloudautomator;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

/**
 * Cloud Automator HTTP Kicker GUI.
 * @author yasuhiko
 *
 */
public class CloudAutomatorHTTPSwing extends JFrame {

	/**
	 *
	 */
	private static final long serialVersionUID = -3780192956158767701L;
	private JPanel contentPane;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					CloudAutomatorHTTPSwing frame = new CloudAutomatorHTTPSwing();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public CloudAutomatorHTTPSwing() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);

		JButton btnNewButton = new JButton("HTTP Trigger Kick!");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					CloudAutomatorHTTP.Kick();
				} catch (Exception e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		contentPane.add(btnNewButton, BorderLayout.CENTER);
	}

}


text:
/*
	This program and the accompanying materials are made available under the
	terms of the MIT license (X11 license) which accompanies this distribution.

	Author: Christoff Bürger
*/

package jastaddc.symbols;

import beaver.Scanner;

/**
 * CUnknownTokenException's are thrown, if while lexing unknown lexems are
 * encountered. It's important to distinguish this type of error while parsing
 * from others, because it's the only possible lexical error caused by faulty
 * source code. Other errors during the lexical analyze are technical based,
 * like trying to read not existing source code files, not being allowed to
 * read a source code file, buffer problem etc. Exceptions like this should
 * never be instances of CUnknownTokenException, so this class is final.

 *

 * Technical based exceptions are represented by {@link java.io.IOException}s.
 */
final public class CUnknownTokenException extends Scanner.Exception {
	final public static long serialVersionUID = 1L;

	public String unknownLexem;

	public CUnknownTokenException(int line, int column, String unknownLexem, String message) {
		super(line, column, message);
		this.unknownLexem = unknownLexem;
	}

	public CUnknownTokenException(int line, int column, String unknownLexem) {
		super(line, column, "Unknown lexical element ["+ unknownLexem +"].");
		this.unknownLexem = unknownLexem;
	}
}


text:
import stream = module("stream");
import http = module("http");
import zlib = module("zlib");
import url = module("url");
import fs = module("fs");

// Import nodejs external modules.
var async = <Async>require("async");

// Represents an asynchronous HTTP request.
class AsyncHTTPRequestTask
{
    private _error: Error;                      // Error object, if any.
    private _total: number;                     // Total number of bytes to receive.
    private _result: string;                    // Result data, if any.
    private _progress: number;                  // Current progress.
    private _isSuccess: bool;                   // Has the task completed successfully?
    private _requestUrl: string;                // The request url.

    //=======================================================================
    //     Properties
    //=======================================================================

    // Gets the error object, if any.
    public get Error(): Error { return this._error; }
    // Gets the total number of bytes to receive.
    public get Total(): number { return this._total; }
    // Gets the HTTP result data, if any.
    public get Result(): string { return this._result; }
    // Gets the current number of bytes received.
    public get Progress(): number { return this._progress; }
    // Gets whether the task has completed successfully.
    public get IsSuccess(): bool { return this._isSuccess; }
    // Gets the request url string.
    public get RequestUrl(): string { return this._requestUrl; }

    //=======================================================================
    //     Constructors
    //=======================================================================

    // Constructor.
    constructor(requestUrl: string)
    {
        this._total = 0;
        this._error = null;
        this._result = null;
        this._progress = 0;
        this._isSuccess = false;
        this._requestUrl = requestUrl;
    }

    //=======================================================================
    //     Methods
    //=======================================================================

    // Returns a task to pass async.* functions.
    public GetAsyncTask()
    {
        // Anonymous function closure for callback.
        var This = this;
        return (cllbck: AsyncCallback) =>
        {
            This.InternalExecute(cllbck);
        };
    }

    //=======================================================================
    //     Non Public
    //=======================================================================

    // Executes the task asynchronously.
    private InternalExecute(callback: AsyncCallback)
    {
        // For closure of callbacks.
        var This = this;

        // Do the HTTP get.
        AsyncHTTPRequestTask.InternalHttpGet(this._requestUrl,
            (response: http.ClientResponse, responseUrl: url.Url) =>
            {
                //console.log(response.headers);

                // Get encoding.
                var encoding = response.headers['content-encoding'];
                if (!encoding && /\.gz(ip)?$/i.test(responseUrl.pathname))
                    encoding = "gzip";
                //console.log(encoding);

                // Unzip content if necessary.
                var output = <stream.ReadableStream>null;
                switch (encoding)
                {
                    case 'gzip':
                        var gzip = (<any>zlib).createGunzip();
                        response.pipe(gzip);
                        output = gzip;
                        break;
                    case 'deflate':
                        var inflate = (<any>zlib).createInflate();
                        response.pipe(inflate);
                        output = inflate;
                        break;
                    default:
                        output = response;
                        break;
                }

                // Prepare for download.
                This._result = "";
                This._total = parseInt(response.headers["content-length"]);
                This._progress = 0;

                // Register "data" event.
                output.on("data", function (chunk: any)
                {
                    // Add data that was read.
                    This._progress += chunk.length;
                    This._result += chunk.toString("utf-8");
                });

                // Register "end" event.
                output.on("end", function ()
                {
                    // We have successfully downloaded all the content.
                    This._isSuccess = true;
                    callback(null, This);
                });

                // Register "close" event.
                output.on("close", function ()
                {
                    // Error if it occurs before "end" event.
                    if (!This._isSuccess)
                    {
                        // Notify.
                        This._error = new Error("the underlying connection was terminated before all data was sent");
                        callback(null, This);
                    }
                });
            },
            (error: Error) =>
            {
                // Notify error.
                This._isSuccess = false;
                This._error = error;
                callback(null, This);
            });
    }

    // Does a direct HTTP GET at specified url by following any redirection (warning: redirection loops will cause a stack overflow).
    private static InternalHttpGet(requestUrl: string, success: (response: http.ClientResponse, responseUrl: url.Url) => void , error: (error: Error) => void )
    {
        //console.log("HTTP GET %s", requestUrl);

        // Parse the request url.
        var parsedRequestUrl = url.parse(requestUrl);

        // Build HTTP request options by accepting encodings that blocklist providers use.
        var options = <any>parsedRequestUrl;
        options.headers =
        {
            'accept': '*/*',
            'accept-encoding': 'gzip,deflate',
            'accept-charset': 'utf-8'
        };

        // Do the HTTP GET.
        var request = http.get(options, function (response: http.ClientResponse) =>
        {
            //console.log("HTTP %d %s", response.statusCode, requestUrl);

            // If it's a redirection...
            if (response.statusCode > 300 && response.statusCode < 400 && response.headers.location)
            {
                // Parse redirection url.
                var parsedRedirectUrl = url.parse(response.headers.location);

                // Set hostname if it's a relative redirection.
                if (!parsedRedirectUrl.hostname)
                    parsedRedirectUrl.hostname = parsedRequestUrl.hostname;

                // Follow redirection.
                InternalHttpGet(url.format(parsedRedirectUrl), success, error);
            }
                // If it's a 200 OK...
            else if (response.statusCode == 200)
            {
                // Call success callback.
                success(response, parsedRequestUrl);
            }
            else
            {
                // Call error callback.
                error(new Error("HTTP request failed with " + response.statusCode + " response code"));
            }
        });

        // Register "error" event.
        request.on("error", error);
    }
}

// Represents a class for an HTTP server that merges a set of blocklists on request.
export class MergedBlocklistServer
{
    //=======================================================================
    //     Methods
    //=======================================================================

    // Starts the server on specified port.
    public Listen(hostname: string, port: number)
    {
        var This = this;

        // Create HTTP server.
        var server = http.createServer((request: http.ServerRequest, response: http.ServerResponse) =>
        {
            // Process the request.
            This.ProcessRequest(request, response);
        });

        // Listen.
        server.listen(port, hostname);
    }

    //=======================================================================
    //     Non Public
    //=======================================================================

    // Processes specified request.
    private ProcessRequest(request: http.ServerRequest, response: http.ServerResponse)
    {
        // Log it.
        console.info("Got HTTP request for %s", request.url);

        // Parse request url.
        var requestUrl = url.parse(request.url);
        if (requestUrl.pathname && !requestUrl.query && requestUrl.pathname != '/')
        {
            // Build local file path.
            var listFilePath = __dirname + "/../lists" + requestUrl.pathname;

            // Make sure it exists.
            if (!fs.existsSync(listFilePath))
            {
                // Respond with 404.
                response.writeHead(404,
                {
                    "Content-Type": "text/plain"
                });
                response.end("404 Not Found\nSpecified file could not be found: " + listFilePath + "\n");
                return;
            }

            // Read file content.
            var listText = fs.readFileSync(listFilePath, "utf-8");
            if (listText.charAt(0) === '\uFEFF') listText = listText.substr(1);

            // Split into lines, ignore empty lines and lines starting with #.
            var listUrls = listText.split("\n").map((value: string) => value.trim()).filter((value: string) => !value.match(/^#.*$/) && !value.match(/^\w*$/));

            // Write OK.
            response.writeHead(200, {
                "Content-Type": "text/plain",
                "Content-Encoding": "utf-8"
            });

            // Merge them asynchronously.
            MergedBlocklistServer.MergeListsAsync(listUrls, (mergedData: string, failedUrls: string[]) =>
            {
                // Log failures.
                for (var i = 0; i < failedUrls.length; i++)
                    console.error("ERROR: could not fetch data from %s", failedUrls[i]);

                // Write result.
                response.end(mergedData, "utf-8");
            });
        }
        else
        {
            // Respond with 404.
            response.writeHead(404, {
                "Content-Type": "text/plain"
            });
            response.end("404 Not Found\n");
        }
    }

    // Merges the lists downloaded from specified urls asynchronously.
    private static MergeListsAsync(listUrls: string[], completionCallback: (mergedData: string, failedUrls: string[]) => void )
    {
        var tasks = [];

        // Build the list of tasks.
        for (var i = 0; i < listUrls.length; i++)
            tasks.push(new AsyncHTTPRequestTask(listUrls[i] + "&fileformat=p2p&archiveformat=gz").GetAsyncTask());

        // Call asynchronously.
        async.parallel(tasks, (error: string, results: AsyncHTTPRequestTask[]) =>
        {
            var failedUrls = <string[]>[];
            var mergedResult = "";

            // Write failures as comments at the beginning of the file.
            for (var i = 0; i < results.length; i++)
                if (!results[i].IsSuccess)
                {
                    failedUrls.push(results[i].RequestUrl);
                    mergedResult += "# failed to load url: " + results[i].RequestUrl + "\n";
                }

            // Write data.
            for (var i = 0; i < results.length; i++)
                if (results[i].IsSuccess)
                {
                    mergedResult += "# list from " + results[i].RequestUrl + "\n";
                    mergedResult += results[i].Result + "\n";
                }

            // Call callback.
            completionCallback(mergedResult, failedUrls);
        });
    }
}

// Requires.
var argv = require('optimist').argv;

// Show help if necessary.
if (argv.h || argv.help)
{
    console.log([
		"usage: blocklist-merger-server [options]",
		"",
		"options:",
		"  --port [number]     Port to use (default is 1337)",
		"  --host [hostname]   Address to use (default is localhost)",
		"  --help              Print this list and exit.",
	].join('\n'));
	process.exit();
}

// Parse args.
var port = argv.port ? argv.port : (process.env.PORT ? process.env.PORT : 1337);
var host = argv.host ? argv.host : (process.env.IP ? process.env.IP : "localhost");

// Create the web server.
var server = new MergedBlocklistServer();
server.Listen(host, port);
console.log("Server is listening on %s:%d...", host, port);

if (process.platform !== 'win32')
{
	process.on('SIGINT', function ()
	{
		console.log("Server stopped.");
		process.exit();
	});
}


text:
package org.apache.samza.webapp;

import com.google.common.collect.ImmutableMap;
import java.net.URL;
import java.util.Collections;
import org.apache.samza.container.LocalityManager;
import org.apache.samza.coordinator.server.HttpServer;
import org.apache.samza.coordinator.server.LocalityServlet;
import org.apache.samza.job.model.ProcessorLocality;
import org.apache.samza.job.model.LocalityModel;
import org.apache.samza.serializers.model.SamzaObjectMapper;
import org.apache.samza.util.ExponentialSleepStrategy;
import org.apache.samza.util.HttpUtil;
import org.codehaus.jackson.map.ObjectMapper;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * A test class for {@link LocalityServlet}. It validates the servlet directly and Serde Mix-In of {@link ProcessorLocality}
 * indirectly.
 */
public class TestLocalityServlet {
  private static final String PROCESSOR_ID1 = "1";
  private static final String PROCESSOR_ID2 = "2";
  private static final String HOST1 = "host1";
  private static final String HOST2 = "host2";
  private static final String JMX_URL = "jmx";
  private static final String TUNNELING_URL = "tunneling";

  private static final ProcessorLocality PROCESSOR_1_LOCALITY =
      new ProcessorLocality(PROCESSOR_ID1, HOST1, JMX_URL, TUNNELING_URL);
  private static final ProcessorLocality PROCESSOR_2_LOCALITY =
      new ProcessorLocality("2", HOST2, JMX_URL, TUNNELING_URL);

  private final ObjectMapper mapper = SamzaObjectMapper.getObjectMapper();
  private HttpServer webApp;
  private LocalityManager localityManager;

  @Before
  public void setup()
      throws Exception {
    localityManager = mock(LocalityManager.class);
    when(localityManager.readLocality())
        .thenReturn(new LocalityModel(ImmutableMap.of(PROCESSOR_ID1, PROCESSOR_1_LOCALITY, PROCESSOR_ID2, PROCESSOR_2_LOCALITY)));
    webApp = new HttpServer("/", 0, "", new ServletHolder(new DefaultServlet()));
    webApp.addServlet("/locality", new LocalityServlet(localityManager));
    webApp.start();
  }

  @After
  public void cleanup()
      throws Exception {
    webApp.stop();
  }

  @Test
  public void testReadContainerLocality() throws Exception {
    URL url = new URL(webApp.getUrl().toString() + "locality");

    String response = HttpUtil.read(url, 1000, new ExponentialSleepStrategy());
    LocalityModel locality = mapper.readValue(response, LocalityModel.class);

    assertEquals("Expected locality for two containers", 2, locality.getProcessorLocalities().size());
    assertEquals("Mismatch in locality for processor " + PROCESSOR_ID1,
        locality.getProcessorLocality(PROCESSOR_ID1), PROCESSOR_1_LOCALITY);
    assertEquals("Mismatch in locality for processor " + PROCESSOR_ID2,
        locality.getProcessorLocality(PROCESSOR_ID2), PROCESSOR_2_LOCALITY);
  }

  @Test
  public void testReadContainerLocalityWithNoLocality() throws Exception {
    final LocalityModel expectedLocality = new LocalityModel(Collections.emptyMap());
    URL url = new URL(webApp.getUrl().toString() + "locality");
    when(localityManager.readLocality()).thenReturn(new LocalityModel(ImmutableMap.of()));

    String response = HttpUtil.read(url, 1000, new ExponentialSleepStrategy());
    LocalityModel locality = mapper.readValue(response, LocalityModel.class);

    assertEquals("Expected empty response but got " + locality, locality, expectedLocality);
  }

  @Test
  public void testReadProcessorLocality() throws Exception {
    URL url = new URL(webApp.getUrl().toString() + "locality?processorId=" + PROCESSOR_ID1);
    String response = HttpUtil.read(url, 1000, new ExponentialSleepStrategy());

    assertEquals("Mismatch in the locality for processor " + PROCESSOR_ID1,
        mapper.readValue(response, ProcessorLocality.class), PROCESSOR_1_LOCALITY);
  }

  @Test
  public void testReadProcessorLocalityWithNoLocality() throws Exception {
    final ProcessorLocality expectedProcessorLocality = new ProcessorLocality(PROCESSOR_ID2, "");
    URL url = new URL(webApp.getUrl().toString() + "locality?processorId=" + PROCESSOR_ID2);
    when(localityManager.readLocality()).thenReturn(new LocalityModel(ImmutableMap.of()));

    String response = HttpUtil.read(url, 1000, new ExponentialSleepStrategy());
    ProcessorLocality processorLocality = mapper.readValue(response, ProcessorLocality.class);

    assertEquals("Expected empty response for processor locality " + PROCESSOR_ID2 + " but got " + processorLocality,
        processorLocality, expectedProcessorLocality);
  }
}


text:
using base::StringPiece;
using net::EpollServer;
using net::test::MockSession;
using net::tools::test::MockConnection;
using testing::_;
using testing::DoAll;
using testing::Invoke;
using testing::InSequence;
using testing::Return;
using testing::WithoutArgs;

namespace net {
namespace tools {
namespace test {
class QuicDispatcherPeer {
 public:
  static void SetTimeWaitListManager(
      QuicDispatcher* dispatcher,
      QuicTimeWaitListManager* time_wait_list_manager) {
    dispatcher->time_wait_list_manager_.reset(time_wait_list_manager);
  }

  static void SetWriteBlocked(QuicDispatcher* dispatcher) {
    dispatcher->write_blocked_ = true;
  }
};

namespace {

class TestDispatcher : public QuicDispatcher {
 public:
  explicit TestDispatcher(const QuicConfig& config,
                          const QuicCryptoServerConfig& crypto_config,
                          EpollServer* eps)
      : QuicDispatcher(config, crypto_config, 1, eps) {}

  MOCK_METHOD4(CreateQuicSession, QuicSession*(
      QuicGuid guid,
      const IPEndPoint& client_address,
      int fd,
      EpollServer* eps));
  using QuicDispatcher::write_blocked_list;
};

// A Connection class which unregisters the session from the dispatcher
// when sending connection close.
// It'd be slightly more realistic to do this from the Session but it would
// involve a lot more mocking.
class MockServerConnection : public MockConnection {
 public:
  MockServerConnection(QuicGuid guid,
                       IPEndPoint address,
                       int fd,
                       EpollServer* eps,
                       QuicDispatcher* dispatcher)
      : MockConnection(guid, address, fd, eps, true),
        dispatcher_(dispatcher) {
  }
  void UnregisterOnConnectionClose() {
    LOG(ERROR) << "Unregistering " << guid();
    dispatcher_->OnConnectionClose(guid(), QUIC_NO_ERROR);
  }
 private:
  QuicDispatcher* dispatcher_;
};

QuicSession* CreateSession(QuicDispatcher* dispatcher,
                           QuicGuid guid,
                           const IPEndPoint& addr,
                           MockSession** session,
                           EpollServer* eps) {
  MockServerConnection* connection =
      new MockServerConnection(guid, addr, 0, eps, dispatcher);
  *session = new MockSession(connection, true);
  ON_CALL(*connection, SendConnectionClose(_)).WillByDefault(
      WithoutArgs(Invoke(
          connection, &MockServerConnection::UnregisterOnConnectionClose)));
  EXPECT_CALL(*reinterpret_cast<MockConnection*>((*session)->connection()),
              ProcessUdpPacket(_, addr, _));

  return *session;
}

class QuicDispatcherTest : public ::testing::Test {
 public:
  QuicDispatcherTest()
      : crypto_config_(QuicCryptoServerConfig::TESTING),
        dispatcher_(config_, crypto_config_, &eps_),
        session1_(NULL),
        session2_(NULL) {
  }

  ~QuicDispatcherTest() {
  }

  MockConnection* connection1() {
    return reinterpret_cast<MockConnection*>(session1_->connection());
  }

  MockConnection* connection2() {
    return reinterpret_cast<MockConnection*>(session2_->connection());
  }

  void ProcessPacket(IPEndPoint addr,
                     QuicGuid guid,
                     const string& data) {
    QuicEncryptedPacket packet(data.data(), data.length());
    dispatcher_.ProcessPacket(IPEndPoint(), addr, guid, packet);
  }

  void ValidatePacket(const QuicEncryptedPacket& packet) {
    EXPECT_TRUE(packet.AsStringPiece().find(data_) != StringPiece::npos);
  }

  IPAddressNumber Loopback4() {
    net::IPAddressNumber addr;
    CHECK(net::ParseIPLiteralToNumber("127.0.0.1", &addr));
    return addr;
  }

  EpollServer eps_;
  QuicConfig config_;
  QuicCryptoServerConfig crypto_config_;
  TestDispatcher dispatcher_;
  MockSession* session1_;
  MockSession* session2_;
  string data_;
};

TEST_F(QuicDispatcherTest, ProcessPackets) {
  IPEndPoint addr(Loopback4(), 1);

  EXPECT_CALL(dispatcher_, CreateQuicSession(1, addr, _, &eps_))
      .WillOnce(testing::Return(CreateSession(
          &dispatcher_, 1, addr, &session1_, &eps_)));
  ProcessPacket(addr, 1, "foo");

  EXPECT_CALL(dispatcher_, CreateQuicSession(2, addr, _, &eps_))
      .WillOnce(testing::Return(CreateSession(
                    &dispatcher_, 2, addr, &session2_, &eps_)));
  ProcessPacket(addr, 2, "bar");

  data_ = "eep";
  EXPECT_CALL(*reinterpret_cast<MockConnection*>(session1_->connection()),
              ProcessUdpPacket(_, _, _)).Times(1).
      WillOnce(testing::WithArgs<2>(Invoke(
          this, &QuicDispatcherTest::ValidatePacket)));
  ProcessPacket(addr, 1, "eep");
}

TEST_F(QuicDispatcherTest, Shutdown) {
  IPEndPoint addr(Loopback4(), 1);

  EXPECT_CALL(dispatcher_, CreateQuicSession(_, addr, _, &eps_))
      .WillOnce(testing::Return(CreateSession(
                    &dispatcher_, 1, addr, &session1_, &eps_)));

  ProcessPacket(addr, 1, "foo");

  EXPECT_CALL(*reinterpret_cast<MockConnection*>(session1_->connection()),
              SendConnectionClose(QUIC_PEER_GOING_AWAY));

  dispatcher_.Shutdown();
}

class MockTimeWaitListManager : public QuicTimeWaitListManager {
 public:
  MockTimeWaitListManager(QuicPacketWriter* writer,
                          EpollServer* eps)
      : QuicTimeWaitListManager(writer, eps) {
  }

  MOCK_METHOD4(ProcessPacket, void(const IPEndPoint& server_address,
                                   const IPEndPoint& client_address,
                                   QuicGuid guid,
                                   const QuicEncryptedPacket& packet));
};

TEST_F(QuicDispatcherTest, TimeWaitListManager) {
  MockTimeWaitListManager* time_wait_list_manager =
      new MockTimeWaitListManager(&dispatcher_, &eps_);
  // dispatcher takes the ownership of time_wait_list_manager.
  QuicDispatcherPeer::SetTimeWaitListManager(&dispatcher_,
                                             time_wait_list_manager);
  // Create a new session.
  IPEndPoint addr(Loopback4(), 1);
  QuicGuid guid = 1;
  EXPECT_CALL(dispatcher_, CreateQuicSession(guid, addr, _, &eps_))
      .WillOnce(testing::Return(CreateSession(
                    &dispatcher_, guid, addr, &session1_, &eps_)));
  ProcessPacket(addr, guid, "foo");

  // Close the connection by sending public reset packet.
  QuicPublicResetPacket packet;
  packet.public_header.guid = guid;
  packet.public_header.reset_flag = true;
  packet.public_header.version_flag = false;
  packet.rejected_sequence_number = 19191;
  packet.nonce_proof = 132232;
  scoped_ptr<QuicEncryptedPacket> encrypted(
      QuicFramer::ConstructPublicResetPacket(packet));
  EXPECT_CALL(*session1_, ConnectionClose(QUIC_PUBLIC_RESET, true)).Times(1)
      .WillOnce(WithoutArgs(Invoke(
          reinterpret_cast<MockServerConnection*>(session1_->connection()),
          &MockServerConnection::UnregisterOnConnectionClose)));
  EXPECT_CALL(*reinterpret_cast<MockConnection*>(session1_->connection()),
              ProcessUdpPacket(_, _, _))
      .WillOnce(Invoke(
          reinterpret_cast<MockConnection*>(session1_->connection()),
          &MockConnection::ReallyProcessUdpPacket));
  dispatcher_.ProcessPacket(IPEndPoint(), addr, guid, *encrypted);
  EXPECT_TRUE(time_wait_list_manager->IsGuidInTimeWait(guid));

  // Dispatcher forwards subsequent packets for this guid to the time wait list
  // manager.
  EXPECT_CALL(*time_wait_list_manager, ProcessPacket(_, _, guid, _)).Times(1);
  ProcessPacket(addr, guid, "foo");
}

class WriteBlockedListTest : public QuicDispatcherTest {
 public:
  void SetUp() {
    IPEndPoint addr(Loopback4(), 1);

    EXPECT_CALL(dispatcher_, CreateQuicSession(_, addr, _, &eps_))
        .WillOnce(testing::Return(CreateSession(
                      &dispatcher_, 1, addr, &session1_, &eps_)));
    ProcessPacket(addr, 1, "foo");

    EXPECT_CALL(dispatcher_, CreateQuicSession(_, addr, _, &eps_))
        .WillOnce(testing::Return(CreateSession(
                      &dispatcher_, 2, addr, &session2_, &eps_)));
    ProcessPacket(addr, 2, "bar");

    blocked_list_ = dispatcher_.write_blocked_list();
  }

  virtual void TearDown() {
    EXPECT_CALL(*connection1(), SendConnectionClose(QUIC_PEER_GOING_AWAY));
    EXPECT_CALL(*connection2(), SendConnectionClose(QUIC_PEER_GOING_AWAY));
    dispatcher_.Shutdown();
  }

  bool SetBlocked() {
    QuicDispatcherPeer::SetWriteBlocked(&dispatcher_);
    return true;
  }

 protected:
  QuicDispatcher::WriteBlockedList* blocked_list_;
};

TEST_F(WriteBlockedListTest, BasicOnCanWrite) {
  // No OnCanWrite calls because no connections are blocked.
  dispatcher_.OnCanWrite();

  // Register connection 1 for events, and make sure it's nofitied.
  blocked_list_->AddBlockedObject(connection1());
  EXPECT_CALL(*connection1(), OnCanWrite());
  dispatcher_.OnCanWrite();

  // It should get only one notification.
  EXPECT_CALL(*connection1(), OnCanWrite()).Times(0);
  EXPECT_FALSE(dispatcher_.OnCanWrite());
}

TEST_F(WriteBlockedListTest, OnCanWriteOrder) {
  // Make sure we handle events in order.
  InSequence s;
  blocked_list_->AddBlockedObject(connection1());
  blocked_list_->AddBlockedObject(connection2());
  EXPECT_CALL(*connection1(), OnCanWrite());
  EXPECT_CALL(*connection2(), OnCanWrite());
  dispatcher_.OnCanWrite();

  // Check the other ordering.
  blocked_list_->AddBlockedObject(connection2());
  blocked_list_->AddBlockedObject(connection1());
  EXPECT_CALL(*connection2(), OnCanWrite());
  EXPECT_CALL(*connection1(), OnCanWrite());
  dispatcher_.OnCanWrite();
}

TEST_F(WriteBlockedListTest, OnCanWriteRemove) {
  // Add and remove one connction.
  blocked_list_->AddBlockedObject(connection1());
  blocked_list_->RemoveBlockedObject(connection1());
  EXPECT_CALL(*connection1(), OnCanWrite()).Times(0);
  dispatcher_.OnCanWrite();

  // Add and remove one connction and make sure it doesn't affect others.
  blocked_list_->AddBlockedObject(connection1());
  blocked_list_->AddBlockedObject(connection2());
  blocked_list_->RemoveBlockedObject(connection1());
  EXPECT_CALL(*connection2(), OnCanWrite());
  dispatcher_.OnCanWrite();

  // Add it, remove it, and add it back and make sure things are OK.
  blocked_list_->AddBlockedObject(connection1());
  blocked_list_->RemoveBlockedObject(connection1());
  blocked_list_->AddBlockedObject(connection1());
  EXPECT_CALL(*connection1(), OnCanWrite()).Times(1);
  dispatcher_.OnCanWrite();
}

TEST_F(WriteBlockedListTest, DoubleAdd) {
  // Make sure a double add does not necessitate a double remove.
  blocked_list_->AddBlockedObject(connection1());
  blocked_list_->AddBlockedObject(connection1());
  blocked_list_->RemoveBlockedObject(connection1());
  EXPECT_CALL(*connection1(), OnCanWrite()).Times(0);
  dispatcher_.OnCanWrite();

  // Make sure a double add does not result in two OnCanWrite calls.
  blocked_list_->AddBlockedObject(connection1());
  blocked_list_->AddBlockedObject(connection1());
  EXPECT_CALL(*connection1(), OnCanWrite()).Times(1);
  dispatcher_.OnCanWrite();
}

TEST_F(WriteBlockedListTest, OnCanWriteHandleBlock) {
  // Finally make sure if we write block on a write call, we stop calling.
  InSequence s;
  blocked_list_->AddBlockedObject(connection1());
  blocked_list_->AddBlockedObject(connection2());
  EXPECT_CALL(*connection1(), OnCanWrite()).WillOnce(
      Invoke(this, &WriteBlockedListTest::SetBlocked));
  EXPECT_CALL(*connection2(), OnCanWrite()).Times(0);
  dispatcher_.OnCanWrite();

  // And we'll resume where we left off when we get another call.
  EXPECT_CALL(*connection2(), OnCanWrite());
  dispatcher_.OnCanWrite();
}

TEST_F(WriteBlockedListTest, LimitedWrites) {
  // Make sure we call both writers.  The first will register for more writing
  // but should not be immediately called due to limits.
  InSequence s;
  blocked_list_->AddBlockedObject(connection1());
  blocked_list_->AddBlockedObject(connection2());
  EXPECT_CALL(*connection1(), OnCanWrite()).WillOnce(Return(true));
  EXPECT_CALL(*connection2(), OnCanWrite()).WillOnce(Return(false));
  dispatcher_.OnCanWrite();

  // Now call OnCanWrite again, and connection1 should get its second chance
  EXPECT_CALL(*connection1(), OnCanWrite());
  dispatcher_.OnCanWrite();
}

TEST_F(WriteBlockedListTest, TestWriteLimits) {
  // Finally make sure if we write block on a write call, we stop calling.
  InSequence s;
  blocked_list_->AddBlockedObject(connection1());
  blocked_list_->AddBlockedObject(connection2());
  EXPECT_CALL(*connection1(), OnCanWrite()).WillOnce(
      Invoke(this, &WriteBlockedListTest::SetBlocked));
  EXPECT_CALL(*connection2(), OnCanWrite()).Times(0);
  dispatcher_.OnCanWrite();

  // And we'll resume where we left off when we get another call.
  EXPECT_CALL(*connection2(), OnCanWrite());
  dispatcher_.OnCanWrite();
}

}  // namespace
}  // namespace test
}  // namespace tools
}  // namespace net


text:
package io.cloudslang.content.nutanix.prism.actions.virtualmachines;

import com.hp.oo.sdk.content.annotations.Action;
import com.hp.oo.sdk.content.annotations.Output;
import com.hp.oo.sdk.content.annotations.Param;
import com.hp.oo.sdk.content.annotations.Response;
import com.jayway.jsonpath.JsonPath;
import io.cloudslang.content.constants.ReturnCodes;
import io.cloudslang.content.nutanix.prism.entities.NutanixCommonInputs;
import io.cloudslang.content.nutanix.prism.entities.NutanixCreateVMInputs;
import io.cloudslang.content.utils.StringUtilities;

import java.util.List;
import java.util.Map;

import static com.hp.oo.sdk.content.plugin.ActionMetadata.MatchType.COMPARE_EQUAL;
import static com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType.ERROR;
import static com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType.RESOLVED;
import static io.cloudslang.content.constants.OutputNames.*;
import static io.cloudslang.content.constants.ResponseNames.FAILURE;
import static io.cloudslang.content.constants.ResponseNames.SUCCESS;
import static io.cloudslang.content.httpclient.entities.HttpClientInputs.*;
import static io.cloudslang.content.nutanix.prism.services.VMImpl.createVM;
import static io.cloudslang.content.nutanix.prism.utils.Constants.Common.*;
import static io.cloudslang.content.nutanix.prism.utils.Constants.CreateVMConstants.CREATE_VM_OPERATION_NAME;
import static io.cloudslang.content.nutanix.prism.utils.Constants.CreateVMConstants.TASK_UUID_PATH;
import static io.cloudslang.content.nutanix.prism.utils.Descriptions.Common.*;
import static io.cloudslang.content.nutanix.prism.utils.Descriptions.CreateVM.*;
import static io.cloudslang.content.nutanix.prism.utils.HttpUtils.getFailureResults;
import static io.cloudslang.content.nutanix.prism.utils.HttpUtils.getOperationResults;
import static io.cloudslang.content.nutanix.prism.utils.Inputs.CommonInputs.PASSWORD;
import static io.cloudslang.content.nutanix.prism.utils.Inputs.CommonInputs.PROXY_HOST;
import static io.cloudslang.content.nutanix.prism.utils.Inputs.CommonInputs.PROXY_PASSWORD;
import static io.cloudslang.content.nutanix.prism.utils.Inputs.CommonInputs.PROXY_PORT;
import static io.cloudslang.content.nutanix.prism.utils.Inputs.CommonInputs.PROXY_USERNAME;
import static io.cloudslang.content.nutanix.prism.utils.Inputs.CommonInputs.USERNAME;
import static io.cloudslang.content.nutanix.prism.utils.Inputs.CommonInputs.*;
import static io.cloudslang.content.nutanix.prism.utils.Inputs.CreateVMInputs.*;
import static io.cloudslang.content.nutanix.prism.utils.InputsValidation.verifyCommonInputs;
import static io.cloudslang.content.nutanix.prism.utils.Outputs.CommonOutputs.TASK_UUID;
import static io.cloudslang.content.utils.OutputUtilities.getFailureResultsMap;
import static org.apache.commons.lang3.StringUtils.EMPTY;
import static org.apache.commons.lang3.StringUtils.defaultIfEmpty;

public class CreateVM {
    @Action(name = CREATE_VM_OPERATION_NAME,
            description = CREATE_VM_OPERATION_DESC,
            outputs = {
                    @Output(value = RETURN_RESULT, description = RETURN_RESULT_DESC),
                    @Output(value = EXCEPTION, description = EXCEPTION_DESC),
                    @Output(value = STATUS_CODE, description = STATUS_CODE_DESC),
                    @Output(value = TASK_UUID, description = TASK_UUID_DESC)
            },
            responses = {
                    @Response(text = SUCCESS, field = RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = COMPARE_EQUAL,
                            responseType = RESOLVED, description = SUCCESS_DESC),
                    @Response(text = FAILURE, field = RETURN_CODE, value = ReturnCodes.FAILURE, matchType = COMPARE_EQUAL,
                            responseType = ERROR, description = FAILURE_DESC)
            })
    public Map<String, String> execute(@Param(value = HOSTNAME, required = true, description = HOSTNAME_DESC) String hostname,
                                       @Param(value = PORT, description = PORT_DESC) String port,
                                       @Param(value = USERNAME, required = true, description = USERNAME_DESC) String username,
                                       @Param(value = PASSWORD, encrypted = true, required = true, description = PASSWORD_DESC) String password,
                                       @Param(value = VM_NAME, required = true, description = VM_NAME_DESC) String vmName,
                                       @Param(value = VM_DESCRIPTION, description = VM_DESCRIPTION_DESC) String vmDescription,
                                       @Param(value = VM_MEMORY_SIZE, required = true, description = VM_MEMORY_SIZE_DESC) String vmMemorySize,
                                       @Param(value = NUM_VCPUS, required = true, description = NUM_VCPUS_DESC) String numVCPUs,
                                       @Param(value = NUM_CORES_PER_VCPU, required = true, description = NUM_CORES_PER_VCPU_DESC) String numCoresPerVCPU,
                                       @Param(value = TIME_ZONE, description = TIME_ZONE_DESC) String timeZone,
                                       @Param(value = HYPERVISOR_TYPE, description = HYPERVISOR_TYPE_DESC) String hypervisorType,
                                       @Param(value = FLASH_MODE_ENABLED, description = FLASH_MODE_ENABLED_DESC) String flashModeEnabled,
                                       @Param(value = IS_SCSI_PASS_THROUGH, description = IS_SCSI_PASS_THROUGH_DESC) String isSCSIPassThrough,
                                       @Param(value = IS_THIN_PROVISIONED, description = IS_THIN_PROVISIONED_DESC) String isThinProvisioned,
                                       @Param(value = IS_CDROM, required = true, description = IS_CDROM_DESC) String isCDROM,
                                       @Param(value = IS_EMPTY_DISK, description = IS_EMPTY_DISK_DESC) String isEmptyDisk,
                                       @Param(value = DEVICE_BUS, required = true, description = DEVICE_BUS_DESC) String deviceBus,
                                       @Param(value = DISK_LABEL, description = DISK_LABEL_DESC) String diskLabel,
                                       @Param(value = DEVICE_INDEX, description = DEVICE_INDEX_DESC) String deviceIndex,
                                       @Param(value = NDFS_FILE_PATH, description = NDFS_FILE_PATH_DESC) String ndfsFilepath,
                                       @Param(value = SOURCE_VM_DISK_UUID, description = SOURCE_VM_DISK_UUID_DESC) String sourceVMDiskUUID,
                                       @Param(value = VM_DISK_MINIMUM_SIZE, description = VM_DISK_MINIMUM_SIZE_DESC) String vmDiskMinimumSize,
                                       @Param(value = EXTERNAL_DISK_URL, description = EXTERNAL_DISK_URL_DESC) String externalDiskUrl,
                                       @Param(value = EXTERNAL_DISK_SIZE, description = EXTERNAL_DISK_SIZE_DESC) String externalDiskSize,
                                       @Param(value = STORAGE_CONTAINER_UUID, description = STORAGE_CONTAINER_UUID_DESC) String storageContainerUUID,
                                       @Param(value = VM_DISK_SIZE, description = VM_DISK_SIZE_DESC) String vmDiskSize,
                                       @Param(value = NETWORK_UUID, required = true, description = NETWORK_UUID_DESC) String networkUUID,
                                       @Param(value = REQUESTED_IP_ADDRESS, description = REQUESTED_IP_ADDRESS_DESC) String requestedIPAddress,
                                       @Param(value = IS_CONNECTED, description = IS_CONNECTED_DESC) String isConnected,
                                       @Param(value = HOST_UUIDS, description = HOST_UUIDS_DESC) String hostUUIDs,
                                       @Param(value = AGENT_VM, description = AGENT_VM_DESC) String agentVM,
                                       @Param(value = API_VERSION, description = API_VERSION_DESC) String apiVersion,
                                       @Param(value = PROXY_HOST, description = PROXY_HOST_DESC) String proxyHost,
                                       @Param(value = PROXY_PORT, description = PROXY_PORT_DESC) String proxyPort,
                                       @Param(value = PROXY_USERNAME, description = PROXY_USERNAME_DESC) String proxyUsername,
                                       @Param(value = PROXY_PASSWORD, encrypted = true, description = PROXY_PASSWORD_DESC) String proxyPassword,
                                       @Param(value = TRUST_ALL_ROOTS, description = TRUST_ALL_ROOTS_DESC) String trustAllRoots,
                                       @Param(value = X509_HOSTNAME_VERIFIER, description = X509_DESC) String x509HostnameVerifier,
                                       @Param(value = TRUST_KEYSTORE, description = TRUST_KEYSTORE_DESC) String trustKeystore,
                                       @Param(value = TRUST_PASSWORD, encrypted = true, description = TRUST_PASSWORD_DESC) String trustPassword,
                                       @Param(value = CONNECT_TIMEOUT, description = CONNECT_TIMEOUT_DESC) String connectTimeout,
                                       @Param(value = SOCKET_TIMEOUT, description = SOCKET_TIMEOUT_DESC) String socketTimeout,
                                       @Param(value = KEEP_ALIVE, description = KEEP_ALIVE_DESC) String keepAlive,
                                       @Param(value = CONNECTIONS_MAX_PER_ROUTE, description = CONN_MAX_ROUTE_DESC) String connectionsMaxPerRoute,
                                       @Param(value = CONNECTIONS_MAX_TOTAL, description = CONN_MAX_TOTAL_DESC) String connectionsMaxTotal) {
        port = defaultIfEmpty(port, DEFAULT_NUTANIX_PORT);
        vmDescription = defaultIfEmpty(vmDescription, EMPTY);
        hypervisorType = defaultIfEmpty(hypervisorType, EMPTY);
        timeZone = defaultIfEmpty(timeZone, DEFAULT_TIMEZONE);
        flashModeEnabled = defaultIfEmpty(flashModeEnabled, BOOLEAN_FALSE);
        isSCSIPassThrough = defaultIfEmpty(isSCSIPassThrough, BOOLEAN_TRUE);
        isThinProvisioned = defaultIfEmpty(isThinProvisioned, BOOLEAN_FALSE);
        isEmptyDisk = defaultIfEmpty(isEmptyDisk, BOOLEAN_FALSE);
        diskLabel = defaultIfEmpty(diskLabel, EMPTY);
        deviceIndex = defaultIfEmpty(deviceIndex, ZERO);
        ndfsFilepath = defaultIfEmpty(ndfsFilepath, EMPTY);
        sourceVMDiskUUID = defaultIfEmpty(sourceVMDiskUUID, EMPTY);
        vmDiskMinimumSize = defaultIfEmpty(vmDiskMinimumSize, ZERO);
        externalDiskUrl = defaultIfEmpty(externalDiskUrl, EMPTY);
        externalDiskSize = defaultIfEmpty(externalDiskSize, ZERO);
        storageContainerUUID = defaultIfEmpty(storageContainerUUID, EMPTY);
        vmDiskSize = defaultIfEmpty(vmDiskSize, ZERO);
        requestedIPAddress = defaultIfEmpty(requestedIPAddress, EMPTY);
        isConnected = defaultIfEmpty(isConnected, BOOLEAN_TRUE);
        hostUUIDs = defaultIfEmpty(hostUUIDs, EMPTY);
        agentVM = defaultIfEmpty(agentVM, BOOLEAN_FALSE);
        apiVersion = defaultIfEmpty(apiVersion, DEFAULT_API_VERSION);
        proxyHost = defaultIfEmpty(proxyHost, EMPTY);
        proxyPort = defaultIfEmpty(proxyPort, DEFAULT_PROXY_PORT);
        proxyUsername = defaultIfEmpty(proxyUsername, EMPTY);
        proxyPassword = defaultIfEmpty(proxyPassword, EMPTY);
        trustAllRoots = defaultIfEmpty(trustAllRoots, BOOLEAN_FALSE);
        x509HostnameVerifier = defaultIfEmpty(x509HostnameVerifier, STRICT);
        trustKeystore = defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE);
        trustPassword = defaultIfEmpty(trustPassword, CHANGEIT);
        connectTimeout = defaultIfEmpty(connectTimeout, CONNECT_TIMEOUT_CONST);
        socketTimeout = defaultIfEmpty(socketTimeout, ZERO);
        keepAlive = defaultIfEmpty(keepAlive, BOOLEAN_TRUE);
        connectionsMaxPerRoute = defaultIfEmpty(connectionsMaxPerRoute, CONNECTIONS_MAX_PER_ROUTE_CONST);
        connectionsMaxTotal = defaultIfEmpty(connectionsMaxTotal, CONNECTIONS_MAX_TOTAL_CONST);

        final List<String> exceptionMessage = verifyCommonInputs(proxyPort, trustAllRoots,
                connectTimeout, socketTimeout, keepAlive, connectionsMaxPerRoute, connectionsMaxTotal);
        if (!exceptionMessage.isEmpty()) {
            return getFailureResultsMap(StringUtilities.join(exceptionMessage, NEW_LINE));
        }
        try {
            final Map<String, String> result = createVM(NutanixCreateVMInputs.builder()
                    .vmName(vmName)
                    .description(vmDescription)
                    .vmMemorySize(vmMemorySize)
                    .numVCPUs(numVCPUs)
                    .numCoresPerVCPU(numCoresPerVCPU)
                    .timeZone(timeZone)
                    .hypervisorType(hypervisorType)
                    .flashModeEnabled(flashModeEnabled)
                    .isSCSIPassThrough(isSCSIPassThrough)
                    .isThinProvisioned(isThinProvisioned)
                    .isCDROM(isCDROM)
                    .isEmpty(isEmptyDisk)
                    .deviceBus(deviceBus)
                    .diskLabel(diskLabel)
                    .deviceIndex(deviceIndex)
                    .ndfsFilepath(ndfsFilepath)
                    .sourceVMDiskUUID(sourceVMDiskUUID)
                    .vmDiskMinimumSize(vmDiskMinimumSize)
                    .externalDiskUrl(externalDiskUrl)
                    .externalDiskSize(externalDiskSize)
                    .storageContainerUUID(storageContainerUUID)
                    .vmDiskSize(vmDiskSize)
                    .networkUUID(networkUUID)
                    .requestedIPAddress(requestedIPAddress)
                    .isConnected(isConnected)
                    .hostUUIDs(hostUUIDs)
                    .agentVM(agentVM)
                    .commonInputs(NutanixCommonInputs.builder()
                                    .hostname(hostname)
                                    .port(port)
                                    .username(username)
                                    .password(password)
                                    .apiVersion(apiVersion)
                                    .proxyHost(proxyHost)
                                    .proxyPort(proxyPort)
                                    .proxyUsername(proxyUsername)
                                    .proxyPassword(proxyPassword)
                                    .trustAllRoots(trustAllRoots)
                                    .x509HostnameVerifier(x509HostnameVerifier)
                                    .trustKeystore(trustKeystore)
                                    .trustPassword(trustPassword)
                                    .connectTimeout(connectTimeout)
                                    .socketTimeout(socketTimeout)
                                    .keepAlive(keepAlive)
                                    .connectionsMaxPerRoot(connectionsMaxPerRoute)
                                    .connectionsMaxTotal(connectionsMaxTotal)
                                    .build()).build());
            final String returnMessage = result.get(RETURN_RESULT);
            final Map<String, String> results = getOperationResults(result, returnMessage, returnMessage, returnMessage);
            final int statusCode = Integer.parseInt(result.get(STATUS_CODE));
            if (statusCode >= 200 && statusCode < 300) {
                final String taskUUID = JsonPath.read(returnMessage, TASK_UUID_PATH);
                results.put(TASK_UUID, taskUUID);
            } else {
                return getFailureResults(hostname, statusCode, returnMessage, returnMessage);
            }
            return results;
        } catch (Exception exception) {
            return getFailureResultsMap(exception);
        }

    }
}


text:
#ifndef COMMON_GAMELET_COMPONENT_H_
#define COMMON_GAMELET_COMPONENT_H_

#include <string>
#include <vector>

#include "absl/status/status.h"

namespace cdc_ft {

// Provides functionality to check the freshness of gamelet components.
// The components are considered fresh if both the timestamp and the file size
// match.
struct GameletComponent {
  std::string filename;
  uint64_t size;
  int64_t modified_time;

  GameletComponent(std::string filename, uint64_t size, time_t modified_time);
  ~GameletComponent();

  bool operator==(const GameletComponent& other) const;
  bool operator!=(const GameletComponent& other) const;

  // Gets the list of gamelet |components| from the given |component_paths|.
  // Returns false if any of the components does not exist or cannot be stat'ed.
  static absl::Status Get(const std::vector<std::string> component_paths,
                          std::vector<GameletComponent>* components);

  // Serializes the list of gamelet |components| as command line options.
  // This should be called on the workstation. The resulting command line
  // should be passed to the gamelet process.
  static std::string ToCommandLineArgs(
      const std::vector<GameletComponent>& components);

  // Deserializes the list of gamelet components from command line options.
  // This should be called in the gamelet process to retrieve the workstation
  // components, which can then be compared to the gamelet components to check
  // freshness.
  static std::vector<GameletComponent> FromCommandLineArgs(int argc,
                                                           const char** argv);

  // Deserializes the list of gamelet components from a |components_arg| string
  // as it is returned by ToCommandLineArgs().
  // This should be called in the gamelet process to retrieve the workstation
  // components, which can then be compared to the gamelet components to check
  // freshness.
  static std::vector<GameletComponent> FromCommandLineArgs(
      const std::string& components_arg);
};

}  // namespace cdc_ft

#endif  // COMMON_GAMELET_COMPONENT_H_


text:
using System.Threading.Tasks;
using Octokit.Tests.Integration.Helpers;
using Xunit;

namespace Octokit.Tests.Integration.Clients
{
    public class TagsClientTests
    {
        public class TheCreateMethod
        {
            readonly RepositoryContext context;
            readonly ITagsClient fixture;
            readonly string sha;

            public TheCreateMethod()
            {
                var github = Helper.GetAuthenticatedClient();

                fixture = github.Git.Tag;
                context = github.CreateRepositoryContext("public-repo").Result;

                var blob = new NewBlob
                {
                    Content = "Hello World!",
                    Encoding = EncodingType.Utf8
                };
                var blobResult = github.Git.Blob.Create(context.RepositoryOwner, context.RepositoryName, blob).Result;

                sha = blobResult.Sha;
            }

            [IntegrationTest]
            public async Task CreatesTagForRepository()
            {
                var newTag = new NewTag { Message = "Hello", Type = TaggedType.Blob, Object = sha, Tag = "tag" };

                var tag = await fixture.Create(context.Repository.Id, newTag);

                Assert.Equal(TaggedType.Blob, tag.Object.Type);
                Assert.Equal("Hello", tag.Message);
                Assert.Equal(tag.Object.Sha, sha);
            }

            [IntegrationTest]
            public async Task CreatesTagForRepositoryWithRepositoryId()
            {
                var newTag = new NewTag { Message = "Hello", Type = TaggedType.Tree, Object = sha, Tag = "tag" };

                var tag = await fixture.Create(context.Repository.Id, newTag);

                Assert.Equal(TaggedType.Blob, tag.Object.Type);
                Assert.Equal("Hello", tag.Message);
                Assert.Equal(tag.Object.Sha, sha);
            }
        }

        public class TheGetMethod
        {
            readonly RepositoryContext context;
            readonly ITagsClient fixture;
            readonly string sha;

            public TheGetMethod()
            {
                var github = Helper.GetAuthenticatedClient();

                fixture = github.Git.Tag;
                context = github.CreateRepositoryContext("public-repo").Result;

                var blob = new NewBlob
                {
                    Content = "Hello World!",
                    Encoding = EncodingType.Utf8
                };
                var blobResult = github.Git.Blob.Create(context.RepositoryOwner, context.RepositoryName, blob).Result;

                sha = blobResult.Sha;
            }

            [IntegrationTest]
            public async Task CreatesTagForRepository()
            {
                var newTag = new NewTag { Message = "Hello", Type = TaggedType.Blob, Object = sha, Tag = "tag" };

                var tag = await fixture.Create(context.RepositoryOwner, context.RepositoryName, newTag);
                var gitTag = await fixture.Get(context.RepositoryOwner, context.RepositoryName, tag.Sha);

                Assert.NotNull(gitTag);
                Assert.Equal(TaggedType.Blob, gitTag.Object.Type);
                Assert.Equal("Hello", gitTag.Message);
                Assert.Equal(gitTag.Object.Sha, sha);
            }

            [IntegrationTest]
            public async Task CreatesTagForRepositoryWithRepositoryId()
            {
                var github = Helper.GetAuthenticatedClient();

                var newTag = new NewTag { Message = "Hello", Type = TaggedType.Blob, Object = sha, Tag = "tag" };

                var tag = await github.Git.Tag.Create(context.Repository.Id, newTag);

                var gitTag = await github.Git.Tag.Get(context.Repository.Id, tag.Sha);

                Assert.NotNull(gitTag);
                Assert.Equal(TaggedType.Blob, gitTag.Object.Type);
                Assert.Equal("Hello", gitTag.Message);
                Assert.Equal(gitTag.Object.Sha, sha);
            }

            [IntegrationTest]
            public async Task DeserializeTagSignatureVerification()
            {
                var github = Helper.GetAuthenticatedClient();

                var newTag = new NewTag { Message = "Hello", Type = TaggedType.Blob, Object = sha, Tag = "tag" };

                var tag = await github.Git.Tag.Create(context.Repository.Id, newTag);

                var gitTag = await github.Git.Tag.Get(context.Repository.Id, tag.Sha);

                Assert.NotNull(gitTag);

                Assert.False(gitTag.Verification.Verified);
                Assert.Equal(VerificationReason.Unsigned, gitTag.Verification.Reason);
                Assert.Null(gitTag.Verification.Signature);
                Assert.Null(gitTag.Verification.Payload);
            }
        }
    }
}


text:
html,body {margin:0;padding:0}
body {font: 85% arial,sans-serif;text-align:center; background:#939388;}
p {margin:0 10px 10px}
div#header {background-color:#7F803B;}
div#header h1{height:80px;line-height:80px;margin:0;padding-left:10px;color:#E0E0CF;}

div#container {text-align:left}
div#container {width:1200px;margin:0 auto}

div#content {background:#E0E0CF;}
div#content p {line-height:1.4;}
div#content {padding:1em;float:right;width:900px;}

div#navigation {background:#C2C2AF;}
div#navigation li {margin-top: 0.7em; margin-bottom: 0.7em; margin-left:-0.7em;list-style-type: none;}
div#navigation li.selected-menu-item {font-weight: bold;}
div#navigation li.menu-item :hover {background:#E0E0CF;}
div#navigation a {text-decoration:none; color:#000000;}
div#navigation {float:left;width:270px}

div#extra {background:#939388;}
div#extra {float:left;clear:left;width:270px}

div#footer {background:#7F803B;}
div#footer p {margin:0;padding:5px 10px}
div#footer {clear:both;width:100%}

code { font: bold 100% courier,fixed; }


text:
using NAudio.Utils;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BFDecoder
{
	/// <summary>
	/// A wrapper for the WasapiLoopbackCapture that will implement basic recording to a file that is overwrite only.
	/// </summary>
	public class LoopbackRecorder
	{
		private IWaveIn _waveIn;
		private WaveFileWriter _writer;
		private IgnoreDisposeStream _outputStream;
		private bool _isRecording = false;

		public LoopbackRecorder()
		{
			_outputStream = new IgnoreDisposeStream(new MemoryStream());
			_waveIn = new WasapiLoopbackCapture();
			_waveIn.DataAvailable += OnDataAvailable;
			_waveIn.RecordingStopped += OnRecordingStopped;
			_writer = new WaveFileWriter(_outputStream, _waveIn.WaveFormat);
		}

		public void StartRecording()
		{
			// If we are currently record then go ahead and exit out.
			if (_isRecording == true)
				return;

			_waveIn.StartRecording();
			_isRecording = true;
		}

		public void StopRecording()
		{
			if (_waveIn == null)
				return;

			_waveIn.StopRecording();
		}

		/// <summary>
		/// Event handled when recording is stopped.  We will clean up open objects here that are required to be
		/// closed and/or disposed of.
		/// </summary>
		void OnRecordingStopped(object sender, StoppedEventArgs e)
		{
			// Writer Close() needs to come first otherwise NAudio will lock up.

			if (_writer != null)
			{
				_writer.Dispose();
				_writer = null;

			}
			if (_waveIn != null)
			{
				_waveIn.Dispose();
				_waveIn = null;
			}

			_isRecording = false;
			if (e.Exception != null)
			{
				throw e.Exception;
			}
		}

		/// <summary>
		/// Event handled when data becomes available.  The data will be written out to disk at this point.
		/// </summary>
		void OnDataAvailable(object sender, WaveInEventArgs e)
		{
			_writer.Write(e.Buffer, 0, e.BytesRecorded);
		}

		public Stream GetRecordingStream()
		{
			return _outputStream;
		}
	}
}


text:
namespace updater {
std::vector<base::FilePath> GetHomeDirPaths(UpdaterScope scope) {
  NOTREACHED();
  return {};
}

base::FilePath GetActiveFile(const base::FilePath& home_dir,
                             const std::string& id) {
  NOTREACHED();
  return base::FilePath();
}

}  // namespace updater