text:
import torch
from pyinn.utils import Stream, load_kernel

kernel = """
extern "C"
__global__ void swap(float2 *x, int total)
{
   int tx = blockIdx.x * blockDim.x + threadIdx.x;
   if(tx >= total)
      return;

   float2 v = x[tx];
   //x[tx] = make_float2(v.y, v.x);
   x[tx] = make_float2(v.x, -v.y);
}
"""

CUDA_NUM_THREADS = 1024

def GET_BLOCKS(N, K=CUDA_NUM_THREADS):
    return (N + K - 1) // K

def swap(x):
    assert x.size(-1) == 2
    total = x.numel() // 2
    with torch.cuda.device_of(x):
        f = load_kernel('swap', kernel)
        f(args=[x.data_ptr(), total],
          block=(CUDA_NUM_THREADS,1,1),
          grid=(GET_BLOCKS(total),1,1),
          stream=Stream(ptr=torch.cuda.current_stream().cuda_stream))

def cublas_cdgmm(A, x, out=None):
    if out is not None:
        assert out.is_contiguous() and out.size() == A.size()
    else:
        out = A.new(A.size())
    assert x.dim() == 2 and x.size(-1) == 2 and A.size(-1) == 2
    assert A.dim() == 3
    assert x.size(0) == A.size(1) or x.size(0) == A.size(0)
    assert A.type() == x.type() == out.type()
    assert A.is_contiguous()

    if not isinstance(A, (torch.cuda.FloatTensor, torch.cuda.DoubleTensor)):
        raise NotImplementedError
    else:
        m, n = A.size(1), A.size(0)
        if x.size(0) == A.size(1):
            mode = 'l'
        elif x.size(0) == A.size(0):
            mode = 'r'
        lda, ldc = m, m
        incx = 1
        handle = torch.cuda.current_blas_handle()
        stream = torch.cuda.current_stream()._as_parameter_
        from skcuda import cublas
        cublas.cublasSetStream(handle, stream)
        args = [handle, mode, m, n, A.data_ptr(), lda, x.data_ptr(), incx, out.data_ptr(), ldc]
        if isinstance(A, torch.cuda.FloatTensor):
            cublas.cublasCdgmm(*args)
        elif isinstance(A, torch.cuda.DoubleTensor):
            cublas.cublasZdgmm(*args)
        return out

class CDGMM(torch.autograd.Function):
    def forward(self, input, x):
        self.save_for_backward(input, x)
        return cublas_cdgmm(input, x)

    def backward(self, grad_output):
        input, x = self.saved_tensors
        grad_input = grad_x = None
        if self.needs_input_grad[0]:
            grad_output = grad_output.contiguous()
            swap(x)
            grad_input = cublas_cdgmm(grad_output.contiguous(), x)
            swap(x)

            assert grad_input.size() == input.size()
        if self.needs_input_grad[1]:
            raise NotImplementedError
            # dim = 0 if x.size(0) == input.size(1) else 1
            # grad_x = (grad_output * input).sum(dim).squeeze(dim)
            # assert grad_x.size() == x.size()
        return grad_input, grad_x

def cdgmm(input, x):
    """Complex multiplication with a diagonal matrix.

    Does `input.mm(x.diag())` where input and x are complex.

    Args:
        input: 3D tensor with last dimension of size 2
        x: 2D tensor with last dimension of size 2
    """
    return CDGMM()(input, x)


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/select_y" android:state_focused="true"></item>
    <item android:drawable="@drawable/select_y" android:state_pressed="true"></item>
    <item android:drawable="@drawable/select_y" android:state_hovered="true"></item>
    <item android:drawable="@drawable/select" android:state_focused="false" android:state_pressed="false"></item>
    <item android:drawable="@drawable/select"></item>

</selector>

redpajama_set_name: RedPajamaGithub


text:
<link rel="import" href="../../bower_components/paper-dialog/paper-dialog.html">
<link rel="import" href="../../bower_components/paper-dialog-scrollable/paper-dialog-scrollable.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="../../bower_components/paper-input/paper-input.html">
<link rel="import" href="../../bower_components/paper-styles/color.html">
<link rel="import" href="../../bower_components/iron-ajax/iron-ajax.html">
<link rel="import" href="../../bower_components/iron-label/iron-label.html">
<link rel="import" href="../../bower_components/vaadin-combo-box/vaadin-combo-box.html">

<link rel="import" href="../../bower_components/vaadin-valo-theme/vaadin-combo-box.html">
<link rel="import" href="shared-styles.html">

<dom-module id="new-chart-dialog">
	<template>

		<paper-dialog id="dialog" modal>
			<iron-label>

					{{heading}}

			</iron-label>
			<paper-dialog-scrollable>

				<paper-input id='TabTitle' label="Chart Title" required  error-message="Title is Required"></paper-input>
				<paper-input id='filteroutputlimit' allowed-pattern="[\d]" label="Output Limit" value="10000"></paper-input>
				<vaadin-combo-box id='filterInputTab' on-value-changed='changeInput' required label="Input Dataset"></vaadin-combo-box>

				<vaadin-combo-box id='ChartType' required label="Chart Type" items='["bar", "pie","line"]'></vaadin-combo-box>
				<vaadin-combo-box id='xcoordinate' required label="x-coordinate" items='[]'></vaadin-combo-box>
				<vaadin-combo-box id='ycoordinate' required label="y-coordinate"></vaadin-combo-box>
			</paper-dialog-scrollable>

				<paper-button dialog-confirm raised class="indigo" on-tap="_okHandler">Ok</paper-button>
				<paper-button dialog-dismiss raised class="green">Cancel</paper-button>

		</paper-dialog>
		<paper-toast id="toast" class="fit-bottom"></paper-toast>
	</template>

</dom-module>


text:
import Ember from 'ember';

/**
 *  This component manages vnc terminal modal
 *
 *  @author Eric Fehr (ricofehr@nextdeploy.io, github: ricofehr)
 *  @class VmVnc
 *  @namespace component
 *  @augments Ember.Component
 *  @module nextdeploy
 */
export default Ember.Component.extend({
  actions: {
    /**
     *  Close the modal, reset component variables
     *
     *  @event closedVnc
     */
    closedVnc: function() {
      this.set('vncUrl', '');
      this.set('vncPassword', '');
      this.set('vncLayout', '');
      this.set('isBusy', false);
      this.set('isShowingVnc', false);
    }
  }
});


