text:
"""MyTardis NGS Ingestor

Client for https://github.com/mytardis/mytardis
and https://github.com/pansapiens/mytardis-seqfac
"""

from setuptools import setup, find_packages
from codecs import open
from os import path
import mytardis_ngs_ingestor

here = path.abspath(path.dirname(__file__))

def get_requirements():
    with open(path.join(here, 'requirements.txt'), 'r') as f:
        install_reqs = [
            s for s in [
                line.strip(' \n') for line in f
            ] if not s.startswith('#') and s != ''
        ]
    return install_reqs

with open(path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='mytardis_ngs_ingestor',
    version=mytardis_ngs_ingestor.__version__,

    description='MyTardis NGS Ingestor',
    long_description=long_description,
    url='https://github.com/pansapiens/mytardis_ngs_ingestor',

    author='Andrew Perry',
    author_email='Andrew.Perry@monash.edu',

    license='MIT',

    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        # How mature is this project? Common values are
        #   3 - Alpha
        #   4 - Beta
        #   5 - Production/Stable
        'Development Status :: 3 - Alpha',

        # Indicate who your project is intended for
        'Intended Audience :: Science/Research',
        'Intended Audience :: System Administrators',
        'Topic :: Scientific/Engineering :: Bio-Informatics'

        # Pick your license as you wish (should match "license" above)
        'License :: OSI Approved :: MIT License',

        # Specify the Python versions you support here. In particular, ensure
        # that you indicate whether you support Python 2, Python 3 or both.
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 2.7',
        # 'Programming Language :: Python :: 3',
        # 'Programming Language :: Python :: 3.2',
        # 'Programming Language :: Python :: 3.3',
        # 'Programming Language :: Python :: 3.4',
    ],

    keywords='DNA RNA bioinformatics sequencing illumina client api data files',

    # You can just specify the packages manually here if your project is
    # simple. Or you can use find_packages().
    packages=find_packages(exclude=['contrib', 'docs', 'tests*']),

    # List run-time dependencies here.  These will be installed by pip when
    # your project is installed. For an analysis of "install_requires" vs pip's
    # requirements files see:
    # https://packaging.python.org/en/latest/requirements.html
    install_requires=get_requirements(),

    # List additional groups of dependencies here (e.g. development
    # dependencies). You can install these using the following syntax,
    # for example:
    # $ pip install -e .[dev,test]
    extras_require={
        'dev': ['prospector',
                'check-manifest'],
        'test': ['tox',
                 'pytest'
                 'coverage',
                 'requests_mock'],
    },

    # If there are data files included in your packages that need to be
    # installed, specify them here.  If using Python 2.6 or less, then these
    # have to be included in MANIFEST.in as well.
    # package_data={
    #      'sample': ['sample.dat'],
    # },

    # Although 'package_data' is the preferred approach, in some case you may
    # need to place data files outside of your packages. See:
    # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa
    # In this case, 'data_file' will be installed into '<sys.prefix>/my_data'
    # data_files=[('my_data', ['data/data_file'])],

    # To provide executable scripts, use entry points in preference to the
    # "scripts" keyword. Entry points provide cross-platform support and allow
    # pip to create the appropriate form of executable for the target platform.
    entry_points={
        'console_scripts': [
            'illumina_uploader='
            'mytardis_ngs_ingestor.illumina_uploader:run_in_console',
            'illumina_autoprocess='
            'mytardis_ngs_ingestor.autoprocessing.autoprocess:run_in_console',
        ],
    },
    test_suite='tests',
)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ChangeListManager">
    <list default="true" id="ba4cf2a1-58da-467c-8f1c-68cec2ad6218" name="Default" comment="" />
    <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
    <option name="TRACKING_ENABLED" value="true" />
    <option name="SHOW_DIALOG" value="false" />
    <option name="HIGHLIGHT_CONFLICTS" value="true" />
    <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
    <option name="LAST_RESOLUTION" value="IGNORE" />
  </component>
  <component name="CreatePatchCommitExecutor">
    <option name="PATCH_PATH" value="" />
  </component>
  <component name="DatabaseView">
    <option name="GROUP_SCHEMA" value="true" />
    <option name="GROUP_CONTENTS" value="false" />
    <option name="SORT_POSITIONED" value="false" />
    <option name="SHOW_TABLE_DETAILS" value="true" />
    <option name="SHOW_EMPTY_GROUPS" value="false" />
    <option name="AUTO_SCROLL_FROM_SOURCE" value="false" />
  </component>
  <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" />
  <component name="FavoritesManager">
    <favorites_list name="startbootstrap-freelancer-gh-pages" />
  </component>
  <component name="FileEditorManager">
    <leaf>
      <file leaf-file-name="README.md" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/README.md">
          <provider selected="true" editor-type-id="split-provider[text-editor;markdown-preview-editor]">
            <state split_layout="SPLIT">
              <first_editor relative-caret-position="456">
                <caret line="24" column="24" lean-forward="true" selection-start-line="24" selection-start-column="24" selection-end-line="24" selection-end-column="24" />
                <folding />
              </first_editor>
              <second_editor />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="contact_me.php" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/mail/contact_me.php">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="171">
              <caret line="9" column="17" lean-forward="true" selection-start-line="9" selection-start-column="17" selection-end-line="9" selection-end-column="17" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="package.json" pinned="false" current-in-tab="false">
        <entry file="file://$PROJECT_DIR$/package.json">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="0">
              <caret line="0" column="0" lean-forward="false" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
      <file leaf-file-name="index.html" pinned="false" current-in-tab="true">
        <entry file="file://$PROJECT_DIR$/index.html">
          <provider selected="true" editor-type-id="text-editor">
            <state relative-caret-position="570">
              <caret line="240" column="34" lean-forward="true" selection-start-line="240" selection-start-column="34" selection-end-line="240" selection-end-column="34" />
              <folding />
            </state>
          </provider>
        </entry>
      </file>
    </leaf>
  </component>
  <component name="IdeDocumentHistory">
    <option name="CHANGED_PATHS">
      <list>
        <option value="$PROJECT_DIR$/index.html" />
      </list>
    </option>
  </component>
  <component name="JsBuildToolGruntFileManager" detection-done="true" sorting="DEFINITION_ORDER" />
  <component name="JsBuildToolPackageJson" detection-done="true" sorting="DEFINITION_ORDER" />
  <component name="JsGulpfileManager">
    <detection-done>true</detection-done>
    <gulpfiles>
      <GulpfileState>
        <gulpfile-path>$PROJECT_DIR$/gulpfile.js</gulpfile-path>
      </GulpfileState>
    </gulpfiles>
    <sorting>DEFINITION_ORDER</sorting>
  </component>
  <component name="PhpWorkspaceProjectConfiguration" backward_compatibility_performed="true" />
  <component name="ProjectFrameBounds">
    <option name="x" value="-8" />
    <option name="y" value="-8" />
    <option name="width" value="1936" />
    <option name="height" value="1034" />
  </component>
  <component name="ProjectView">
    <navigator currentView="ProjectPane" proportions="" version="1">
      <flattenPackages />
      <showMembers />
      <showModules />
      <showLibraryContents />
      <hideEmptyPackages />
      <abbreviatePackageNames />
      <autoscrollToSource />
      <autoscrollFromSource />
      <sortByType />
      <manualOrder />
      <foldersAlwaysOnTop value="true" />
    </navigator>
    <panes>
      <pane id="ProjectPane">
        <subPane>
          <PATH>
            <PATH_ELEMENT>
              <option name="myItemId" value="startbootstrap-freelancer-gh-pages" />
              <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" />
            </PATH_ELEMENT>
            <PATH_ELEMENT>
              <option name="myItemId" value="startbootstrap-freelancer-gh-pages" />
              <option name="myItemType" value="com.jetbrains.php.projectView.PhpTreeStructureProvider$1" />
            </PATH_ELEMENT>
          </PATH>
        </subPane>
      </pane>
      <pane id="Scope" />
      <pane id="Scratches" />
    </panes>
  </component>
  <component name="PropertiesComponent">
    <property name="WebServerToolWindowFactoryState" value="false" />
    <property name="nodejs_interpreter_path" value="C:/Program Files/nodejs/node" />
    <property name="js.eslint.eslintPackage" value="" />
    <property name="settings.editor.selected.configurable" value="reference.settingsdialog.IDE.editor.colors" />
    <property name="js-jscs-nodeInterpreter" value="C:\Program Files\nodejs\node.exe" />
  </component>
  <component name="RunManager">
    <configuration default="true" type="JavaScriptTestRunnerProtractor" factoryName="Protractor">
      <config-file value="" />
      <node-interpreter value="project" />
      <envs />
      <method />
    </configuration>
    <configuration default="true" type="JavascriptDebugType" factoryName="JavaScript Debug">
      <method />
    </configuration>
    <configuration default="true" type="NodeJSConfigurationType" factoryName="Node.js" path-to-node="project" working-dir="">
      <method />
    </configuration>
    <configuration default="true" type="PHPUnitRunConfigurationType" factoryName="PHPUnit">
      <TestRunner />
      <method />
    </configuration>
    <configuration default="true" type="PhpBehatConfigurationType" factoryName="Behat">
      <BehatRunner />
      <method />
    </configuration>
    <configuration default="true" type="PhpLocalRunConfigurationType" factoryName="PHP Console">
      <method />
    </configuration>
    <configuration default="true" type="PhpSpecConfigurationType" factoryName="PHPSpec">
      <PhpTestRunnerSettings />
      <method />
    </configuration>
    <configuration default="true" type="js.build_tools.gulp" factoryName="Gulp.js">
      <method />
    </configuration>
    <configuration default="true" type="js.build_tools.npm" factoryName="npm">
      <command value="run" />
      <scripts />
      <node-interpreter value="project" />
      <envs />
      <method />
    </configuration>
    <configuration default="true" type="mocha-javascript-test-runner" factoryName="Mocha">
      <node-interpreter>project</node-interpreter>
      <node-options />
      <working-directory />
      <pass-parent-env>true</pass-parent-env>
      <envs />
      <ui />
      <extra-mocha-options />
      <test-kind>DIRECTORY</test-kind>
      <test-directory />
      <recursive>false</recursive>
      <method />
    </configuration>
  </component>
  <component name="ShelveChangesManager" show_recycled="false">
    <option name="remove_strategy" value="false" />
  </component>
  <component name="TaskManager">
    <task active="true" id="Default" summary="Default task">
      <changelist id="ba4cf2a1-58da-467c-8f1c-68cec2ad6218" name="Default" comment="" />
      <created>1484530468889</created>
      <option name="number" value="Default" />
      <option name="presentableId" value="Default" />
      <updated>1484530468889</updated>
      <workItem from="1484530470810" duration="1379000" />
    </task>
    <servers />
  </component>
  <component name="TimeTrackingManager">
    <option name="totallyTimeSpent" value="1379000" />
  </component>
  <component name="TodoView">
    <todo-panel id="selected-file">
      <is-autoscroll-to-source value="true" />
    </todo-panel>
    <todo-panel id="all">
      <are-packages-shown value="true" />
      <is-autoscroll-to-source value="true" />
    </todo-panel>
  </component>
  <component name="ToolWindowManager">
    <frame x="-8" y="-8" width="1936" height="1034" extended-state="6" />
    <editor active="true" />
    <layout>
      <window_info id="Gulp" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
      <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" show_stripe_button="true" weight="0.09791667" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" />
      <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" />
      <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
      <window_info id="Database" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" />
      <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
      <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" />
      <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" />
      <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" />
      <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" />
      <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" />
      <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" />
      <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" />
      <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" show_stripe_button="true" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" />
    </layout>
  </component>
  <component name="TypeScriptGeneratedFilesManager">
    <option name="processedProjectFiles" value="true" />
  </component>
  <component name="VcsContentAnnotationSettings">
    <option name="myLimit" value="2678400000" />
  </component>
  <component name="XDebuggerManager">
    <breakpoint-manager />
    <watches-manager />
  </component>
  <component name="editorHistoryManager">
    <entry file="file://$PROJECT_DIR$/package.json">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="0">
          <caret line="0" column="0" lean-forward="false" selection-start-line="0" selection-start-column="0" selection-end-line="0" selection-end-column="0" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/README.md">
      <provider selected="true" editor-type-id="split-provider[text-editor;markdown-preview-editor]">
        <state split_layout="SPLIT">
          <first_editor relative-caret-position="456">
            <caret line="24" column="24" lean-forward="true" selection-start-line="24" selection-start-column="24" selection-end-line="24" selection-end-column="24" />
            <folding />
          </first_editor>
          <second_editor />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/mail/contact_me.php">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="171">
          <caret line="9" column="17" lean-forward="true" selection-start-line="9" selection-start-column="17" selection-end-line="9" selection-end-column="17" />
          <folding />
        </state>
      </provider>
    </entry>
    <entry file="file://$PROJECT_DIR$/index.html">
      <provider selected="true" editor-type-id="text-editor">
        <state relative-caret-position="570">
          <caret line="240" column="34" lean-forward="true" selection-start-line="240" selection-start-column="34" selection-end-line="240" selection-end-column="34" />
          <folding />
        </state>
      </provider>
    </entry>
  </component>
</project>

redpajama_set_name: RedPajamaGithub


text:
package server

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"math/big"
	"net/http"
	"net/url"
	"strings"
	"sync"
	"time"

	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"

	"github.com/livepeer/go-livepeer/clog"
	"github.com/livepeer/go-livepeer/common"
	"github.com/livepeer/go-livepeer/core"
	"github.com/livepeer/go-livepeer/net"
	"github.com/livepeer/go-livepeer/pm"
	"github.com/livepeer/go-tools/drivers"
	ffmpeg "github.com/livepeer/lpms/ffmpeg"
	"github.com/livepeer/lpms/stream"
	"github.com/patrickmn/go-cache"

	ethcommon "github.com/ethereum/go-ethereum/common"
	"github.com/ethereum/go-ethereum/common/hexutil"
	"github.com/ethereum/go-ethereum/crypto"

	"github.com/golang/glog"
	"github.com/pkg/errors"
)

const GRPCConnectTimeout = 3 * time.Second
const GRPCTimeout = 8 * time.Second
const HTTPIdleTimeout = 10 * time.Minute

var authTokenValidPeriod = 30 * time.Minute
var discoveryAuthWebhookCacheCleanup = 5 * time.Minute

var discoveryAuthWebhookCache = cache.New(authTokenValidPeriod, discoveryAuthWebhookCacheCleanup)

type Orchestrator interface {
	ServiceURI() *url.URL
	Address() ethcommon.Address
	TranscoderSecret() string
	Sign([]byte) ([]byte, error)
	VerifySig(ethcommon.Address, string, []byte) bool
	CheckCapacity(core.ManifestID) error
	TranscodeSeg(context.Context, *core.SegTranscodingMetadata, *stream.HLSSegment) (*core.TranscodeResult, error)
	ServeTranscoder(stream net.Transcoder_RegisterTranscoderServer, capacity int, capabilities *net.Capabilities)
	TranscoderResults(job int64, res *core.RemoteTranscoderResult)
	ProcessPayment(ctx context.Context, payment net.Payment, manifestID core.ManifestID) error
	TicketParams(sender ethcommon.Address, priceInfo *net.PriceInfo) (*net.TicketParams, error)
	PriceInfo(sender ethcommon.Address) (*net.PriceInfo, error)
	SufficientBalance(addr ethcommon.Address, manifestID core.ManifestID) bool
	DebitFees(addr ethcommon.Address, manifestID core.ManifestID, price *net.PriceInfo, pixels int64)
	Capabilities() *net.Capabilities
	AuthToken(sessionID string, expiration int64) *net.AuthToken
}

// Balance describes methods for a session's balance maintenance
type Balance interface {
	Credit(amount *big.Rat)
	StageUpdate(minCredit *big.Rat, ev *big.Rat) (int, *big.Rat, *big.Rat)
}

// BalanceUpdateStatus indicates the current status of a balance update
type BalanceUpdateStatus int

const (
	// Staged indicates that the update has been created but the credit
	// has not been spent yet
	Staged = iota
	// CreditSpent indicates that the update's credit has been spent
	// but the debit has not been processed yet
	CreditSpent
	// ReceivedChange indicates that the update's credit has been spent
	// and a debit was processed such that there was "change" (net of credit/debit)
	ReceivedChange
)

// BalanceUpdate describes an update to be performed on the balance of a session
type BalanceUpdate struct {
	// ExistingCredit is the existing credit reserved for the update
	ExistingCredit *big.Rat

	// NewCredit is the new credit for the update provided by a payment
	NewCredit *big.Rat

	// NumTickets is the number of tickets in the payment for the update
	NumTickets int

	// Debit is the amount to debit for the update
	Debit *big.Rat

	// Status is the current status of the update
	Status BalanceUpdateStatus
}

// BroadcastSession - session-specific state for broadcasters
type BroadcastSession struct {
	Broadcaster              common.Broadcaster
	Params                   *core.StreamParameters
	BroadcasterOS            drivers.OSSession
	Sender                   pm.Sender
	Balances                 *core.AddressBalances
	OrchestratorScore        float32
	VerifiedByPerceptualHash bool
	lock                     *sync.RWMutex
	// access these fields under the lock
	SegsInFlight     []SegFlightMetadata
	LatencyScore     float64
	OrchestratorInfo *net.OrchestratorInfo
	OrchestratorOS   drivers.OSSession
	PMSessionID      string
	Balance          Balance
}

func (bs *BroadcastSession) Transcoder() string {
	bs.lock.RLock()
	defer bs.lock.RUnlock()
	return bs.OrchestratorInfo.Transcoder
}

func (bs *BroadcastSession) Address() string {
	bs.lock.RLock()
	defer bs.lock.RUnlock()
	return hexutil.Encode(bs.OrchestratorInfo.Address)
}

func (bs *BroadcastSession) Clone() *BroadcastSession {
	bs.lock.RLock()
	newSess := *bs
	newSess.lock = &sync.RWMutex{}
	bs.lock.RUnlock()
	return &newSess
}

func (bs *BroadcastSession) IsTrusted() bool {
	return bs.OrchestratorScore == common.Score_Trusted
}

// ReceivedTranscodeResult contains received transcode result data and related metadata
type ReceivedTranscodeResult struct {
	*net.TranscodeData
	Info         *net.OrchestratorInfo
	LatencyScore float64
}

type lphttp struct {
	orchestrator Orchestrator
	orchRPC      *grpc.Server
	transRPC     *http.ServeMux
	node         *core.LivepeerNode
}

func (h *lphttp) EndTranscodingSession(ctx context.Context, request *net.EndTranscodingSessionRequest) (*net.EndTranscodingSessionResponse, error) {
	return endTranscodingSession(h.node, h.orchestrator, request)
}

// grpc methods
func (h *lphttp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	ct := r.Header.Get("Content-Type")
	if r.ProtoMajor == 2 && strings.HasPrefix(ct, "application/grpc") {
		h.orchRPC.ServeHTTP(w, r)
	} else {
		h.transRPC.ServeHTTP(w, r)
	}
}

func (h *lphttp) GetOrchestrator(context context.Context, req *net.OrchestratorRequest) (*net.OrchestratorInfo, error) {
	return getOrchestrator(h.orchestrator, req)
}

func (h *lphttp) Ping(context context.Context, req *net.PingPong) (*net.PingPong, error) {
	return ping(context, req, h.orchestrator)
}

// XXX do something about the implicit start of the http mux? this smells
func StartTranscodeServer(orch Orchestrator, bind string, mux *http.ServeMux, workDir string, acceptRemoteTranscoders bool, n *core.LivepeerNode) error {
	s := grpc.NewServer()
	lp := lphttp{
		orchestrator: orch,
		orchRPC:      s,
		transRPC:     mux,
		node:         n,
	}
	net.RegisterOrchestratorServer(s, &lp)
	lp.transRPC.HandleFunc("/segment", lp.ServeSegment)
	if acceptRemoteTranscoders {
		net.RegisterTranscoderServer(s, &lp)
		lp.transRPC.HandleFunc("/transcodeResults", lp.TranscodeResults)
	}

	cert, key, err := getCert(orch.ServiceURI(), workDir)
	if err != nil {
		return err
	}

	glog.Info("Listening for RPC on ", bind)
	srv := http.Server{
		Addr:        bind,
		Handler:     &lp,
		IdleTimeout: HTTPIdleTimeout,
	}
	return srv.ListenAndServeTLS(cert, key)
}

// CheckOrchestratorAvailability - the broadcaster calls CheckOrchestratorAvailability which invokes Ping on the orchestrator
func CheckOrchestratorAvailability(orch Orchestrator) bool {
	ts := time.Now()
	tsSignature, err := orch.Sign([]byte(fmt.Sprintf("%v", ts)))
	if err != nil {
		return false
	}

	ping := crypto.Keccak256(tsSignature)

	orchClient, conn, err := startOrchestratorClient(context.Background(), orch.ServiceURI())
	if err != nil {
		return false
	}
	defer conn.Close()

	ctx, cancel := context.WithTimeout(context.Background(), GRPCTimeout)
	defer cancel()

	pong, err := orchClient.Ping(ctx, &net.PingPong{Value: ping})
	if err != nil {
		glog.Error("Was not able to submit Ping: ", err)
		return false
	}

	return orch.VerifySig(orch.Address(), string(ping), pong.Value)
}

func ping(context context.Context, req *net.PingPong, orch Orchestrator) (*net.PingPong, error) {
	glog.Info("Received Ping request")
	value, err := orch.Sign(req.Value)
	if err != nil {
		glog.Error("Unable to sign Ping request")
		return nil, err
	}
	return &net.PingPong{Value: value}, nil
}