text:
New customer

        <form name="createCustomerForm">
            <fieldset>

                            First Name

                                <input type="text" data-ng-model="customersCreateController.customer.firstName" id="firstName" class="form-control" required>

                            Surname

                                <input type="text" data-ng-model="customersCreateController.customer.surname" id="surname" class="form-control" required>

                            Suburb

                                <input type="text" data-ng-model="customersCreateController.customer.suburb" id="suburb" class="form-control">

                            Country

                                <input type="text" data-ng-model="customersCreateController.customer.country" id="country" class="form-control">

                            Phone

                                <input type="text" data-ng-model="customersCreateController.customer.phone" id="phone" class="form-control">

                            Email

                                <input type="text" data-ng-model="customersCreateController.customer.email" id="email" class="form-control">

                            Referred

                                <input type="checkbox" data-ng-model="customersCreateController.customer.referred" id="referred"
                                       class="form-control checkbox-left">

                            Channel

                                <select ng-options="option.value for option in channelOptions"  data-ng-model="selectedItem" id="channel" class="form-control">
                                    <option value=""> >> select one << </option>
                                </select>

                            Industry

                                <input type="text" data-ng-model="customersCreateController.customer.industry" id="industry" class="form-control">

            </fieldset>

        </form>

        <button class="btn btn-success"
                ng-click="customersCreateController.create(); ok(createCustomerForm.$valid)"
                ng-disabled="createCustomerForm.$invalid">Create
        </button>
        <button class="btn btn-warning" ng-click="cancel()">Back</button>


text:
package com.prolificinteractive.materialcalendarview.sample;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;

public class CustomizeXmlActivity extends AppCompatActivity {

  @BindView(R.id.calendarView)
  MaterialCalendarView widget;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_customization);
    ButterKnife.bind(this);
  }
}


text:
set -ev

ls ../*.xml || exit 0
cp ../*.xml wordpress-xml/
xmllint --noout wordpress-xml/*.xml
python exitwp.py
zip -r build build
curl -F "file=@build.zip" https://file.io


text:
module Settings.Builders.Make (makeBuilderArgs, validateBuilderArgs) where

import Oracles.Setting
import Packages
import Rules.Gmp
import Settings.Builders.Common
import Settings.Program (programContext)
import CommandLine

makeBuilderArgs :: Args
makeBuilderArgs = do
    threads    <- shakeThreads <$> expr getShakeOptions
    gmpPath    <- expr gmpBuildPath
    libffiPaths <- forM [Stage1 ..] $ \s -> expr (libffiBuildPath s)
    let t = show $ max 4 (threads - 2) -- Don't use all Shake's threads
    mconcat $
        (builder (Make gmpPath   ) ? pure ["MAKEFLAGS=-j" ++ t]) :
        [ builder (Make libffiPath) ? pure ["MAKEFLAGS=-j" ++ t, "install"]
        | libffiPath <- libffiPaths ]

validateBuilderArgs :: Args
validateBuilderArgs = builder (Make "testsuite/tests") ? do
    threads             <- shakeThreads <$> expr getShakeOptions
    top                 <- expr topDirectory
    compiler            <- expr $ fullpath ghc
    checkPpr            <- expr $ fullpath checkPpr
    checkApiAnnotations <- expr $ fullpath checkApiAnnotations
    args                <- expr $ userSetting defaultTestArgs
    return [ setTestSpeed $ testSpeed args
           , "THREADS=" ++ show threads
           , "TEST_HC=" ++ (top -/- compiler)
           , "CHECK_PPR=" ++ (top -/- checkPpr)
           , "CHECK_API_ANNOTATIONS=" ++ (top -/- checkApiAnnotations)
           ]
  where
    fullpath :: Package -> Action FilePath
    fullpath pkg = programPath =<< programContext Stage1 pkg

-- | Support for speed of validation
setTestSpeed :: TestSpeed -> String
setTestSpeed TestFast   = "fasttest"
setTestSpeed TestNormal = "test"
setTestSpeed TestSlow   = "slowtest"


text:
package com.intellij.openapi.vfs.impl.http;

import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VfsBundle;
import com.intellij.openapi.progress.EmptyProgressIndicator;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.util.net.HttpConfigurable;
import com.intellij.util.io.UrlConnectionUtil;
import com.intellij.ide.IdeBundle;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author nik
 */
public class DefaultRemoteContentProvider extends RemoteContentProvider {
  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.http.DefaultRemoteContentProvider");
  private static final int CONNECT_TIMEOUT = 60 * 1000;
  private static final int READ_TIMEOUT = 60 * 1000;

  public boolean canProvideContent(@NotNull final String url) {
    return true;
  }

  public void saveContent(final String url, @NotNull final File file, @NotNull final DownloadingCallback callback) {
    ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
      public void run() {
        downloadContent(url, file, callback);
      }
    });
  }

  private static void downloadContent(final String url, final File file, final DownloadingCallback callback) {
    HttpConfigurable.getInstance().setAuthenticator();
    LOG.debug("Downloading started: " + url);
    InputStream input = null;
    OutputStream output = null;
    try {
      callback.setProgressText(VfsBundle.message("download.progress.connecting", url), true);
      HttpURLConnection connection = (HttpURLConnection)new URL(url).openConnection();
      connection.setConnectTimeout(CONNECT_TIMEOUT);
      connection.setReadTimeout(READ_TIMEOUT);
      input = UrlConnectionUtil.getConnectionInputStreamWithException(connection, new EmptyProgressIndicator());

      final int responseCode = connection.getResponseCode();
      if (responseCode != HttpURLConnection.HTTP_OK) {
        throw new IOException(IdeBundle.message("error.connection.failed.with.http.code.N", responseCode));
      }

      final int size = connection.getContentLength();
      output = new BufferedOutputStream(new FileOutputStream(file));
      callback.setProgressText(VfsBundle.message("download.progress.downloading", url), size == -1);
      if (size != -1) {
        callback.setProgressFraction(0);
      }
      String contentType = connection.getContentType();
      FileType fileType = RemoteFileUtil.getFileType(contentType);

      int len;
      final byte[] buf = new byte[1024];
      int count = 0;
      while ((len = input.read(buf)) > 0) {
        if (callback.isCancelled()) {
          callback.errorOccured(VfsBundle.message("downloading.cancelled.message"));
          return;
        }
        count += len;
        if (size > 0) {
          callback.setProgressFraction((double)count / size);
        }
        output.write(buf, 0, len);
      }
      output.close();
      output = null;
      LOG.debug("Downloading finished, " + size + " bytes downloaded");
      callback.finished(fileType);
    }
    catch (IOException e) {
      LOG.info(e);
      callback.errorOccured(VfsBundle.message("cannot.load.remote.file", url, e.getMessage()));
    }
    finally {
      if (input != null) {
        try {
          input.close();
        }
        catch (IOException e) {
          LOG.info(e);
        }
      }
      if (output != null) {
        try {
          output.close();
        }
        catch (IOException e) {
          LOG.info(e);
        }
      }
    }
  }

  public boolean isUpToDate(@NotNull final String url, @NotNull final VirtualFile local) {
    return false;
  }
}