// GetOrchestratorInfo - the broadcaster calls GetOrchestratorInfo which invokes GetOrchestrator on the orchestrator
func GetOrchestratorInfo(ctx context.Context, bcast common.Broadcaster, orchestratorServer *url.URL) (*net.OrchestratorInfo, error) {
	c, conn, err := startOrchestratorClient(ctx, orchestratorServer)
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	req, err := genOrchestratorReq(bcast)
	r, err := c.GetOrchestrator(ctx, req)
	if err != nil {
		return nil, errors.Wrapf(err, "Could not get orchestrator orch=%v", orchestratorServer)
	}

	return r, nil
}

// EndSession - the broadcaster calls EndTranscodingSession to tear down sessions used for verification only once
func EndTranscodingSession(ctx context.Context, sess *BroadcastSession) error {
	uri, err := url.Parse(sess.Transcoder())
	if err != nil {
		return err
	}
	c, conn, err := startOrchestratorClient(ctx, uri)
	if err != nil {
		return err
	}
	defer conn.Close()

	req, err := genEndSessionRequest(sess)
	_, err = c.EndTranscodingSession(ctx, req)
	if err != nil {
		return errors.Wrapf(err, "Could not end orchestrator session orch=%v", sess.Transcoder())
	}
	return nil
}

func startOrchestratorClient(ctx context.Context, uri *url.URL) (net.OrchestratorClient, *grpc.ClientConn, error) {
	clog.V(common.DEBUG).Infof(ctx, "Connecting RPC to uri=%v", uri)
	conn, err := grpc.Dial(uri.Host,
		grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
		grpc.WithBlock(),
		grpc.WithTimeout(GRPCConnectTimeout))
	if err != nil {
		return nil, nil, errors.Wrapf(err, "Did not connect to orch=%v", uri)

	}
	c := net.NewOrchestratorClient(conn)

	return c, conn, nil
}

func genOrchestratorReq(b common.Broadcaster) (*net.OrchestratorRequest, error) {
	sig, err := b.Sign([]byte(fmt.Sprintf("%v", b.Address().Hex())))
	if err != nil {
		return nil, err
	}
	return &net.OrchestratorRequest{Address: b.Address().Bytes(), Sig: sig}, nil
}

func genEndSessionRequest(sess *BroadcastSession) (*net.EndTranscodingSessionRequest, error) {
	return &net.EndTranscodingSessionRequest{AuthToken: sess.OrchestratorInfo.AuthToken}, nil
}

func getOrchestrator(orch Orchestrator, req *net.OrchestratorRequest) (*net.OrchestratorInfo, error) {
	addr := ethcommon.BytesToAddress(req.Address)
	if err := verifyOrchestratorReq(orch, addr, req.Sig); err != nil {
		return nil, fmt.Errorf("Invalid orchestrator request: %v", err)
	}

	if _, err := authenticateBroadcaster(addr.Hex()); err != nil {
		return nil, fmt.Errorf("authentication failed: %v", err)
	}

	// currently, orchestrator == transcoder
	return orchestratorInfo(orch, addr, orch.ServiceURI().String())
}

func endTranscodingSession(node *core.LivepeerNode, orch Orchestrator, req *net.EndTranscodingSessionRequest) (*net.EndTranscodingSessionResponse, error) {
	verifyToken := orch.AuthToken(req.AuthToken.SessionId, req.AuthToken.Expiration)
	if !bytes.Equal(verifyToken.Token, req.AuthToken.Token) {
		return nil, fmt.Errorf("Invalid auth token")
	}
	node.EndTranscodingSession(req.AuthToken.SessionId)
	return &net.EndTranscodingSessionResponse{}, nil
}

func getPriceInfo(orch Orchestrator, addr ethcommon.Address) (*net.PriceInfo, error) {
	if AuthWebhookURL != nil {
		webhookRes := getFromDiscoveryAuthWebhookCache(addr.Hex())
		if webhookRes != nil && webhookRes.PriceInfo != nil {
			return webhookRes.PriceInfo, nil
		}
	}
	return orch.PriceInfo(addr)
}

func orchestratorInfo(orch Orchestrator, addr ethcommon.Address, serviceURI string) (*net.OrchestratorInfo, error) {
	priceInfo, err := getPriceInfo(orch, addr)
	if err != nil {
		return nil, err
	}

	params, err := orch.TicketParams(addr, priceInfo)
	if err != nil {
		return nil, err
	}

	// Generate auth token
	sessionID := string(core.RandomManifestID())
	expiration := time.Now().Add(authTokenValidPeriod).Unix()
	authToken := orch.AuthToken(sessionID, expiration)

	tr := net.OrchestratorInfo{
		Transcoder:   serviceURI,
		TicketParams: params,
		PriceInfo:    priceInfo,
		Address:      orch.Address().Bytes(),
		Capabilities: orch.Capabilities(),
		AuthToken:    authToken,
	}

	os := drivers.NodeStorage.NewSession(authToken.SessionId)

	if os != nil {
		if os.IsExternal() {
			tr.Storage = []*net.OSInfo{core.ToNetOSInfo(os.GetInfo())}
		} else {
			os.EndSession()
		}
	}

	return &tr, nil
}

func verifyOrchestratorReq(orch Orchestrator, addr ethcommon.Address, sig []byte) error {
	if !orch.VerifySig(addr, addr.Hex(), sig) {
		glog.Error("orchestrator req sig check failed")
		return fmt.Errorf("orchestrator req sig check failed")
	}
	return orch.CheckCapacity("")
}

type discoveryAuthWebhookRes struct {
	PriceInfo *net.PriceInfo `json:"priceInfo,omitempty"`
}

// authenticateBroadcaster returns an error if authentication fails
// on success it caches the webhook response
func authenticateBroadcaster(id string) (*discoveryAuthWebhookRes, error) {
	if AuthWebhookURL == nil {
		return nil, nil
	}

	values := map[string]string{"id": id}
	jsonValues, err := json.Marshal(values)
	if err != nil {
		return nil, err
	}
	res, err := http.Post(AuthWebhookURL.String(), "application/json", bytes.NewBuffer(jsonValues))
	if err != nil {
		return nil, err
	}

	body, err := ioutil.ReadAll(res.Body)
	defer res.Body.Close()
	if err != nil {
		return nil, err
	}

	if res.StatusCode != 200 {
		return nil, errors.New(string(body))
	}

	webhookRes := &discoveryAuthWebhookRes{}
	if err := json.Unmarshal(body, webhookRes); err != nil {
		return nil, err
	}

	addToDiscoveryAuthWebhookCache(id, webhookRes, authTokenValidPeriod)

	return webhookRes, nil
}

func addToDiscoveryAuthWebhookCache(id string, webhookRes *discoveryAuthWebhookRes, expiration time.Duration) {
	_, ok := discoveryAuthWebhookCache.Get(id)
	if ok {
		discoveryAuthWebhookCache.Replace(id, webhookRes, authTokenValidPeriod)
	} else {
		discoveryAuthWebhookCache.Add(id, webhookRes, authTokenValidPeriod)
	}
}

func getFromDiscoveryAuthWebhookCache(id string) *discoveryAuthWebhookRes {
	c, ok := discoveryAuthWebhookCache.Get(id)
	if !ok {
		return nil
	}
	webhookRes, ok := c.(*discoveryAuthWebhookRes)
	if !ok {
		return nil
	}
	return webhookRes
}

func pmTicketParams(params *net.TicketParams) *pm.TicketParams {
	if params == nil {
		return nil
	}

	return &pm.TicketParams{
		Recipient:         ethcommon.BytesToAddress(params.Recipient),
		FaceValue:         new(big.Int).SetBytes(params.FaceValue),
		WinProb:           new(big.Int).SetBytes(params.WinProb),
		RecipientRandHash: ethcommon.BytesToHash(params.RecipientRandHash),
		Seed:              new(big.Int).SetBytes(params.Seed),
		ExpirationBlock:   new(big.Int).SetBytes(params.ExpirationBlock),
		ExpirationParams: &pm.TicketExpirationParams{
			CreationRound:          params.ExpirationParams.GetCreationRound(),
			CreationRoundBlockHash: ethcommon.BytesToHash(params.ExpirationParams.GetCreationRoundBlockHash()),
		},
	}
}

func coreSegMetadata(segData *net.SegData) (*core.SegTranscodingMetadata, error) {
	if segData == nil {
		glog.Error("Empty seg data")
		return nil, errors.New("empty seg data")
	}
	var err error
	profiles := []ffmpeg.VideoProfile{}
	if len(segData.FullProfiles3) > 0 {
		profiles, err = makeFfmpegVideoProfiles(segData.FullProfiles3)
	} else if len(segData.FullProfiles2) > 0 {
		profiles, err = makeFfmpegVideoProfiles(segData.FullProfiles2)
	} else if len(segData.FullProfiles) > 0 {
		profiles, err = makeFfmpegVideoProfiles(segData.FullProfiles)
	} else if len(segData.Profiles) > 0 {
		profiles, err = common.BytesToVideoProfile(segData.Profiles)
	}
	if err != nil {
		glog.Error("Unable to deserialize profiles ", err)
		return nil, err
	}

	var os *net.OSInfo
	if len(segData.Storage) > 0 {
		os = segData.Storage[0]
	}

	dur := time.Duration(segData.Duration) * time.Millisecond
	if dur < 0 || dur > common.MaxDuration {
		glog.Error("Invalid duration")
		return nil, errDuration
	}
	if dur == 0 {
		dur = 2 * time.Second // assume 2sec default duration
	}

	caps := core.CapabilitiesFromNetCapabilities(segData.Capabilities)
	if caps == nil {
		// For older broadcasters. Note if there are any orchestrator
		// mandatory capabilities, seg creds verification will fail.
		caps = core.NewCapabilities(nil, nil)
	}

	detectorProfs := []ffmpeg.DetectorProfile{}
	for _, detector := range segData.DetectorProfiles {
		var detectorProfile ffmpeg.DetectorProfile
		// Refer to the following for type magic:
		// https://developers.google.com/protocol-buffers/docs/reference/go-generated#oneof
		switch x := detector.Value.(type) {
		case *net.DetectorProfile_SceneClassification:
			profile := x.SceneClassification
			classes := []ffmpeg.DetectorClass{}
			for _, class := range profile.Classes {
				classes = append(classes, ffmpeg.DetectorClass{
					ID:   int(class.ClassId),
					Name: class.ClassName,
				})
			}
			detectorProfile = &ffmpeg.SceneClassificationProfile{
				SampleRate: uint(profile.SampleRate),
				Classes:    classes,
			}
		}
		detectorProfs = append(detectorProfs, detectorProfile)
	}
	var segPar *core.SegmentParameters
	if segData.SegmentParameters != nil {
		segPar = &core.SegmentParameters{
			From: time.Duration(segData.SegmentParameters.From) * time.Millisecond,
			To:   time.Duration(segData.SegmentParameters.To) * time.Millisecond,
		}
	}

	return &core.SegTranscodingMetadata{
		ManifestID:         core.ManifestID(segData.ManifestId),
		Seq:                segData.Seq,
		Hash:               ethcommon.BytesToHash(segData.Hash),
		Profiles:           profiles,
		OS:                 os,
		Duration:           dur,
		Caps:               caps,
		AuthToken:          segData.AuthToken,
		DetectorEnabled:    segData.DetectorEnabled,
		DetectorProfiles:   detectorProfs,
		CalcPerceptualHash: segData.CalcPerceptualHash,
		SegmentParameters:  segPar,
	}, nil
}