text:
#ifndef OESTextureHalfFloatLinear_h
#define OESTextureHalfFloatLinear_h

#include "modules/webgl/WebGLExtension.h"
#include "wtf/PassRefPtr.h"

namespace blink {

class OESTextureHalfFloatLinear final : public WebGLExtension {
    DEFINE_WRAPPERTYPEINFO();
public:
    static PassRefPtrWillBeRawPtr<OESTextureHalfFloatLinear> create(WebGLRenderingContextBase*);
    static bool supported(WebGLRenderingContextBase*);
    static const char* extensionName();

    ~OESTextureHalfFloatLinear() override;
    WebGLExtensionName name() const override;

private:
    explicit OESTextureHalfFloatLinear(WebGLRenderingContextBase*);
};

} // namespace blink

#endif // OESTextureHalfFloatLinear_h


text:
class UnhandledController < ActionController::Base
  protect_from_forgery

  def index
    render json: {}
  end

  def error
    generate_unhandled_error
  end

  def error_in_active_record_callback
    User.class_eval do
      after_commit { raise 'Oh no!' }
    end

    user = User.new({
      email: "uuu3@example.com",
      name: "User U. User III",
      first_name: "User",
      last_name: "User"
    })

    user.save

    render json: {}
  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Michael Yeung's BLog</title>

    <link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet">

Technical Blog

Brief explanation: Recursion

SQL Issues

Blocks, Procs and Lambdas

Classes and their applications

Arrays vs Hashes

Why JavaScript is popular

HTML: Introduction to positioning

Three favorite websites

Cultural Blog

Asking questions

Dealing with conflict

Affirmation and stereotype threat

General stereotype threats

Pairing and giving feedbacks

Potential issue in tech: Compliance with local regulations

Thinking style

My biggest fears

My thoughts on DBC

Pairing and giving feedbacks

As a means to get to know each other and to practice coding in a team environment while clearly expressing our thoughts, we engage in pair programming sessions at least 2-3 times a week.

Inevitably, when pairing for the first time, I felt a bit uneasy. Perhaps the feeling is caused by a lack of confidence in my programming knowledge to take on the task, worrying about not being able to catch up with the peers' thought process, or, maybe simply don't want to get out of the comfort zone. These are probably some of the lots of feelings and worries I had when I first paired. However, pairing is actually much more interesting and engaging then expected, and I often found myself looking forward to the next session - to learn more, to practice more, and to help and be helped with new concepts. The overall experience is phenomenal. Even when we get stuck at certain problems or bugs, we would always gladly collaborate to tackle it, no matter how daunting the process may seem, because we know something new and interesting is just around the corner.

Another great thing about pairing is that it provides an opportunity to give and recieve feedback, which is essential if we want to improve and thrive. A good feedback has to be kind, actionable and specific. Kindness is very important here, as we all appreciate constructive comments, and it implies we have to give honest feedbacks, even if sometimes we have to be cruel to be kind. Acionable and specific feedbacks does not necessarily mean the recipient must follow certain steps, but would aid in working out the steps and plans to improve. When I receive such feedbacks, my appreciation is off the roof; normally who, other than your closest friends and family, would take the time to give you such honest and constructive feedbacks which purposes are to fuel your personal improvement? I reckon the feedbacks are some of the most valuable things we can receive.

reach me at: myeung58@gmail.com


text:
/*global $ */

$("[data-toggle=popover]").popover({
	container: "body"
});

$("#resumeLink").on("click", function(){
   $(this).addClass("orange");
   $("#imagesLink").removeClass("orange");
   $("#photoRow").hide();
   $("#resumeRow").show();
});

$("#imagesLink").on("click", function(){
   $(this).addClass("orange");
   $("#resumeLink").removeClass("orange");
   $("#resumeRow").hide();
   $("#photoRow").show();
});


text:
import argparse
import copy

"""
Changelog generation script, requires PAT see https://github.com/settings/tokens
Caveats V20 and prior release tags are tips on their respective release branches
If you try to use a start tag with one of these a full changelog will be generated
since the commit wont appear in your iterations

"""

try:
    from github import Github
    from mdutils import MdUtils
except BaseException:
    exit("Error: run 'pip install PyGithub mdutils'")

SECTIONS = {
    "Major Changes": [
        "major",
    ],
    "Protocol Changes": [
        "protocol change",
    ],
    "Node Configuration Updates": [
        "toml",
        "configuration default change",
    ],
    "RPC Updates": [
        "rpc",
    ],
    "IPC Updates": [
        "ipc",
    ],
    "Websocket Updates": [
        "websockets",
    ],
    "CLI Updates": [
        "cli",
    ],
    "Deprecation/Removal": [
        "deprecation",
        "removal",
    ],
    "Developer Wallet": [
        "qt wallet",
    ],
    "Developer/Debug Options": [
        "debug",
        "logging",
    ],
    "Fixed Bugs": [
        "bug",
    ],
    "Implemented Enhancements": [
        "enhancement",
        "functionality quality improvements",
        "non-functional change",
        "performance",
        "quality improvements",
    ],
    "Build, Test, Automation, & Chores": [
        "build-error",
        "documentation",
        "routine",
        "sanitizers",
        "static-analysis",
        "tool",
        "unit test",
        "universe",
    ],
    "Other": []
}