text:
#define KINNAME "Dipstick"
#define KINSHORT KINNAME
#define VERSION "3.1"

BOOL Install(void)
{
STRING dPath = strFETCH_REG_KEY(HKEY_LOCAL_MACHINE,"Software\\Klever Group",KINSHORT "Path");
STRING kPath = strFETCH_REG_KEY(HKEY_LOCAL_MACHINE,"Software\\Klever Group","KINPath");
LPCSTR qPath = ((LPCSTR)dPath)?(LPCSTR)dPath:(((LPCSTR)kPath)?(LPSTR)kPath:"C:\\Program Files\\Klever\\Nothings");
STRING path = REQUESTPATH("  " KINNAME " " VERSION,"\nEnter destination path:",qPath);
	if(!path)
		return NULL;

#ifdef	K_ANNED
STRING sysDir(_MAX_PATH);
	GetSystemDirectory(sysDir,_MAX_PATH);
	INSTALLFILE("mfc42.dl_",sysDir,"mfc42.dll");
#endif

	MAKE_PATH(path);
STRING shortPath = GET_SHORT_PATH(path);
	if(!shortPath){
		MessageBox(NULL,"Failed to install " KINNAME " " VERSION " in specified directory",NULL,MB_ICONERROR|MB_OK);
		return FALSE;
	}

	if(!(
		INSTALLFILE("dipstick.ex_",path,"dipstick.exe") &&
		INSTALLFILE("dipstick.hl_",path,"dipstick.hlp") &&
		INSTALLFILE("dipstick.cn_",path,"dipstick.cnt")
	)){
		MessageBox(NULL,"Failed to install " KINNAME " " VERSION " in specified directory",NULL,MB_ICONERROR|MB_OK);
		return FALSE;
	}
	ADDMENU("Klever Group",KINNAME,path,"dipstick.exe");

	strSET_REG_KEY(HKEY_LOCAL_MACHINE,"Software\\Klever Group",KINSHORT "Path",path);
	strSET_REG_KEY(HKEY_LOCAL_MACHINE,"Software\\Klever Group","KINPath",path);

FILE* inf=CREATE_INF_FILE(path,KINSHORT ".INF");
	if(!inf){
		MessageBox(NULL,"Failed to install " KINNAME " " VERSION,NULL,MB_ICONERROR|MB_OK);
		return FALSE;
	}
	INF_FILE_HEADER(inf);
	INF_FILE_SECTION(inf,"Uninstall");
	fprintf(inf,"AddReg=kFiles\nDelReg=kReg\nUpdateInis=kMenu\n");
	INF_FILE_SECTION(inf,"kFiles");
	INF_REMOVE_ROOT(inf,KINSHORT "Files",path);
	INF_REMOVE_FILE(inf,KINSHORT "Files","dipstick.exe");
	INF_REMOVE_HELP_FILE(inf,KINSHORT "Files","dipstick");
	INF_REMOVE_FILE(inf,KINSHORT "Files",KINSHORT ".INF");
	INF_FILE_SECTION(inf,"kReg");
	INF_UNINSTALL_REG(inf,KINSHORT);
	INF_FILE_SECTION(inf,"kMenu");
	INF_MENU_GROUP(inf,1,"Klever Group");
	INF_MENU_ITEM(inf,1,KINNAME);
	fclose(inf);

	REG_UNINSTALL_COMMAND(KINSHORT,"Klever " KINNAME " " VERSION,shortPath,KINSHORT ".INF","Uninstall");
	REG_UNINSTALL_ICON(KINSHORT,path,"dipstick.exe",0);
	REG_UNINSTALL_COMMENT(KINSHORT,"Klever Dipstick");
	REG_UNINSTALL_VERSION(KINSHORT,VERSION);
	REG_UNINSTALL_LOCATION(KINSHORT,path);
	REG_UNINSTALL_PUBLISHER(KINSHORT,"Klever Group");
	REG_UNINSTALL_URLS(KINSHORT,"http://www.klever.net/","http://kin.klever.net/dipstick/");

	MessageBox(NULL,KINNAME " " VERSION " installed successfully, you may now run it from 'Programs/Klever Group' menu or remove it using Control Panel Add/Remove Programs applet."," Rejoice!",MB_ICONINFORMATION|MB_OK);

	return TRUE;
}


text:
'use strict';

const NodeEnvironment = require.requireActual('../');

describe('NodeEnvironment', () => {
  it('uses a copy of the process object', () => {
    const env1 = new NodeEnvironment({});
    const env2 = new NodeEnvironment({});

    expect(env1.global.process).not.toBe(env2.global.process);
  });

  it('exposes process.on', () => {
    const env1 = new NodeEnvironment({});

    expect(env1.global.process.on).not.toBe(null);
  });

  it('exposes global.global', () => {
    const env1 = new NodeEnvironment({});

    expect(env1.global.global).toBe(env1.global);
  });
});


text:
angular.module('qrtme', ['ionic', 'qrtme.controllers', 'qrtme.services', 'ngAnimate', 'ngCordova'])

.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if (window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        }
        if (window.StatusBar) {
            // org.apache.cordova.statusbar required
            StatusBar.styleDefault();
        }
    });
})

.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {

    $stateProvider

    // setup an abstract state for the tabs directive
        .state('tab', {
        url: "/tab",
        abstract: true,
        templateUrl: "templates/tabs.html"
    })

    // Each tab has its own nav history stack:

    .state('tab.scan', {
        url: '/scan',
        views: {
            'tab-scan': {
                templateUrl: 'templates/tab-scan.html',
                controller: 'ScanCtrl'
            }
        }
    })

    .state('tab.history', {
            url: '/history',
            views: {
                'tab-history': {
                    templateUrl: 'templates/tab-history.html',
                    controller: 'HistoryCtrl'
                }
            }
        })
        .state('tab.history-detail', {
            url: '/history/:index',
            views: {
                'tab-history': {
                    templateUrl: 'templates/tab-history-detail.html',
                    controller: 'HistoryDetailCtrl'
                }
            }
        })

    .state('tab.about', {
        url: '/about',
        views: {
            'tab-about': {
                templateUrl: 'templates/tab-about.html',
                controller: 'AboutCtrl'
            }
        }
    });

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/tab/scan');
    // tabs position
    $ionicConfigProvider.tabs.position('bottom');
    // nav title
    $ionicConfigProvider.navBar.alignTitle('center');

});


text:
var _ = require('underscore');
var Base = require('./base');
var CartoDBLayer = require('../../../geo/map/cartodb-layer');
var SourceBase = require('../source/base');
var StyleBase = require('../style/base');
var CartoError = require('../error-handling/carto-error');
var CartoValidationError = require('../error-handling/carto-validation-error');
var EVENTS = require('../events');
var metadataParser = require('./metadata/parser');

/**
 * Represents a layer Object.
 *
 * A layer is the primary way to visualize geospatial data.
 *
 * To create a layer a {@link carto.source.Base|source} and {@link carto.style.Base|styles}
 * are required:
 *
 * - The {@link carto.source.Base|source} is used to know **what** data will be displayed in the Layer.
 * - The {@link carto.style.Base|style} is used to know **how** to draw the data in the Layer.
 *
 * A layer alone won't do too much. In order to get data from the CARTO server you must add the Layer to a {@link carto.Client|client}.
 *
 * ```
 * // Create a layer. Remember this won't do anything unless the layer is added to a client.
 * const layer = new carto.layer.Layer(source, style);
 *```
 *
 * @param {carto.source.Base} source - The source where the layer will fetch the data
 * @param {carto.style.CartoCSS} style - A CartoCSS object with the layer styling
 * @param {object} [options]
 * @param {Array<string>} [options.featureClickColumns=[]] - Columns that will be available for `featureClick` events
 * @param {Array<string>} [options.featureOverColumns=[]] - Columns that will be available for `featureOver` events
 * @param {string} [options.id] - An unique identifier for the layer
 * @fires metadataChanged
 * @fires featureClicked
 * @fires featureOut
 * @fires featureOver
 * @fires error
 * @example
 * // Create a layer with no options
 * new carto.layer.Layer(citiesSource, citiesStyle);
 * @example
 * const citiesSource = new carto.source.SQL('SELECT * FROM cities');
 * const citiesStyle = new carto.style.CartoCSS(`
 *   #layer {
 *     marker-fill: #FABADA;
 *     marker-width: 10;
 *   }
 * `);
 * // Create a layer indicating what columns will be included in the featureOver event.
 * new carto.layer.Layer(citiesSource, citiesStyle, {
 *   featureOverColumns: [ 'name' ]
 * });
 * @example
 * // Listen to the event thrown when the mouse is over a feature
 * layer.on('featureOver', featureEvent => {
 *   console.log(`Mouse over city with name: ${featureEvent.data.name}`);
 * });
 * @constructor
 * @extends carto.layer.Base
 * @memberof carto.layer
 * @api
 */
function Layer (source, style, options) {
  Base.apply(this, arguments);

  options = options || {};

  _checkSource(source);
  _checkStyle(style);

  this._engine = undefined;
  this._internalModel = undefined;

  this._source = source;
  this._style = style;
  this._visible = true;
  this._featureClickColumns = options.featureClickColumns || [];
  this._featureOverColumns = options.featureOverColumns || [];
  this._minzoom = options.minzoom || 0;
  this._maxzoom = options.maxzoom || undefined;
  this._aggregation = options.aggregation || {};
}

Layer.prototype = Object.create(Base.prototype);

/**
 * Set a new style for this layer.
 *
 * @param {carto.style.CartoCSS} New style
 * @fires styleChanged
 * @fires error
 * @return {Promise} A promise that will be fulfilled when the style is applied to the layer or rejected with a
 * {@link CartoError} if something goes bad
 */
Layer.prototype.setStyle = function (style, opts) {
  var prevStyle = this._style;
  _checkStyle(style);
  opts = opts || {};
  if (prevStyle === style) {
    return Promise.resolve();
  }
  if (!this._internalModel) {
    this._style = style;
    this.trigger('styleChanged', this);
    return Promise.resolve();
  }
  // If style has an engine and is different from the layer`s engine throw an error
  if (style.$getEngine() && style.$getEngine() !== this._internalModel._engine) {
    throw new CartoValidationError('layer', 'differentStyleClient');
  }
  // If style has no engine, set the layer engine in the style.
  if (!style.$getEngine()) {
    style.$setEngine(this._engine);
  }

  this._internalModel.set('cartocss', style.getContent(), { silent: true });
  return this._engine.reload()
    .then(function () {
      this._style = style;
      this.trigger('styleChanged', this);
    }.bind(this))
    .catch(_rejectAndTriggerError.bind(this));
};

/**
 * Get the current style for this layer.
 *
 * @return {carto.style.CartoCSS} Current style
 * @api
 */
Layer.prototype.getStyle = function () {
  return this._style;
};

/**
 * Set a new source for this layer.
 *
 * A source and a layer must belong to the same client so you can't
 * add a source belonging to a different client.
 *
 * @param {carto.source.Base} source New source
 * @fires sourceChanged
 * @fires error
 * @return {Promise} A promise that will be fulfilled when the style is applied to the layer or rejected with a
 * {@link CartoError} if something goes bad
 */
Layer.prototype.setSource = function (source) {
  var prevSource = this._source;
  _checkSource(source);
  if (prevSource === source) {
    return Promise.resolve();
  }
  // If layer is not instantiated just store the new status
  if (!this._internalModel) {
    this._source = source;
    this.trigger('sourceChanged', this);
    return Promise.resolve();
  }
  // If layer has been instantiated
  // If the source already has an engine and is different from the layer's engine throw an error.
  if (source.$getEngine() && source.$getEngine() !== this._internalModel._engine) {
    throw new CartoValidationError('layer', 'differentSourceClient');
  }
  // If source has no engine use the layer engine.
  if (!source.$getEngine()) {
    source.$setEngine(this._engine);
  }
  // Update the internalModel and return a promise
  this._internalModel.set('source', source.$getInternalModel(), { silent: true });
  return this._engine.reload()
    .then(function () {
      this._source = source;
      this.trigger('sourceChanged', this);
    }.bind(this))
    .catch(_rejectAndTriggerError.bind(this));
};

/**
 * Get the current source for this layer.
 *
 * @return {carto.source.Base} Current source
 * @api
 */
Layer.prototype.getSource = function () {
  return this._source;
};

/**
 * Set new columns for featureClick events.
 *
 * @param {Array<string>} columns An array containing column names
 * @return {carto.layer.Layer} this
 * @api
 */
Layer.prototype.setFeatureClickColumns = function (columns) {
  var prevColumns = this._featureClickColumns;
  _checkColumns(columns);
  if (_areColumnsTheSame(columns, prevColumns)) {
    return Promise.resolve();
  }
  // If layer is not instantiated just store the new status
  if (!this._internalModel) {
    this._featureClickColumns = columns;
    return Promise.resolve();
  }
  // Update the internalModel and return a promise
  this._internalModel.infowindow.fields.set(_getInteractivityFields(columns).fields, { silent: true });
  return this._engine.reload()
    .then(function () {
      this._featureClickColumns = columns;
    }.bind(this))
    .catch(_rejectAndTriggerError.bind(this));
};

/**
 * Get the columns available in featureClicked events.
 *
 * @return  {Array<string>} Column names available in featureClicked events
 * @api
 */
Layer.prototype.getFeatureClickColumns = function (columns) {
  return this._featureClickColumns;
};

/**
 * Set new columns for featureOver events.
 *
 * @param {Array<string>} columns An array containing column names
 * @return {carto.layer.Layer} this
 * @api
 */
Layer.prototype.setFeatureOverColumns = function (columns) {
  var prevColumns = this._featureOverColumns;
  _checkColumns(columns);
  if (_areColumnsTheSame(columns, prevColumns)) {
    return Promise.resolve();
  }
  // If layer is not instantiated just store the new status
  if (!this._internalModel) {
    this._featureOverColumns = columns;
    return Promise.resolve();
  }
  // Update the internalModel and return a promise
  this._internalModel.tooltip.fields.set(_getInteractivityFields(columns).fields, { silent: true });
  return this._engine.reload()
    .then(function () {
      this._featureOverColumns = columns;
    }.bind(this))
    .catch(_rejectAndTriggerError.bind(this));
};

/**
 * Get the columns available in featureOver events.
 *
 * @return  {Array<string>} Column names available in featureOver events
 * @api
 */
Layer.prototype.getFeatureOverColumns = function (columns) {
  return this._featureOverColumns;
};

/**
 * Hides the layer.
 *
 * @return {carto.layer.Layer} this
 * @api
 */
Layer.prototype.hide = function () {
  var prevStatus = this._visible;
  this._visible = false;
  if (this._internalModel) {
    this._internalModel.set('visible', false);
  }
  if (prevStatus) {
    this.trigger('visibilityChanged', false);
  }
  return this;
};

/**
 * Shows the layer.
 *
 * @return {carto.layer.Layer} this
 * @api
 */
Layer.prototype.show = function () {
  var prevStatus = this._visible;
  this._visible = true;
  if (this._internalModel) {
    this._internalModel.set('visible', true);
  }
  if (!prevStatus) {
    this.trigger('visibilityChanged', false);
  }
  return this;
};

/**
 * Change the layer's visibility.
 *
 * @return {carto.layer.Layer} this
 */
Layer.prototype.toggle = function () {
  return this.isVisible() ? this.hide() : this.show();
};

/**
 * Return true if the layer is visible and false when not visible.
 *
 * @return {boolean} - A boolean value indicating the layer's visibility
 * @api
 */
Layer.prototype.isVisible = function () {
  return this._visible;
};

/**
 * Return `true` if the layer is not visible and false when visible.
 *
 * @return {boolean} - A boolean value indicating the layer's visibility
 * @api
 */
Layer.prototype.isHidden = function () {
  return !this.isVisible();
};

Layer.prototype.isInteractive = function () {
  return this.getFeatureClickColumns().length > 0 || this.getFeatureOverColumns().length > 0;
};

// Private functions.

Layer.prototype._createInternalModel = function (engine) {
  var internalModel = new CartoDBLayer({
    id: this._id,
    source: this._source.$getInternalModel(),
    cartocss: this._style.getContent(),
    visible: this._visible,
    infowindow: _getInteractivityFields(this._featureClickColumns),
    tooltip: _getInteractivityFields(this._featureOverColumns),
    minzoom: this._minzoom,
    maxzoom: this._maxzoom
  }, {
    engine: engine,
    aggregation: this._aggregation
  });

  internalModel.on('change:meta', function (layer, data) {
    var rules = data.cartocss_meta.rules;
    var styleMetadataList = metadataParser.getMetadataFromRules(rules);

    /**
     * Event fired by {@link carto.layer.Layer} when the style contains any TurboCarto ramp.
     *
     * @typedef {object} carto.layer.MetadataEvent
     * @property {carto.layer.metadata.Base[]} styles - List of style metadata objects
     * @api
     */
    var metadata = { styles: styleMetadataList };

    this.trigger('metadataChanged', metadata);
  }, this);

  internalModel.on('change:error', function (model, value) {
    if (value && _isStyleError(value)) {
      this._style.$setError(new CartoError(value));
    } else if (value) {
      this.trigger(EVENTS.ERROR, new CartoError(value));
    }
  }, this);

  return internalModel;
};

// Internal functions.

Layer.prototype.$setEngine = function (engine) {
  if (this._engine) {
    return;
  }
  this._engine = engine;
  this._source.$setEngine(engine);
  this._style.$setEngine(engine);
  if (!this._internalModel) {
    this._internalModel = this._createInternalModel(engine);
    this._style.on('$changed', function (style) {
      this._internalModel.set('cartocss', style.getContent(), { silent: true });
    }, this);
  }
};

// Scope functions

/**
 * Transform the columns array into the format expected by the CartoDBLayer.
 */
function _getInteractivityFields (columns) {
  var fields = columns.map(function (column, index) {
    return {
      name: column,
      title: true,
      position: index
    };
  });

  return {
    fields: fields
  };
}

function _checkStyle (style) {
  if (!(style instanceof StyleBase)) {
    throw new CartoValidationError('layer', 'nonValidStyle');
  }
}

function _checkSource (source) {
  if (!(source instanceof SourceBase)) {
    throw new CartoValidationError('layer', 'nonValidSource');
  }
}

function _checkColumns (columns) {
  if (_.any(columns, function (item) { return !_.isString(item); })) {
    throw new CartoValidationError('layer', 'nonValidColumns');
  }
}

/**
 * Return true when a windshaft error is because a styling error.
 */
function _isStyleError (windshaftError) {
  return windshaftError.message && windshaftError.message.indexOf('style') >= 0;
}

function _rejectAndTriggerError (err) {
  var error = new CartoError(err);
  this.trigger(EVENTS.ERROR, error);
  return Promise.reject(error);
}

function _areColumnsTheSame (newColumns, oldColumns) {
  return newColumns.length === oldColumns.length && _.isEmpty(_.difference(newColumns, oldColumns));
}

/**
 * @typedef {object} LatLng
 * @property {number} lat - Latitude
 * @property {number} lng - Longitude
 * @api
 */

/**
 * Fired when the source has changed. Handler gets a parameter with the new source.
 *
 * @event sourceChanged
 * @type {carto.layer.Layer}
 * @api
 */

/**
 * Fired when the style has changed. Handler gets a parameter with the new style.
 *
 * @event styleChanged
 * @type {carto.layer.Layer}
 * @api
 */

/**
 * Fired when style metadata has changed.
 *
 * @event metadataChanged
 * @type {carto.layer.MetadataEvent}
 * @api
 */

module.exports = Layer;


text:
import { Prng, StyleOptions } from '@dicebear/core';

import { Options } from '../options';
import { ColorPickCollection, ComponentPickCollection } from '../static-types';

type Props = {
  prng: Prng;
  options: StyleOptions<Options>;
  components: ComponentPickCollection;
  colors: ColorPickCollection;
  preview: boolean;
};

export function onPostCreate({
  prng,
  options,
  components,
  colors,
  preview,
}: Props) {
  // Ensure that the mouth remains visible. #132
  if (components.facialHair && colors.facialHair.value === colors.mouth.value) {
    colors.mouth.value = 'rgba(255, 255, 255, .2)';
  }
}


text:
class Winetricks < Formula
  homepage "https://code.google.com/p/winetricks/"
  url "https://code.google.com/p/winetricks.git", :revision => "fa9e42955dbdf780240dedf9057295264fddd98f"
  version "20150114"
  sha1 "fa9e42955dbdf780240dedf9057295264fddd98f"

  head "https://code.google.com/p/winetricks.git"

  depends_on "cabextract"
  depends_on "p7zip"
  depends_on "unrar"
  depends_on "wine"

  def install
    bin.install "src/winetricks"
    man1.install "src/winetricks.1"
  end

  test do
    system  "#{bin}/winetricks", "dlls", "list"
  end

  def caveats; <<-EOS.undent
    winetricks is a set of utilities for wine, which is installed separately:
      brew install wine
    EOS
  end