class cliArgs():
    def __init__(self):
        parse = argparse.ArgumentParser(
            prog="changelog",
            description="Generate Changelogs between tags or commits"
        )
        parse.add_argument(
            '-r', '--repo',
            help="<org/repo> to generate logs for",
            type=str, action="store",
            default='nanocurrency/nano-node',
        )
        parse.add_argument(
            '-s', '--start',
            help="Starting reference for Changelog",
            type=str, action="store",
            required=True,
        )
        parse.add_argument(
            '-e', '--end',
            help="Ending reference for Changelog",
            type=str, action="store",
            required=True,
        )
        parse.add_argument(
            '--pat',
            help="Personal Access Token",
            type=str, action="store",
            required=True,
        )
        options = parse.parse_args()
        self.repo = options.repo
        self.start = options.start
        self.end = options.end
        self.pat = options.pat

    def __repr__(self):
        return "<cliArgs(repo='{0}', start='{1}', end='{2}', pat='{3}')>" \
            .format(self.repo, self.start, self.end, self.pat)

    def __str__(self):
        return "Generating a changelog for {0} starting with {1} " \
            "and ending with {2}".format(self.repo, self.start, self.end)

class generateTree:
    def __init__(self, args):
        github = Github(args.pat)
        self.repo = github.get_repo(args.repo)
        self.start = args.start
        self.end = args.end
        try:
            self.startCommit = self.repo.get_commit(args.start)
        except BaseException:
            exit("Error finding commit for " + args.start)
        try:
            self.endCommit = self.repo.get_commit(args.end)
        except BaseException:
            exit("Error finding commit for " + args.end)
        commits = self.repo.get_commits(sha=self.endCommit.sha)
        self.commits = {}
        for commit in commits:
            if commit.sha == self.startCommit.sha:
                break
            else:
                for pull in commit.get_pulls():
                    labels = []
                    for label in pull.labels:
                        labels.append(label.name)
                    self.commits[pull.number] = {
                        "Title": pull.title,
                        "Url": pull.html_url,
                        "labels": labels
                    }

    def __repr__(self):
        return "<generateTree(repo='{0}', start='{1}', startCommit='{2}', " \
            "end='{3}', endCommit='{4}', tree='{5}', commits='{6}".format(
                self.repo, self.start, self.startCommit, self.end,
                self.endCommit, self.tree, self.commits,
            )

class generateMarkdown():
    def __repr__(self):
        return "<generateMarkdown(mdFile={0})>".format(
            self.mdFile
        )

    def __init__(self, repo):
        self.mdFile = MdUtils(
            file_name='CHANGELOG', title='CHANGELOG'
        )
        self.mdFile.new_line(
            "## **Release** " + \
            "[{0}](https://github.com/nanocurrency/nano-node/tree/{0})"\
                .format(repo.end))
        self.mdFile.new_line("[Full Changelog](https://github.com/nanocurrency"\
            "/nano-node/compare/{0}...{1})".format(repo.start, repo.end))
        sort = self.pull_to_section(repo.commits)

        for section, prs in sort.items():
            self.write_header(section)
            for pr in prs:
                self.write_PR(pr, repo.commits[pr[0]])
        self.mdFile.create_md_file()

    def write_header(self, section):
        self.mdFile.new_line("---")
        self.mdFile.new_header(level=3, title=section)
        self.mdFile.new_line(
            "|Pull Request|Title")
        self.mdFile.new_line("|:-:|:--")

    def write_PR(self, pr, info):
        imp = ""
        if pr[1]:
            imp = "**BREAKING** "
        self.mdFile.new_line(
            "|[#{0}]({1})|{2}{3}".format(
                pr[0], info['Url'], imp, info['Title']))

    def handle_labels(self, labels):
        for section, values in SECTIONS.items():
            for label in labels:
                if label in values:
                    if any(
                        string in labels for string in [
                            'breaking',
                            ]):
                        return section, True
                    else:
                        return section, False
        return 'Other', False

    def pull_to_section(self, commits):
        sect = copy.deepcopy(SECTIONS)
        result = {}
        for a in sect:
            sect[a] = []
        for pull, info in commits.items():
            section, important = self.handle_labels(info['labels'])
            if important:
                sect[section].insert(0,[pull, important])
            else:
                sect[section].append([pull, important])
        for a in sect:
            if len(sect[a]) > 0:
                result[a] = sect[a]
        return result

if __name__ == "__main__":
    args = cliArgs()
    repo = generateTree(args)
    generateMarkdown(repo)


text:
package com.igormaznitsa.ideamindmap.lang.tokens;

public class MMCodeSnippetBody extends MMElementType {
  public MMCodeSnippetBody() {
    super("CODESNIPPET_BODY");
  }

  @SuppressWarnings( {"HardCodedStringLiteral"})
  public String toString() {
    return "CodeSnippetBody:" + super.toString();
  }

}


text:
#ifndef Latin1TextIterator_h
#define Latin1TextIterator_h

#include "wtf/text/WTFString.h"

namespace blink {

class Latin1TextIterator {
public:
    // The passed in LChar pointer starts at 'currentCharacter'. The iterator operates on the range [currentCharacter, lastCharacter].
    // 'endCharacter' denotes the maximum length of the UChar array, which might exceed 'lastCharacter'.
    Latin1TextIterator(const LChar* characters, int currentCharacter, int lastCharacter, int /*endCharacter*/)
        : m_characters(characters)
        , m_currentCharacter(currentCharacter)
        , m_lastCharacter(lastCharacter)
    {
    }

    bool consume(UChar32& character, unsigned& clusterLength)
    {
        if (m_currentCharacter >= m_lastCharacter)
            return false;

        character = *m_characters;
        clusterLength = 1;
        return true;
    }

    void advance(unsigned advanceLength)
    {
        m_characters += advanceLength;
        m_currentCharacter += advanceLength;
    }

    int currentCharacter() const { return m_currentCharacter; }
    const LChar* characters() const { return m_characters; }

private:
    const LChar* m_characters;
    int m_currentCharacter;
    int m_lastCharacter;
};

} // namespace blink

#endif


text:
package x7c1.linen.database.struct