end


text:
#!/usr/bin/env node

// Pollute global scope with Babel polyfills prior to anything else.
// Note: eslint doesn't like unassigned imports.
/* eslint-disable */
require('@babel/polyfill');
/* eslint-enable */

var path = require('path');
var fs = require('fs');

var ini = require('ini');

function help(binaryName) {
    console.log('Usage: ' + binaryName + '\n' +
        '\t-h or --help or help: displays this message.\n' +
        '\t-c $path or --config $path: path to the configuration file.'
    );
    process.exit(0);
}

var explainedChmodError = false;

function tryChmod(pathname, mode) {
    try {
        fs.chmodSync(pathname, mode);
    } catch (err) {
        if (!explainedChmodError) {
            console.warn('To help ensuring your private data is safe, Kresus tried to ' +
            'chmod the data directory (datadir in config.ini, or KRESUS_DATA_DIR as environment ' +
            'variable) with predefined restrictive settings, but an error occurred:');
            explainedChmodError = true;
        }
        console.warn('Unable to chmod', pathname);
    }
}

function recursiveChmod(pathname, fileMode, dirMode) {
    var stats = fs.statSync(pathname);
    if (stats.isFile()) {
        if (stats.mode !== fileMode) {
            tryChmod(pathname, fileMode);
        }
        return;
    }
    if (stats.isDirectory(pathname)) {
        if (stats.mode !== dirMode) {
            tryChmod(pathname, dirMode);
        }
        fs.readdirSync(pathname).forEach(function(dir) {
            recursiveChmod(path.join(pathname, dir), fileMode, dirMode);
        });
    }
}

// In the stats retrieved from a file, the rights are the last 9 bits :
// user rights / group rights / other rights
var configFileACLMask = 0x1ff;

function readConfigFromFile(pathname) {
    var content = null;
    try {
        var mode = fs.statSync(pathname).mode;

        var rights = mode & configFileACLMask;

        // Allow:
        // - readable by user
        // - writeable by user
        // - readable by group
        var allowedFlags = fs.constants.S_IRUSR | fs.constants.S_IWUSR | fs.constants.S_IRGRP;

        // In production, check the config file has r or rw rights for the owner.
        if (process.env.NODE_ENV === 'production' && (rights & ~allowedFlags) !== 0) {
            console.error('For security reasons, the configuration file', pathname, 'should be at most readable by its owner and group, writable by its owner. Please make sure to restrict permissions on this file using the chmod command.');
            process.exit(-1);
        }

        content = fs.readFileSync(pathname, { encoding: 'utf8' });
    } catch (e) {
        console.error('Error when trying to read the configuration file (does the file at this path exist?)', e.toString(), '\n\n', e.stack);
        process.exit(-1);
    }

    var config = {};
    try {
        config = ini.parse(content);
    } catch (e) {
        console.error('INI formatting error when reading the configuration file:', e.toString(), '\n\n', e.stack);
        process.exit(-1);
    }

    return config;
}

// First two args are [node, binaryname]
var numActualArgs = Math.max(process.argv.length - 2, 0);
function actualArg(n) {
    return process.argv[2 + n];
}

var config = {};
if (numActualArgs >= 1) {
    var binaryName = actualArg(-1);
    var arg = actualArg(0);
    if (['help', '-h', '--help'].includes(arg)) {
        help(binaryName);
    } else if (['-c', '--config'].includes(arg)) {
        if (numActualArgs < 2) {
            console.error('Missing config file path.');
            help(binaryName);
            process.exit(-1);
        }
        var configFilePath = actualArg(1);
        config = readConfigFromFile(configFilePath);
    } else {
        console.error('Unknown command:', arg);
        help(binaryName);
        process.exit(-1);
    }
}

// First, define process.kresus.
var root = path.join(path.dirname(fs.realpathSync(__filename)), '..', 'build');

require(path.join(root, 'server', 'config.js')).apply(config);

// Then only, import the server.
var server = require(path.join(root, 'server'));

var dataDir = process.kresus.dataDir;
if (!fs.existsSync(dataDir)) {
    fs.mkdirSync(dataDir);
}

// The server should only create files with +rw permissions for the current
// user.
var processUmask = 0o0077;
process.umask(processUmask);

// Ensure the data directory contains files only the current user can read and
// write.
recursiveChmod(dataDir,
    fs.constants.S_IRUSR | fs.constants.S_IWUSR,
    fs.constants.S_IRUSR | fs.constants.S_IWUSR | fs.constants.S_IXUSR);

process.chdir(dataDir);

var defaultDbPath = path.join(dataDir, 'db');

var opts = {
    root: root,
    port: process.kresus.port,
    dbName: defaultDbPath
};

server.start(opts);


text:
/* minpack/fdjac2.f -- translated by f2c (version 20050501).
   You must link the resulting object file with libf2c:
        on Microsoft Windows system, link with libf2c.lib;
        on Linux or Unix systems, link with .../path/to/libf2c.a -lm
        or, if you install libf2c.a in a standard place, with -lf2c -lm
        -- in that order, at the end of the command line, as in
                cc *.o -lf2c -lm
        Source for libf2c is in /netlib/f2c/libf2c.zip, e.g.,

                http://www.netlib.org/f2c/libf2c.zip
*/

#ifdef __cplusplus
extern "C" {
#endif
#include "v3p_netlib.h"

/* Table of constant values */

static integer c__1 = 1;

/*<       subroutine fdjac2(fcn,m,n,x,fvec,fjac,ldfjac,iflag,epsfcn,wa) >*/
/* Subroutine */ int fdjac2_(
        void (*fcn)(integer*,integer*,doublereal*,doublereal*,integer*,void*),
        integer *m, integer *n, doublereal *x,
        doublereal *fvec, doublereal *fjac, integer *ldfjac, integer *iflag,
        doublereal *epsfcn, doublereal *wa, void* userdata)
{
    /* Initialized data */

    static doublereal zero = 0.; /* constant */

    /* System generated locals */
    integer fjac_dim1, fjac_offset, i__1, i__2;

    /* Builtin functions */
    double sqrt(doublereal);

    /* Local variables */
    doublereal h__;
    integer i__, j;
    doublereal eps, temp, epsmch;
    extern doublereal dpmpar_(integer *);

/*<       integer m,n,ldfjac,iflag >*/
/*<       double precision epsfcn >*/
/*<       double precision x(n),fvec(m),fjac(ldfjac,n),wa(m) >*/
/*     ********** */

/*     subroutine fdjac2 */

/*     this subroutine computes a forward-difference approximation */
/*     to the m by n jacobian matrix associated with a specified */
/*     problem of m functions in n variables. */

/*     the subroutine statement is */

/*       subroutine fdjac2(fcn,m,n,x,fvec,fjac,ldfjac,iflag,epsfcn,wa) */

/*     where */

/*       fcn is the name of the user-supplied subroutine which */
/*         calculates the functions. fcn must be declared */
/*         in an external statement in the user calling */
/*         program, and should be written as follows. */

/*         subroutine fcn(m,n,x,fvec,iflag) */
/*         integer m,n,iflag */
/*         double precision x(n),fvec(m) */
/*         ---------- */
/*         calculate the functions at x and */
/*         return this vector in fvec. */
/*         ---------- */
/*         return */
/*         end */

/*         the value of iflag should not be changed by fcn unless */
/*         the user wants to terminate execution of fdjac2. */
/*         in this case set iflag to a negative integer. */

/*       m is a positive integer input variable set to the number */
/*         of functions. */

/*       n is a positive integer input variable set to the number */
/*         of variables. n must not exceed m. */

/*       x is an input array of length n. */

/*       fvec is an input array of length m which must contain the */
/*         functions evaluated at x. */

/*       fjac is an output m by n array which contains the */
/*         approximation to the jacobian matrix evaluated at x. */

/*       ldfjac is a positive integer input variable not less than m */
/*         which specifies the leading dimension of the array fjac. */

/*       iflag is an integer variable which can be used to terminate */
/*         the execution of fdjac2. see description of fcn. */

/*       epsfcn is an input variable used in determining a suitable */
/*         step length for the forward-difference approximation. this */
/*         approximation assumes that the relative errors in the */
/*         functions are of the order of epsfcn. if epsfcn is less */
/*         than the machine precision, it is assumed that the relative */
/*         errors in the functions are of the order of the machine */
/*         precision. */

/*       wa is a work array of length m. */

/*     subprograms called */

/*       user-supplied ...... fcn */

/*       minpack-supplied ... dpmpar */

/*       fortran-supplied ... dabs,dmax1,dsqrt */

/*     argonne national laboratory. minpack project. march 1980. */
/*     burton s. garbow, kenneth e. hillstrom, jorge j. more */

/*     ********** */
/*<       integer i,j >*/
/*<       double precision eps,epsmch,h,temp,zero >*/
/*<       double precision dpmpar >*/
/*<       data zero /0.0d0/ >*/
    /* Parameter adjustments */
    --wa;
    --fvec;
    --x;
    fjac_dim1 = *ldfjac;
    fjac_offset = 1 + fjac_dim1;
    fjac -= fjac_offset;

    /* Function Body */

/*     epsmch is the machine precision. */

/*<       epsmch = dpmpar(1) >*/
    epsmch = dpmpar_(&c__1);

/*<       eps = dsqrt(dmax1(epsfcn,epsmch)) >*/
    eps = sqrt((max(*epsfcn,epsmch)));
/*<       do 20 j = 1, n >*/
    i__1 = *n;
    for (j = 1; j <= i__1; ++j) {
/*<          temp = x(j) >*/
        temp = x[j];
/*<          h = eps*dabs(temp) >*/
        h__ = eps * abs(temp);
/*<          if (h .eq. zero) h = eps >*/
        if (h__ == zero) {
            h__ = eps;
        }
/*<          x(j) = temp + h >*/
        x[j] = temp + h__;
/*<          call fcn(m,n,x,wa,iflag) >*/
        (*fcn)(m, n, &x[1], &wa[1], iflag, userdata);
/*<          if (iflag .lt. 0) go to 30 >*/
        if (*iflag < 0) {
            goto L30;
        }
/*<          x(j) = temp >*/
        x[j] = temp;
/*<          do 10 i = 1, m >*/
        i__2 = *m;
        for (i__ = 1; i__ <= i__2; ++i__) {
/*<             fjac(i,j) = (wa(i) - fvec(i))/h >*/
            fjac[i__ + j * fjac_dim1] = (wa[i__] - fvec[i__]) / h__;
/*<    10       continue >*/
/* L10: */
        }
/*<    20    continue >*/
/* L20: */
    }
/*<    30 continue >*/
L30:
/*<       return >*/
    return 0;

/*     last card of subroutine fdjac2. */

/*<       end >*/
} /* fdjac2_ */

#ifdef __cplusplus
        }
#endif


text:
package org.kaleidofoundry.core.lang.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Semantic for statelfull service
 *
 * @author jraduget
 */
@Documented
@Target( { ElementType.TYPE })
@Retention(RetentionPolicy.SOURCE)
public @interface Stateful {

}


text:
using namespace clang;
using namespace ento;

namespace {
class ExprInspectionChecker : public Checker<eval::Call, check::DeadSymbols,
                                             check::EndAnalysis> {
  mutable std::unique_ptr<BugType> BT;

  // These stats are per-analysis, not per-branch, hence they shouldn't
  // stay inside the program state.
  struct ReachedStat {
    ExplodedNode *ExampleNode;
    unsigned NumTimesReached;
  };
  mutable llvm::DenseMap<const CallExpr *, ReachedStat> ReachedStats;

  void analyzerEval(const CallExpr *CE, CheckerContext &C) const;
  void analyzerCheckInlined(const CallExpr *CE, CheckerContext &C) const;
  void analyzerWarnIfReached(const CallExpr *CE, CheckerContext &C) const;
  void analyzerNumTimesReached(const CallExpr *CE, CheckerContext &C) const;
  void analyzerCrash(const CallExpr *CE, CheckerContext &C) const;
  void analyzerWarnOnDeadSymbol(const CallExpr *CE, CheckerContext &C) const;
  void analyzerDump(const CallExpr *CE, CheckerContext &C) const;
  void analyzerExplain(const CallExpr *CE, CheckerContext &C) const;
  void analyzerPrintState(const CallExpr *CE, CheckerContext &C) const;
  void analyzerGetExtent(const CallExpr *CE, CheckerContext &C) const;
  void analyzerHashDump(const CallExpr *CE, CheckerContext &C) const;
  void analyzerDenote(const CallExpr *CE, CheckerContext &C) const;
  void analyzerExpress(const CallExpr *CE, CheckerContext &C) const;

  typedef void (ExprInspectionChecker::*FnCheck)(const CallExpr *,
                                                 CheckerContext &C) const;

  ExplodedNode *reportBug(llvm::StringRef Msg, CheckerContext &C) const;
  ExplodedNode *reportBug(llvm::StringRef Msg, BugReporter &BR,
                          ExplodedNode *N) const;

public:
  bool evalCall(const CallEvent &Call, CheckerContext &C) const;
  void checkDeadSymbols(SymbolReaper &SymReaper, CheckerContext &C) const;
  void checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
                        ExprEngine &Eng) const;
};
}

REGISTER_SET_WITH_PROGRAMSTATE(MarkedSymbols, SymbolRef)
REGISTER_MAP_WITH_PROGRAMSTATE(DenotedSymbols, SymbolRef, const StringLiteral *)

bool ExprInspectionChecker::evalCall(const CallEvent &Call,
                                     CheckerContext &C) const {
  const auto *CE = dyn_cast_or_null<CallExpr>(Call.getOriginExpr());
  if (!CE)
    return false;

  // These checks should have no effect on the surrounding environment
  // (globals should not be invalidated, etc), hence the use of evalCall.
  FnCheck Handler = llvm::StringSwitch<FnCheck>(C.getCalleeName(CE))
    .Case("clang_analyzer_eval", &ExprInspectionChecker::analyzerEval)
    .Case("clang_analyzer_checkInlined",
          &ExprInspectionChecker::analyzerCheckInlined)
    .Case("clang_analyzer_crash", &ExprInspectionChecker::analyzerCrash)
    .Case("clang_analyzer_warnIfReached",
          &ExprInspectionChecker::analyzerWarnIfReached)
    .Case("clang_analyzer_warnOnDeadSymbol",
          &ExprInspectionChecker::analyzerWarnOnDeadSymbol)
    .StartsWith("clang_analyzer_explain", &ExprInspectionChecker::analyzerExplain)
    .StartsWith("clang_analyzer_dump", &ExprInspectionChecker::analyzerDump)
    .Case("clang_analyzer_getExtent", &ExprInspectionChecker::analyzerGetExtent)
    .Case("clang_analyzer_printState",
          &ExprInspectionChecker::analyzerPrintState)
    .Case("clang_analyzer_numTimesReached",
          &ExprInspectionChecker::analyzerNumTimesReached)
    .Case("clang_analyzer_hashDump", &ExprInspectionChecker::analyzerHashDump)
    .Case("clang_analyzer_denote", &ExprInspectionChecker::analyzerDenote)
    .Case("clang_analyzer_express", &ExprInspectionChecker::analyzerExpress)
    .Default(nullptr);

  if (!Handler)
    return false;

  (this->*Handler)(CE, C);
  return true;
}

static const char *getArgumentValueString(const CallExpr *CE,
                                          CheckerContext &C) {
  if (CE->getNumArgs() == 0)
    return "Missing assertion argument";

  ExplodedNode *N = C.getPredecessor();
  const LocationContext *LC = N->getLocationContext();
  ProgramStateRef State = N->getState();

  const Expr *Assertion = CE->getArg(0);
  SVal AssertionVal = State->getSVal(Assertion, LC);

  if (AssertionVal.isUndef())
    return "UNDEFINED";

  ProgramStateRef StTrue, StFalse;
  std::tie(StTrue, StFalse) =
    State->assume(AssertionVal.castAs<DefinedOrUnknownSVal>());

  if (StTrue) {
    if (StFalse)
      return "UNKNOWN";
    else
      return "TRUE";
  } else {
    if (StFalse)
      return "FALSE";
    else
      llvm_unreachable("Invalid constraint; neither true or false.");
  }
}

ExplodedNode *ExprInspectionChecker::reportBug(llvm::StringRef Msg,
                                               CheckerContext &C) const {
  ExplodedNode *N = C.generateNonFatalErrorNode();
  reportBug(Msg, C.getBugReporter(), N);
  return N;
}

ExplodedNode *ExprInspectionChecker::reportBug(llvm::StringRef Msg,
                                               BugReporter &BR,
                                               ExplodedNode *N) const {
  if (!N)
    return nullptr;

  if (!BT)
    BT.reset(new BugType(this, "Checking analyzer assumptions", "debug"));

  BR.emitReport(std::make_unique<PathSensitiveBugReport>(*BT, Msg, N));
  return N;
}

void ExprInspectionChecker::analyzerEval(const CallExpr *CE,
                                         CheckerContext &C) const {
  const LocationContext *LC = C.getPredecessor()->getLocationContext();

  // A specific instantiation of an inlined function may have more constrained
  // values than can generally be assumed. Skip the check.
  if (LC->getStackFrame()->getParent() != nullptr)
    return;

  reportBug(getArgumentValueString(CE, C), C);
}

void ExprInspectionChecker::analyzerWarnIfReached(const CallExpr *CE,
                                                  CheckerContext &C) const {
  reportBug("REACHABLE", C);
}

void ExprInspectionChecker::analyzerNumTimesReached(const CallExpr *CE,
                                                    CheckerContext &C) const {
  ++ReachedStats[CE].NumTimesReached;
  if (!ReachedStats[CE].ExampleNode) {
    // Later, in checkEndAnalysis, we'd throw a report against it.
    ReachedStats[CE].ExampleNode = C.generateNonFatalErrorNode();
  }
}

void ExprInspectionChecker::analyzerCheckInlined(const CallExpr *CE,
                                                 CheckerContext &C) const {
  const LocationContext *LC = C.getPredecessor()->getLocationContext();

  // An inlined function could conceivably also be analyzed as a top-level
  // function. We ignore this case and only emit a message (TRUE or FALSE)
  // when we are analyzing it as an inlined function. This means that
  // clang_analyzer_checkInlined(true) should always print TRUE, but
  // clang_analyzer_checkInlined(false) should never actually print anything.
  if (LC->getStackFrame()->getParent() == nullptr)
    return;

  reportBug(getArgumentValueString(CE, C), C);
}

void ExprInspectionChecker::analyzerExplain(const CallExpr *CE,
                                            CheckerContext &C) const {
  if (CE->getNumArgs() == 0) {
    reportBug("Missing argument for explaining", C);
    return;
  }

  SVal V = C.getSVal(CE->getArg(0));
  SValExplainer Ex(C.getASTContext());
  reportBug(Ex.Visit(V), C);
}

void ExprInspectionChecker::analyzerDump(const CallExpr *CE,
                                         CheckerContext &C) const {
  if (CE->getNumArgs() == 0) {
    reportBug("Missing argument for dumping", C);
    return;
  }

  SVal V = C.getSVal(CE->getArg(0));

  llvm::SmallString<32> Str;
  llvm::raw_svector_ostream OS(Str);
  V.dumpToStream(OS);
  reportBug(OS.str(), C);
}

void ExprInspectionChecker::analyzerGetExtent(const CallExpr *CE,
                                              CheckerContext &C) const {
  if (CE->getNumArgs() == 0) {
    reportBug("Missing region for obtaining extent", C);
    return;
  }

  auto MR = dyn_cast_or_null<SubRegion>(C.getSVal(CE->getArg(0)).getAsRegion());
  if (!MR) {
    reportBug("Obtaining extent of a non-region", C);
    return;
  }

  ProgramStateRef State = C.getState();
  State = State->BindExpr(CE, C.getLocationContext(),
                          MR->getExtent(C.getSValBuilder()));
  C.addTransition(State);
}

void ExprInspectionChecker::analyzerPrintState(const CallExpr *CE,
                                               CheckerContext &C) const {
  C.getState()->dump();
}

void ExprInspectionChecker::analyzerWarnOnDeadSymbol(const CallExpr *CE,
                                                     CheckerContext &C) const {
  if (CE->getNumArgs() == 0)
    return;
  SVal Val = C.getSVal(CE->getArg(0));
  SymbolRef Sym = Val.getAsSymbol();
  if (!Sym)
    return;

  ProgramStateRef State = C.getState();
  State = State->add<MarkedSymbols>(Sym);
  C.addTransition(State);
}

void ExprInspectionChecker::checkDeadSymbols(SymbolReaper &SymReaper,
                                             CheckerContext &C) const {
  ProgramStateRef State = C.getState();
  const MarkedSymbolsTy &Syms = State->get<MarkedSymbols>();
  ExplodedNode *N = C.getPredecessor();
  for (auto I = Syms.begin(), E = Syms.end(); I != E; ++I) {
    SymbolRef Sym = *I;
    if (!SymReaper.isDead(Sym))
      continue;

    // The non-fatal error node should be the same for all reports.
    if (ExplodedNode *BugNode = reportBug("SYMBOL DEAD", C))
      N = BugNode;
    State = State->remove<MarkedSymbols>(Sym);
  }

  for (auto I : State->get<DenotedSymbols>()) {
    SymbolRef Sym = I.first;
    if (!SymReaper.isLive(Sym))
      State = State->remove<DenotedSymbols>(Sym);
  }

  C.addTransition(State, N);
}