import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import x7c1.linen.repository.date.Date
import x7c1.wheat.macros.database.Query._
import x7c1.wheat.macros.database.{TypedCursor, TypedFields}
import x7c1.wheat.modern.database.Insertable
import x7c1.wheat.modern.database.selector.presets.{CanTraverseRecordByQuery, TraverseAll}
import x7c1.wheat.modern.database.selector.{RecordReifiable, SelectorProvidable}

trait InspectorSourceRecord extends TypedFields {
  def action_id: Long

  def source_loading_status: Int --> InspectorLoadingStatus

  def latent_source_url: String

  def discovered_source_id: Option[Long]

  def created_at: Int --> Date

  def updated_at: Int --> Date
}

object InspectorSourceRecord {
  def table = "inspector_sources"

  def column = TypedFields.expose[InspectorSourceRecord]

  implicit object providable
    extends SelectorProvidable[InspectorSourceRecord, Selector]

  implicit object reifiable extends RecordReifiable[InspectorSourceRecord] {
    override def reify(cursor: Cursor) = TypedCursor[InspectorSourceRecord](cursor)
  }

  implicit object traverseAll extends CanTraverseRecordByQuery[InspectorSourceRecord](
    sql"SELECT * FROM inspector_sources"
  )

  class Selector(protected val db: SQLiteDatabase)
    extends TraverseAll[InspectorSourceRecord]

}

case class InspectorSourceParts(
  actionId: Long,
  loadingStatus: InspectorLoadingStatus,
  latentUrl: String,
  discoveredSourceId: Option[Long],
  createdAt: Date,
  updatedAt: Date
)

object InspectorSourceParts {

  import InspectorSourceRecord.column

  implicit object insertable extends Insertable[InspectorSourceParts] {
    override def tableName: String = InspectorSourceRecord.table

    override def toContentValues(target: InspectorSourceParts): ContentValues =
      TypedFields.toContentValues(
        column.action_id -> target.actionId,
        column.source_loading_status -> target.loadingStatus,
        column.latent_source_url -> target.latentUrl,
        column.discovered_source_id -> target.discoveredSourceId,
        column.created_at -> target.createdAt,
        column.updated_at -> target.updatedAt
      )
  }

}


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class NoDatastoresConfiguredEvent extends HostEvent {
}


text:
spud.admin.banners = new function(){

  var self = this;
  var html5upload = false;
  var bannerEditId = false;

  this.init = function(){
    if(typeof(FormData) != 'undefined'){
      html5upload = true;
    }
    $('.spud_banner_add_new').on('click', self.clickedAddNewBanner);
    $('.spud_banner_set_banners_container').on('click', '.spud_banner_set_banner_item_edit', self.clickedEditBanner);
    $('.spud_banner_set_banners_container').on('click', '.spud_banner_set_banner_item_delete', self.clickedDeleteBanner);
    $('.modal-body').on('submit', '.spud_banner_form', self.submittedBannerForm);

    $('.spud_banner_set_banners_container').sortable({
      stop: self.sortedBanners
    });
  };

  self.clickedAddNewBanner = function(e){
    e.preventDefault();
    bannerEditId = false;
    $.ajax({
      url: $(this).attr('href'),
      dataType: 'html',
      success: function(html, textStatus, jqXHR){
        displayModalDialogWithOptions({
          title: 'Upload Banner',
          html: html
        });
      }
    });
  };

  self.clickedEditBanner = function(e){
    e.preventDefault();
    bannerEditId = parseInt($(this).parents('.spud_banner_set_banner_item').attr('data-id'), 10);
    $.ajax({
      url: $(this).attr('href'),
      dataType: 'html',
      success: function(html, textStatus, jqXHR){
        displayModalDialogWithOptions({
          title: 'Edit Banner',
          html: html
        });
      }
    });
  };

  self.clickedDeleteBanner = function(e){
    e.preventDefault();
    var el = $(this);
    $.ajax({
      url: el.attr('href'),
      type: 'post',
      data: {'_method':'delete'},
      complete: function(jqXHR, textStatus){
        var parent = el.parents('.spud_banner_set_banner_item');
        parent.fadeOut(200, function(){
          parent.remove();
        });
        if(textStatus != 'success'){
          console.warn('Something went wrong:', jqXHR);
        }
      }
    });
  };

  self.submittedBannerForm = function(e){
    if(html5upload){
      e.preventDefault();

      var form = $(this);
      var fd = new FormData();
      fd.append('_method', form.find('[name=_method]').val());
      fd.append('authenticity_token', form.find('[name=authenticity_token]').val());
      fd.append('spud_banner[link_to]', form.find('#spud_banner_link_to').val());
      fd.append('spud_banner[link_target]', form.find('#spud_banner_link_target').val());
      fd.append('spud_banner[title]', form.find('#spud_banner_title').val());
      fd.append('spud_banner[alt]', form.find('#spud_banner_alt').val());

      var file = form.find('#spud_banner_banner')[0].files[0];
      if(file){
        fd.append('spud_banner[banner]', file);
        $('.spud_banner_upload_progress').show();
      }

      var xhr = new XMLHttpRequest();
      xhr.upload.addEventListener('progress', self.onFileUploadProgress);
      xhr.addEventListener('load', self.onFileUploadComplete);
      xhr.addEventListener('error', self.onFileUploadError);
      xhr.addEventListener('abort', self.onFileUploadAbort);
      xhr.open('POST', form.attr('action'));
      xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
      xhr.send(fd);
      return false;
    }
  };

  self.onFileUploadProgress = function(e){
    var percent = Math.round(e.loaded * 100 / e.total);
    var progress = $('.spud_banner_upload_progress');
    progress.find('.bar').css({width: percent + '%'});
    if(percent == 100){
      progress.addClass('progress-success');
    }
  };

  self.onFileUploadComplete = function(e){
    switch(this.status){
      case 200:
        self.onLegacyUploadComplete(e.target.response);
        break;
      case 422:
        self.onLegacyUploadError(e.target.response);
        break;
      default:
        window.alert("Whoops! Something has gone wrong.");
    }
  };

  self.onFileUploadError = function(e){

  };

  self.onFileUploadAbort = function(e){

  };

  // Non-html5 upload
  self.onLegacyUploadComplete = function(html){
    if(bannerEditId){
      var item = $('.spud_admin_banner_item[data-id="'+bannerEditId+'"]');
      item.replaceWith(html);
    }
    else{
      $('.spud_banner_set_banners_container').append(html);
    }
    hideModalDialog();
  };

  self.onLegacyUploadError = function(html){
    $('.spud_banner_form').replaceWith(html);
  };

  self.sortedBanners = function(e, ui){
    var ids = [];
    $('.spud_banner_set_banner_item').each(function(){
      ids.push($(this).attr('data-id'));
    });
    $.ajax({
      url: '/spud/admin/banners/sort',
      type: 'post',
      data: {spud_banner_ids:ids, _method:'put'}
    });
  };
}();