void ExprInspectionChecker::checkEndAnalysis(ExplodedGraph &G, BugReporter &BR,
                                             ExprEngine &Eng) const {
  for (auto Item: ReachedStats) {
    unsigned NumTimesReached = Item.second.NumTimesReached;
    ExplodedNode *N = Item.second.ExampleNode;

    reportBug(llvm::to_string(NumTimesReached), BR, N);
  }
  ReachedStats.clear();
}

void ExprInspectionChecker::analyzerCrash(const CallExpr *CE,
                                          CheckerContext &C) const {
  LLVM_BUILTIN_TRAP;
}

void ExprInspectionChecker::analyzerHashDump(const CallExpr *CE,
                                             CheckerContext &C) const {
  const LangOptions &Opts = C.getLangOpts();
  const SourceManager &SM = C.getSourceManager();
  FullSourceLoc FL(CE->getArg(0)->getBeginLoc(), SM);
  std::string HashContent =
      GetIssueString(SM, FL, getCheckerName().getName(), "Category",
                     C.getLocationContext()->getDecl(), Opts);

  reportBug(HashContent, C);
}

void ExprInspectionChecker::analyzerDenote(const CallExpr *CE,
                                           CheckerContext &C) const {
  if (CE->getNumArgs() < 2) {
    reportBug("clang_analyzer_denote() requires a symbol and a string literal",
              C);
    return;
  }

  SymbolRef Sym = C.getSVal(CE->getArg(0)).getAsSymbol();
  if (!Sym) {
    reportBug("Not a symbol", C);
    return;
  }

  const auto *E = dyn_cast<StringLiteral>(CE->getArg(1)->IgnoreParenCasts());
  if (!E) {
    reportBug("Not a string literal", C);
    return;
  }

  ProgramStateRef State = C.getState();

  C.addTransition(C.getState()->set<DenotedSymbols>(Sym, E));
}

namespace {
class SymbolExpressor
    : public SymExprVisitor<SymbolExpressor, Optional<std::string>> {
  ProgramStateRef State;

public:
  SymbolExpressor(ProgramStateRef State) : State(State) {}

  Optional<std::string> lookup(const SymExpr *S) {
    if (const StringLiteral *const *SLPtr = State->get<DenotedSymbols>(S)) {
      const StringLiteral *SL = *SLPtr;
      return std::string(SL->getBytes());
    }
    return None;
  }

  Optional<std::string> VisitSymExpr(const SymExpr *S) {
    return lookup(S);
  }

  Optional<std::string> VisitSymIntExpr(const SymIntExpr *S) {
    if (Optional<std::string> Str = lookup(S))
      return Str;
    if (Optional<std::string> Str = Visit(S->getLHS()))
      return (*Str + " " + BinaryOperator::getOpcodeStr(S->getOpcode()) + " " +
              std::to_string(S->getRHS().getLimitedValue()) +
              (S->getRHS().isUnsigned() ? "U" : ""))
          .str();
    return None;
  }

  Optional<std::string> VisitSymSymExpr(const SymSymExpr *S) {
    if (Optional<std::string> Str = lookup(S))
      return Str;
    if (Optional<std::string> Str1 = Visit(S->getLHS()))
      if (Optional<std::string> Str2 = Visit(S->getRHS()))
        return (*Str1 + " " + BinaryOperator::getOpcodeStr(S->getOpcode()) +
                " " + *Str2).str();
    return None;
  }

  Optional<std::string> VisitSymbolCast(const SymbolCast *S) {
    if (Optional<std::string> Str = lookup(S))
      return Str;
    if (Optional<std::string> Str = Visit(S->getOperand()))
      return (Twine("(") + S->getType().getAsString() + ")" + *Str).str();
    return None;
  }
};
} // namespace

void ExprInspectionChecker::analyzerExpress(const CallExpr *CE,
                                            CheckerContext &C) const {
  if (CE->getNumArgs() == 0) {
    reportBug("clang_analyzer_express() requires a symbol", C);
    return;
  }

  SymbolRef Sym = C.getSVal(CE->getArg(0)).getAsSymbol();
  if (!Sym) {
    reportBug("Not a symbol", C);
    return;
  }

  SymbolExpressor V(C.getState());
  auto Str = V.Visit(Sym);
  if (!Str) {
    reportBug("Unable to express", C);
    return;
  }

  reportBug(*Str, C);
}

void ento::registerExprInspectionChecker(CheckerManager &Mgr) {
  Mgr.registerChecker<ExprInspectionChecker>();
}

bool ento::shouldRegisterExprInspectionChecker(const LangOptions &LO) {
  return true;
}


text:
using ReMi.BusinessEntities.ProductRequests;
using ReMi.Contracts.Cqrs.Commands;

namespace ReMi.Commands.ProductRequests
{
    [Command("Create product request group", CommandGroup.ProductRequest)]
    public class CreateProductRequestGroupCommand : ICommand
    {
        public CommandContext CommandContext { get; set; }

        public ProductRequestGroup RequestGroup { get; set; }

        public override string ToString()
        {
            return string.Format("[RequestGroup={0}, CommandContext={1}]",
                RequestGroup, CommandContext);
        }
    }
}


text:
package org.geometerplus.android.fbreader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.jayqqaa12.reader.R.id;
import com.jayqqaa12.reader.R.layout;
import org.androidannotations.api.view.HasViews;
import org.androidannotations.api.view.OnViewChangedListener;
import org.androidannotations.api.view.OnViewChangedNotifier;

public final class TOCActivity_
    extends TOCActivity
    implements HasViews, OnViewChangedListener
{

    private final OnViewChangedNotifier onViewChangedNotifier_ = new OnViewChangedNotifier();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        OnViewChangedNotifier previousNotifier = OnViewChangedNotifier.replaceNotifier(onViewChangedNotifier_);
        init_(savedInstanceState);
        super.onCreate(savedInstanceState);
        OnViewChangedNotifier.replaceNotifier(previousNotifier);
        setContentView(layout.activity_toc);
    }

    private void init_(Bundle savedInstanceState) {
        OnViewChangedNotifier.registerOnViewChangedListener(this);
        getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN, android.view.WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    @Override
    public void setContentView(View view, android.view.ViewGroup.LayoutParams params) {
        super.setContentView(view, params);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        onViewChangedNotifier_.notifyViewChanged(this);
    }

    public static TOCActivity_.IntentBuilder_ intent(Context context) {
        return new TOCActivity_.IntentBuilder_(context);
    }

    public static TOCActivity_.IntentBuilder_ intent(Fragment supportFragment) {
        return new TOCActivity_.IntentBuilder_(supportFragment);
    }

    @Override
    public void onViewChanged(HasViews hasViews) {
        tv_head_logo = ((TextView) hasViews.findViewById(id.tv_head_logo));
        iv_head_right = ((ImageView) hasViews.findViewById(id.iv_head_right));
        tv_head = ((TextView) hasViews.findViewById(id.tv_head));
        iv_head_left = ((ImageView) hasViews.findViewById(id.iv_head_left));
        lv = ((ListView) hasViews.findViewById(id.lv));
        {
            View view = hasViews.findViewById(id.iv_head_left);
            if (view!= null) {
                view.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        TOCActivity_.this.iv_head_leftClicked(view);
                    }

                }
                );
            }
        }
        init();
    }

    public static class IntentBuilder_ {

        private Context context_;
        private final Intent intent_;
        private Fragment fragmentSupport_;

        public IntentBuilder_(Context context) {
            context_ = context;
            intent_ = new Intent(context, TOCActivity_.class);
        }

        public IntentBuilder_(Fragment fragment) {
            fragmentSupport_ = fragment;
            context_ = fragment.getActivity();
            intent_ = new Intent(context_, TOCActivity_.class);
        }

        public Intent get() {
            return intent_;
        }

        public TOCActivity_.IntentBuilder_ flags(int flags) {
            intent_.setFlags(flags);
            return this;
        }

        public void start() {
            context_.startActivity(intent_);
        }

        public void startForResult(int requestCode) {
            if (fragmentSupport_!= null) {
                fragmentSupport_.startActivityForResult(intent_, requestCode);
            } else {
                if (context_ instanceof Activity) {
                    ((Activity) context_).startActivityForResult(intent_, requestCode);
                } else {
                    context_.startActivity(intent_);
                }
            }
        }

    }

}


text:
<?php

/**
 * This file is part of the Spryker Demoshop.
 * For full license information, please view the LICENSE file that was distributed with this source code.
 */

namespace Orm\Zed\Newsletter\Persistence;

use Spryker\Zed\Newsletter\Persistence\Propel\AbstractSpyNewsletterType as BaseSpyNewsletterType;

/**
 * Skeleton subclass for representing a row from the 'spy_newsletter_type' table.
 *
 *
 *
 * You should add additional methods to this class to meet the
 * application requirements. This class will only be generated as
 * long as it does not already exist in the output directory.
 */
class SpyNewsletterType extends BaseSpyNewsletterType
{
}


text:
/* eslint-env mocha */
'use strict'

const { getDescribe, getIt } = require('../utils/mocha')
const { expectIsBitswap } = require('./utils')

/** @typedef { import("ipfsd-ctl/src/factory") } Factory */
/**
 * @param {Factory} common
 * @param {Object} options
 */
module.exports = (common, options) => {
  const describe = getDescribe(options)
  const it = getIt(options)

  describe('.stats.bitswap', () => {
    let ipfs

    before(async () => {
      ipfs = (await common.spawn()).api
    })

    after(() => common.clean())

    it('should get bitswap stats', async () => {
      const res = await ipfs.stats.bitswap()
      expectIsBitswap(null, res)
    })
  })
}


text:
@interface KBButtonView : YOView

@property (readonly) KBButton *button;

+ (instancetype)buttonViewWithView:(YOView *)view targetBlock:(dispatch_block_t)targetBlock;

- (void)setView:(YOView *)view;

- (void)setButtonStyle:(KBButtonStyle)style options:(KBButtonOptions)options;

@end


text:
{% extends "skins/base.html" %}

{% load i18n controller_base_tags static mc2_tags %}

{% block extra_css %}
    <link rel="stylesheet" href= "{% static "css/home.css" %}"/>
{% endblock %}

{% block page_header_title %}
{% endblock %}

{% block left-sidebar %}

MENU

 Home

 Dashboard

{% endblock %}

{% block content %}

        Running Applications – {{controller_list.count}}/Unlimited

    {% if user.is_superuser or is_admin %}

Choose app type

                        Basic
                        Docker

Create an app

Setup and create a new app

    {% endif %}

      {% for controller in controller_list %}
      {% render_controller controller %}
      {% endfor %}

{% endblock %}

{% block script %}

{% endblock %}