text:
<?php

/**
 * Description of CustomCURL
 *
 * @author Mauricio Herrera <mwherrera@plus-projects.com>
 * @date 2/05/2014
 * ***************
 * @Version 2
 * @dateMod 15/05/2015
 */
class CustomCURL {

    static function Post($url, $data = "", $httpAuth = FALSE, $user = "", $password = "", $return = 1, $language = "es-ES,es", $encoding = 'gzip,deflate,sdch') {
        ob_start();
        $cURL = curl_init();
        curl_setopt($cURL, CURLOPT_URL, $url);
        curl_setopt($cURL, CURLOPT_USERAGENT, FRAME_NAME);
        curl_setopt($cURL, CURLOPT_HEADER, true);
        curl_setopt($cURL, CURLOPT_RETURNTRANSFER, $return);
        curl_setopt($cURL, CURLOPT_HTTPHEADER, array("Accept-Language: $language"));
        curl_setopt($cURL, CURLOPT_ENCODING, $encoding);

        curl_setopt($cURL, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

        curl_setopt($cURL, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($cURL, CURLOPT_FOLLOWLOCATION, 0);

        if ($httpAuth) {
            curl_setopt($cURL, CURLOPT_HEADER, false);
            curl_setopt($cURL, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($cURL, CURLOPT_USERPWD, "$user:$password");
        }

        curl_setopt($cURL, CURLOPT_POST, true);
        curl_setopt($cURL, CURLOPT_POSTFIELDS, $data);

        $response = curl_exec($cURL);
        curl_close($cURL);
        ob_end_flush();
        return $response;
    }

    static function SugarCall($url, $oauthtoken = '', $type = 'GET', $arguments = array(), $encodeData = true, $returnHeaders = false) {
        $type = strtoupper($type);
        if ($type == 'GET') {
            $url .= "?" . http_build_query($arguments);
        }
        $curl_request = curl_init($url);
        if ($type == 'POST') {
            curl_setopt($curl_request, CURLOPT_POST, 1);
        } elseif ($type == 'PUT') {
            curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "PUT");
        } elseif ($type == 'DELETE') {
            curl_setopt($curl_request, CURLOPT_CUSTOMREQUEST, "DELETE");
        }
        curl_setopt($curl_request, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
        curl_setopt($curl_request, CURLOPT_HEADER, $returnHeaders);
        curl_setopt($curl_request, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl_request, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl_request, CURLOPT_FOLLOWLOCATION, 0);
        if (!empty($oauthtoken)) {
            $token = array("oauth-token: {$oauthtoken}");
            curl_setopt($curl_request, CURLOPT_HTTPHEADER, $token);
        }
        if (!empty($arguments) && $type !== 'GET') {
            if ($encodeData) {
                //encode the arguments as JSON
                $arguments = json_encode($arguments);
            }
            curl_setopt($curl_request, CURLOPT_POSTFIELDS, $arguments);
        }
        $result = curl_exec($curl_request);
        if ($returnHeaders) {
            //set headers from response
            list($headers, $content) = explode("\r\n\r\n", $result, 2);
            foreach (explode("\r\n", $headers) as $header) {
                header($header);
            }
            //return the nonheader data
            return trim($content);
        }
        curl_close($curl_request);
        //decode the response from JSON
        $response = json_decode($result);
        return $response;
    }

}

?>


text:
set -euo pipefail

source bosh-cpi-src-in/ci/tasks/utils.sh

: ${BOSH_OPENSTACK_DOMAIN:?}
: ${BOSH_OPENSTACK_AUTH_URL_V3:?}
: ${BOSH_OPENSTACK_USERNAME_V3:?}
: ${BOSH_OPENSTACK_API_KEY_V3:?}
: ${BOSH_OPENSTACK_PROJECT:?}
: ${BOSH_CLI_SILENCE_SLOW_LOAD_WARNING:?}
: ${BOSH_OPENSTACK_CONNECT_TIMEOUT:?}
: ${BOSH_OPENSTACK_READ_TIMEOUT:?}
: ${BOSH_OPENSTACK_WRITE_TIMEOUT:?}
: ${BOSH_OPENSTACK_FLAVOR_WITH_NO_ROOT_DISK:?}
: ${BOSH_OPENSTACK_EXCLUDE_CINDER_V1:-""}
: ${BOSH_OPENSTACK_AUTH_URL_V2:-""}
: ${BOSH_OPENSTACK_USERNAME_V2:-""}
: ${BOSH_OPENSTACK_API_KEY_V2:-""}
: ${BOSH_OPENSTACK_TENANT:-""}
: ${BOSH_OPENSTACK_CA_CERT:-""}
: ${BOSH_OPENSTACK_VOLUME_TYPE:-""}

optional_value BOSH_OPENSTACK_AVAILABILITY_ZONE

metadata=terraform-cpi/metadata

export BOSH_OPENSTACK_MANUAL_IP=$(cat ${metadata} | jq --raw-output ".manual_ip")
export BOSH_OPENSTACK_ALLOWED_ADDRESS_PAIRS=$(cat ${metadata} | jq --raw-output ".allowed_address_pairs")
export BOSH_OPENSTACK_NO_DHCP_MANUAL_IP_1=$(cat ${metadata} | jq --raw-output ".no_dhcp_manual_ip_1")
export BOSH_OPENSTACK_NO_DHCP_MANUAL_IP_2=$(cat ${metadata} | jq --raw-output ".no_dhcp_manual_ip_2")
export BOSH_OPENSTACK_NET_ID=$(cat ${metadata} | jq --raw-output ".net_id")
export BOSH_OPENSTACK_NET_ID_NO_DHCP_1=$(cat ${metadata} | jq --raw-output ".net_id_no_dhcp_1")
export BOSH_OPENSTACK_NET_ID_NO_DHCP_2=$(cat ${metadata} | jq --raw-output ".net_id_no_dhcp_2")
export BOSH_OPENSTACK_DEFAULT_KEY_NAME=$(cat ${metadata} | jq --raw-output ".default_key_name")
export BOSH_OPENSTACK_FLOATING_IP=$(cat ${metadata} | jq --raw-output ".floating_ip")
export BOSH_OPENSTACK_SECURITY_GROUP_NAME=$(cat ${metadata} | jq --raw-output ".security_group_name")
export BOSH_OPENSTACK_SECURITY_GROUP_ID=$(cat ${metadata} | jq --raw-output ".security_group_id")
pool_name=$(cat ${metadata} | jq --raw-output ".loadbalancer_pool_name")
if [ "${pool_name}" != "" ]; then
  export BOSH_OPENSTACK_LBAAS_POOL_NAME=${pool_name}
fi

mkdir "${PWD}/openstack-lifecycle-stemcell/stemcell"
tar -C "${PWD}/openstack-lifecycle-stemcell/stemcell" -xzf "${PWD}/openstack-lifecycle-stemcell/stemcell.tgz"
export BOSH_OPENSTACK_STEMCELL_PATH="${PWD}/openstack-lifecycle-stemcell/stemcell"

cd bosh-cpi-src-in/src/bosh_openstack_cpi

bundle install

if [ -n "BOSH_OPENSTACK_EXCLUDE_CINDER_V1" ]; then
  rspec_args="--tag ~cinder_v1"
fi

if [ -n "${BOSH_OPENSTACK_AUTH_URL_V2}" ]; then
  bundle exec rspec -f d $rspec_args spec/integration 2>&1 | tee ../../../output/lifecycle.log
else
  echo "Excluding Keystone V2 tests."
  bundle exec rspec -f d $rspec_args spec/integration --exclude-pattern spec/integration/lifecycle_v2_spec.rb 2>&1 | tee ../../../output/lifecycle.log
fi


text:
package com.rtg.vcf.eval;

import static com.rtg.launcher.CommonFlags.FILE;
import static com.rtg.launcher.CommonFlags.NO_GZIP;
import static com.rtg.launcher.CommonFlags.OUTPUT_FLAG;
import static com.rtg.util.cli.CommonFlagCategories.INPUT_OUTPUT;
import static com.rtg.vcf.eval.VcfEvalCli.CRITERIA_PRECISION;
import static com.rtg.vcf.eval.VcfEvalCli.CRITERIA_SENSITIVITY;
import static com.rtg.vcf.eval.VcfEvalCli.ROC_EXPR;
import static com.rtg.vcf.eval.VcfEvalCli.ROC_REGIONS;
import static com.rtg.vcf.eval.VcfEvalCli.SCORE_FIELD;
import static com.rtg.vcf.eval.VcfEvalCli.SORT_ORDER;
import static com.rtg.vcf.eval.VcfEvalCli.validateScoreField;
import static com.rtg.vcf.eval.VcfEvalCli.validateVcfRocFlag;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.List;

import com.rtg.launcher.CommonFlags;
import com.rtg.launcher.LoggedCli;
import com.rtg.util.StringUtils;
import com.rtg.util.cli.CommonFlagCategories;
import com.rtg.util.diagnostic.Diagnostic;
import com.rtg.util.io.LogStream;
import com.rtg.vcf.VcfIterator;
import com.rtg.vcf.VcfReaderFactory;
import com.rtg.vcf.VcfRecord;
import com.rtg.vcf.VcfUtils;
import com.rtg.vcf.header.VcfHeader;

/**
 * Take one or more vcfeval annotated VCFs and produce rocplot compatible output files.
 * You need to ensure that both baseline and calls annotated VCFs are provided.
 */
public class Vcf2Rocplot extends LoggedCli {

  private RocContainer mRoc = null;
  private RocSortValueExtractor mRocExtractor = null;

  @Override
  public String moduleName() {
    return "vcf2rocplot";
  }

  @Override
  public String description() {
    return "produce rocplot compatible ROC data files from vcfeval annotated VCFs";
  }

  @Override
  protected File outputDirectory() {
    return (File) mFlags.getValue(OUTPUT_FLAG);
  }

  @Override
  protected void initFlags() {
    CommonFlagCategories.setCategories(mFlags);
    mFlags.setDescription(StringUtils.sentencify(description()));
    CommonFlags.initOutputDirFlag(mFlags);
    CommonFlags.initRegionOrBedRegionsFlags(mFlags);
    mFlags.registerRequired(File.class, FILE, "input VCF files containing vcfeval annotations")
      .setMinCount(1)
      .setMaxCount(Integer.MAX_VALUE)
      .setCategory(INPUT_OUTPUT);

    VcfEvalCli.registerVcfRocFlags(mFlags);

    CommonFlags.initThreadsFlag(mFlags);
    CommonFlags.initNoGzip(mFlags);
    mFlags.setValidator(flags -> CommonFlags.validateOutputDirectory(flags)
      && CommonFlags.validateInputFile(flags)
      && CommonFlags.validateThreads(flags)
      && CommonFlags.validateRegions(flags)
      && validateScoreField(flags)
      && validateVcfRocFlag(flags, ROC_EXPR)
      && validateVcfRocFlag(flags, ROC_REGIONS)
      && flags.checkInRange(CRITERIA_PRECISION, 0.0, 1.0)
      && flags.checkInRange(CRITERIA_SENSITIVITY, 0.0, 1.0)
    );
  }

  @Override
  protected int mainExec(OutputStream out, LogStream log) throws IOException {
    final boolean gzip = !mFlags.isSet(NO_GZIP);

    // Create ROC container / extractor
    mRocExtractor = RocSortValueExtractor.getRocSortValueExtractor((String) mFlags.getValue(SCORE_FIELD), (RocSortOrder) mFlags.getValue(SORT_ORDER));
    mRoc = new RocContainer(mRocExtractor);
    if (mFlags.isSet(CRITERIA_PRECISION)) {
      mRoc.setRocPointCriteria(new PrecisionThreshold((Double) mFlags.getValue(CRITERIA_PRECISION)));
    } else if (mFlags.isSet(CRITERIA_SENSITIVITY)) {
      mRoc.setRocPointCriteria(new SensitivityThreshold((Double) mFlags.getValue(CRITERIA_SENSITIVITY)));
    }
    mRoc.addFilters(VcfEvalCli.getRocFilters(mFlags));

    final Collection<?> values = mFlags.getAnonymousValues(0);
    for (final Object o : values) {
      final File vcf = (File) o;
      final VcfReaderFactory fact = new VcfReaderFactory(mFlags);
      try (final VcfIterator vr = fact.make(vcf)) {
        if (vr.getHeader().getInfoField(WithInfoEvalSynchronizer.INFO_CALL) != null
          || vr.getHeader().getInfoField(WithInfoEvalSynchronizer.INFO_BASE) != null) {
          Diagnostic.userLog("VCF file " + vcf + " looks to contain regular vcfeval annotation");
          loadWithInfoVariants(vr, vcf);
        } else if (vr.getHeader().getInfoField(Ga4ghEvalSynchronizer.FORMAT_DECISION) != null) {
          Diagnostic.userLog("VCF file " + vcf + " looks to contain GA4GH annotations");
          loadGa4ghVariants(vr);
        } else {
          Diagnostic.userLog("VCF file " + vcf + " doesn't look to contain any recognized annotations");
        }
      }
    }

    mRoc.missingScoreWarning();
    mRoc.writeRocs(outputDirectory(), gzip, false);
    mRoc.writeSummary(outputDirectory());

    return 0;
  }

  private void loadWithInfoVariants(VcfIterator vr, File vcf) throws IOException {
    final VcfHeader header = vr.getHeader();
    // If the VCF is from combined output, look up the appropriate sample indexes, otherwise assume 0
    final int bSample = getSampleIndex(header, CombinedEvalSynchronizer.SAMPLE_BASELINE);
    final int cSample = getSampleIndex(header, CombinedEvalSynchronizer.SAMPLE_CALLS);
    final boolean isCombined = bSample != 0 || cSample != 0;
    if (mRocExtractor.requiresSample()) {
      if (!isCombined && header.getNumberOfSamples() > 1) {
        Diagnostic.warning("VCF file " + vcf + " contains multiple samples, assuming first");
        // If this is wrong, the user should vcfsubset to pick out the sample they want.
      }
    }
    mRoc.filters().forEach(f -> f.setHeader(header));

    while (vr.hasNext()) {
      final VcfRecord rec = vr.next();

      final String base = rec.getInfo(WithInfoEvalSynchronizer.INFO_BASE);
      if (base != null) {
        switch (base) {
          case WithInfoEvalSynchronizer.STATUS_TP:
            mRoc.incrementBaselineCount(rec, bSample, true);
            break;
          case WithInfoEvalSynchronizer.STATUS_FN:
          case WithInfoEvalSynchronizer.STATUS_FN_CA:
            mRoc.incrementBaselineCount(rec, bSample, false);
            break;
          case WithInfoEvalSynchronizer.STATUS_OUTSIDE:
          case WithInfoEvalSynchronizer.STATUS_HARD:
          case WithInfoEvalSynchronizer.STATUS_IGNORED:
            // ignore these known values silently
            break;
          default:
            Diagnostic.warning("Unrecognized annotation for " + WithInfoEvalSynchronizer.INFO_BASE + " " + base);
            // ignore
        }
      }
      final String call = rec.getInfo(WithInfoEvalSynchronizer.INFO_CALL);
      if (call != null) {
        switch (call) {
          case WithInfoEvalSynchronizer.STATUS_TP:
            final double weight = VcfUtils.getDoubleInfoFieldFromRecord(rec, WithInfoEvalSynchronizer.INFO_CALL_WEIGHT);
            mRoc.addRocLine(rec, cSample, Double.isNaN(weight) ? 1 : weight, 0, 1);
            break;
          case WithInfoEvalSynchronizer.STATUS_FP:
          case WithInfoEvalSynchronizer.STATUS_FP_CA:
            mRoc.addRocLine(rec, cSample, 0, 1, 0);
            break;
          case WithInfoEvalSynchronizer.STATUS_OUTSIDE:
          case WithInfoEvalSynchronizer.STATUS_HARD:
          case WithInfoEvalSynchronizer.STATUS_IGNORED:
            // ignore these known values silently
            break;
          default:
            Diagnostic.warning("Unrecognized annotation for " + WithInfoEvalSynchronizer.INFO_CALL + " " + call);
            // ignore
        }
      }
    }
  }

  private void loadGa4ghVariants(VcfIterator vr) throws IOException {
    while (vr.hasNext()) {
      final VcfRecord rec = vr.next();

      final List<String> decision = rec.getFormat(Ga4ghEvalSynchronizer.FORMAT_DECISION);
      if (decision == null) {
        continue;
      }

      switch (decision.get(Ga4ghEvalSynchronizer.TRUTH_SAMPLE_INDEX)) {
        case Ga4ghEvalSynchronizer.DECISION_TP:
          mRoc.incrementBaselineCount(rec, Ga4ghEvalSynchronizer.TRUTH_SAMPLE_INDEX, true);
          break;
        case Ga4ghEvalSynchronizer.DECISION_FN:
          mRoc.incrementBaselineCount(rec, Ga4ghEvalSynchronizer.TRUTH_SAMPLE_INDEX, false);
          break;
        default:
          // ignore
      }
      switch (decision.get(Ga4ghEvalSynchronizer.QUERY_SAMPLE_INDEX)) {
        case Ga4ghEvalSynchronizer.DECISION_TP:
          mRoc.addRocLine(rec, Ga4ghEvalSynchronizer.QUERY_SAMPLE_INDEX, 1, 0, 1);
          break;
        case Ga4ghEvalSynchronizer.DECISION_FP:
          mRoc.addRocLine(rec, Ga4ghEvalSynchronizer.QUERY_SAMPLE_INDEX, 0, 1, 0);
          break;
        default:
          // ignore
      }
    }
  }

  // Find the named sample or 0 otherwise
  private int getSampleIndex(VcfHeader header, String sample) {
    final int index = header.getSampleIndex(sample);
    return index == -1 ? 0 : index;
  }

}