text:
"use strict";
const mongoose = require('mongoose');
const hm = require('./history-model');
const async = require('async')

module.exports = function historyPlugin(schema, options) {
  const customCollectionName  = options && options.customCollectionName;
  const customDiffAlgo = options && options.customDiffAlgo;
  const diffOnly  = options && options.diffOnly;
  const metadata = options && options.metadata;

  // Clear all history collection from Schema
  schema.statics.historyModel = function() {
    return hm.HistoryModel(hm.historyCollectionName(this.collection.name, customCollectionName), options);
  };

  // Clear all history documents from history collection
  schema.statics.clearHistory = function(callback) {
    const History = hm.HistoryModel(hm.historyCollectionName(this.collection.name, customCollectionName), options);
    History.remove({}, function(err) {
      callback(err);
    });
  };

  // Save original data
  schema.post( 'init', function() {
    if (diffOnly){
      this._original = this.toObject();
    }
  });

  function setMetadata(original, d, historyDoc, callback){
    async.each(metadata, (m, cb) => {
      if (typeof(m.value) === 'function'){
        if (m.value.length === 3){
          /** async function */
          m.value(original, d, function(err, data){
            if (err) cb(err);
            historyDoc[m.key] = data;
            cb();
          })
        } else {
          historyDoc[m.key] = m.value(original, d);
          cb();
        }
      } else {
        historyDoc[ m.key] = d ? d[ m.value] : null;
        cb();
      }
    }, callback)
  }

  // Create a copy when insert or update, or a diff log
  schema.pre('save', function(next) {
    let historyDoc = {};

    if(diffOnly && !this.isNew) {
      var original = this._original;
      delete this._original;
      var d = this.toObject();
      var diff = {};
      diff['_id'] = d['_id'];
      for(var k in d){
        if(customDiffAlgo) {
          var customDiff = customDiffAlgo(k, d[k], original[k]);
          if(customDiff) {
            diff[k] = customDiff.diff;
          }
        } else {
          if(String(d[k]) != String(original[k])){
            diff[k] = d[k];
          }
        }
      }

      historyDoc = createHistoryDoc(diff, 'u');
    } else {
      var d = this.toObject();
      let operation = this.isNew ? 'i' : 'u';
      historyDoc = createHistoryDoc(d, operation);
    }

    saveHistoryModel(original, d, historyDoc, this.collection.name, next);
  });

  // Listen on update
  schema.pre('update', function(next) {
      processUpdate.call(this, next);
  });

  // Listen on updateOne
  schema.pre('updateOne', function (next) {
      processUpdate.call(this, next);
  });

  // Listen on findOneAndUpdate
  schema.pre('findOneAndUpdate', function (next) {
      processUpdate.call(this, next);
  });

  // Create a copy on remove
  schema.pre('remove', function(next) {
    let d = this.toObject();
    let historyDoc = createHistoryDoc(d, 'r');

    saveHistoryModel(this.toObject(), d, historyDoc, this.collection.name, next);
  });

  // Create a copy on findOneAndRemove
  schema.post('findOneAndRemove', function (doc, next) {
    processRemove.call(this, doc, next);
  });

  function createHistoryDoc(d, operation) {
    const { __v, ...doc } = d;

    let historyDoc = {};
    historyDoc['t'] = new Date();
    historyDoc['o'] = operation;
    historyDoc['d'] = doc;

    return historyDoc;
  }

  function saveHistoryModel(original, d, historyDoc, collectionName, next) {
    if (metadata) {
      setMetadata(original, d, historyDoc, (err) => {
        if (err) return next(err);
        let history = new hm.HistoryModel(hm.historyCollectionName(collectionName, customCollectionName), options)(historyDoc);
        history.save(next);
      });
    } else {
      let history = new hm.HistoryModel(hm.historyCollectionName(collectionName, customCollectionName), options)(historyDoc);
      history.save(next);
    }
  }

  function processUpdate(next) {
    let d = this._update.$set || this._update;
    let historyDoc = createHistoryDoc(d, 'u');

    saveHistoryModel(this.toObject, d, historyDoc, this.mongooseCollection.collectionName, next);
  }

  function processRemove(doc, next) {
    let d = doc.toObject();
    let historyDoc = createHistoryDoc(d, 'r');

    saveHistoryModel(this.toObject, d, historyDoc, this.mongooseCollection.collectionName, next);
  }

};


text:
namespace android_webview {

JsReplyProxy::JsReplyProxy(
    mojo::PendingAssociatedRemote<mojom::JavaToJsMessaging>
        java_to_js_messaging)
    : java_to_js_messaging_(std::move(java_to_js_messaging)) {
  JNIEnv* env = base::android::AttachCurrentThread();
  java_ref_.Reset(
      Java_JsReplyProxy_create(env, reinterpret_cast<intptr_t>(this)));
}

JsReplyProxy::~JsReplyProxy() {
  if (java_ref_.is_null())
    return;

  JNIEnv* env = base::android::AttachCurrentThread();
  Java_JsReplyProxy_onDestroy(env, java_ref_);
}

base::android::ScopedJavaLocalRef<jobject> JsReplyProxy::GetJavaPeer() {
  return base::android::ScopedJavaLocalRef<jobject>(java_ref_);
}

void JsReplyProxy::PostMessage(
    JNIEnv* env,
    const base::android::JavaParamRef<jstring>& message) {
  DCHECK(java_to_js_messaging_);
  java_to_js_messaging_->OnPostMessage(
      base::android::ConvertJavaStringToUTF16(env, message));
}

}  // namespace android_webview

redpajama_set_name: RedPajamaGithub


text:
import time
import gevent
import gipc
import random
from devp2p.service import BaseService
from devp2p.app import BaseApp
from ethereum.ethpow import mine, TT64M1
from ethereum.slogging import get_logger
log = get_logger('pow')
log_sub = get_logger('pow.subprocess')

class Miner(gevent.Greenlet):

    rounds = 100
    max_elapsed = 1.

    def __init__(self, mining_hash, block_number, difficulty, nonce_callback,
                 hashrate_callback, cpu_pct=100):
        self.mining_hash = mining_hash
        self.block_number = block_number
        self.difficulty = difficulty
        self.nonce_callback = nonce_callback
        self.hashrate_callback = hashrate_callback
        self.cpu_pct = cpu_pct
        self.last = time.time()
        self.is_stopped = False
        super(Miner, self).__init__()

    def _run(self):
        nonce = random.randint(0, TT64M1)
        while not self.is_stopped:
            log_sub.debug('starting mining round')
            st = time.time()
            bin_nonce, mixhash = mine(self.block_number, self.difficulty, self.mining_hash,
                                      start_nonce=nonce, rounds=self.rounds)
            elapsed = time.time() - st
            if bin_nonce:
                log_sub.debug('nonce found')
                self.nonce_callback(bin_nonce, mixhash, self.mining_hash)
                break
            delay = elapsed * (1 - self.cpu_pct / 100.)
            hashrate = int(self.rounds // (elapsed + delay))
            self.hashrate_callback(hashrate)
            log_sub.debug('sleeping', delay=delay, elapsed=elapsed, rounds=self.rounds)
            gevent.sleep(delay + 0.001)
            nonce += self.rounds
            # adjust
            adjust = elapsed / self.max_elapsed
            self.rounds = int(self.rounds / adjust)

        log_sub.debug('mining task finished', is_stopped=self.is_stopped)

    def stop(self):
        self.is_stopped = True
        self.join()

class PoWWorker(object):

    """
    communicates with the parent process using: tuple(str_cmd, dict_kargs)
    """

    def __init__(self, cpipe, cpu_pct):
        self.cpipe = cpipe
        self.miner = None
        self.cpu_pct = cpu_pct

    def send_found_nonce(self, bin_nonce, mixhash, mining_hash):
        log_sub.debug('sending nonce')
        self.cpipe.put(('found_nonce', dict(bin_nonce=bin_nonce, mixhash=mixhash,
                                            mining_hash=mining_hash)))

    def send_hashrate(self, hashrate):
        log_sub.debug('sending hashrate')
        self.cpipe.put(('hashrate', dict(hashrate=hashrate)))

    def recv_set_cpu_pct(self, cpu_pct):
        self.cpu_pct = max(0, min(100, cpu_pct))
        if self.miner:
            self.miner.cpu_pct = self.cpu_pct

    def recv_mine(self, mining_hash, block_number, difficulty):
        "restarts the miner"
        log_sub.debug('received new new mining task')
        assert isinstance(block_number, int)
        if self.miner:
            self.miner.stop()
        self.miner = Miner(mining_hash, block_number, difficulty, self.send_found_nonce,
                           self.send_hashrate, self.cpu_pct)
        self.miner.start()

    def run(self):
        while True:
            cmd, kargs = self.cpipe.get()
            assert isinstance(kargs, dict)
            getattr(self, 'recv_' + cmd)(**kargs)

def powworker_process(cpipe, cpu_pct):
    "entry point in forked sub processes, setup env"
    gevent.get_hub().SYSTEM_ERROR = BaseException  # stop on any exception
    PoWWorker(cpipe, cpu_pct).run()

# parent process defined below ##############################################3

class PoWService(BaseService):

    name = 'pow'
    default_config = dict(pow=dict(activated=False, cpu_pct=100))

    def __init__(self, app):
        super(PoWService, self).__init__(app)
        cpu_pct = self.app.config['pow']['cpu_pct']
        self.cpipe, self.ppipe = gipc.pipe(duplex=True)
        self.worker_process = gipc.start_process(
            target=powworker_process, args=(self.cpipe, cpu_pct))
        self.app.services.chain.on_new_head_candidate_cbs.append(self.on_new_head_candidate)
        self.hashrate = 0

    @property
    def active(self):
        return self.app.config['pow']['activated']

    def on_new_head_candidate(self, block):
        log.debug('new head candidate', block_number=block.number,
                  mining_hash=block.mining_hash.encode('hex'), activated=self.active)
        if self.active and not self.app.services.chain.is_syncing:
            self.ppipe.put(('mine', dict(mining_hash=block.mining_hash,
                                         block_number=block.number, difficulty=block.difficulty)))

    def recv_hashrate(self, hashrate):
        log.debug('hashrate updated', hashrate=hashrate)
        self.hashrate = hashrate

    def recv_found_nonce(self, bin_nonce, mixhash, mining_hash):
        log.debug('nonce found', mining_hash=mining_hash.encode('hex'))
        blk = app.services.chain.chain.head_candidate
        if blk.mining_hash != mining_hash:
            log.debug('mining_hash does not match')
            return
        blk.mixhash = mixhash
        blk.nonce = bin_nonce
        app.services.chain.add_mined_block(blk)

    def _run(self):
        self.on_new_head_candidate(self.app.services.chain.chain.head_candidate)
        while True:
            cmd, kargs = self.ppipe.get()
            assert isinstance(kargs, dict)
            getattr(self, 'recv_' + cmd)(**kargs)

    def stop(self):
        self.worker_process.terminate()
        self.worker_process.join()
        super(PoWService, self).stop()

if __name__ == "__main__":
    app = BaseApp()
    PoWService.register_with_app(app)
    app.start()


text:
package bashir

import (
	"fmt"
	"os"
	"path/filepath"
	"regexp"

	prompt "github.com/segmentio/go-prompt"
)

type CommandGenerator struct {
	config  *Config
	maker   *EnvVarMaker
	matcher *regexp.Regexp
}

func NewCommandGenerator(config *Config) *CommandGenerator {
	maker := NewEnvVarMaker()
	matcher := regexp.MustCompile("(.*):ask\\?")

	return &CommandGenerator{
		config:  config,
		maker:   maker,
		matcher: matcher,
	}
}

func (c *CommandGenerator) GetEnvVarArgs(envVars []string) []string {
	out := []string{}

	for _, v := range envVars {
		val, err := c.maker.GetEnvVarValue(v)
		if err != nil {
			// warn? exit?
		}
		out = append(out, "-e", val)
	}

	return out
}

func (c *CommandGenerator) GetEnvVarsArguments(command Command) []string {
	defaultEnvVars := c.config.Defaults.EnvVars
	commandEnvVars := command.EnvVars

	out := []string{}

	out = append(out, c.GetEnvVarArgs(defaultEnvVars)...)
	out = append(out, c.GetEnvVarArgs(commandEnvVars)...)

	return out
}

func (c *CommandGenerator) IsArgumentAskable(arg string) (substring string, ask bool) {
	substring = ""
	ask = c.matcher.MatchString(arg)

	if ask {
		substring = c.matcher.FindStringSubmatch(arg)[1]
	}

	return
}

func (c *CommandGenerator) GetArgumentValueOrAsk(arguments []string) []string {
	out := []string{}

	for _, val := range arguments {
		name, askable := c.IsArgumentAskable(val)

		if askable {
			val = prompt.String(fmt.Sprintf("Value for %s?", name))
		}

		out = append(out, val)
	}

	return out
}

func (c *CommandGenerator) GetArgs(command Command) []string {
	defaultArgs := c.config.Defaults.Args
	commandArgs := command.Args
	out := []string{}

	out = append(out, c.GetArgumentValueOrAsk(defaultArgs)...)
	out = append(out, c.GetArgumentValueOrAsk(commandArgs)...)

	return out
}

func (c *CommandGenerator) GetVolumeArguments(command Command) []string {
	defaultVolumeArgs := c.config.Defaults.Volumes
	out := []string{}

	out = append(out, c.GetVolumeArgs(defaultVolumeArgs)...)

	fmt.Println(out)

	return out
}

func (c *CommandGenerator) GetVolumeArgs(volumes []string) []string {
	out := []string{}

	for _, v := range volumes {

		if v[0] == '~' {
			dir := os.Getenv("HOME")
			v = filepath.Join(dir, v[1:])
		}

		out = append(out, "-v", v)
	}

	return out
}


text:
use crate::cache::{Cache, CacheRead, CacheWrite, Storage};
use crate::errors::*;
use crate::util::SpawnExt;
use futures_03::executor::ThreadPool;
use memcached::client::Client;
use memcached::proto::NoReplyOperation;
use memcached::proto::Operation;
use memcached::proto::ProtoType::Binary;
use std::cell::RefCell;
use std::io::Cursor;
use std::time::{Duration, Instant};

thread_local! {
    static CLIENT: RefCell<Option<Client>> = RefCell::default();
}

#[derive(Clone)]
pub struct MemcachedCache {
    url: String,
    pool: ThreadPool,
}

impl MemcachedCache {
    pub fn new(url: &str, pool: &ThreadPool) -> Result<MemcachedCache> {
        Ok(MemcachedCache {
            url: url.to_owned(),
            pool: pool.clone(),
        })
    }

    fn parse(&self) -> Vec<(&str, usize)> {
        self.url.split_whitespace().map(|w| (w, 1usize)).collect()
    }

    fn exec<U, F>(&self, f: F) -> U
    where
        F: FnOnce(&mut Client) -> U,
    {
        CLIENT.with(|rc| {
            match *rc.borrow_mut() {
                ref mut opt @ Some(_) => opt,
                ref mut opt @ None => {
                    *opt = Some(Client::connect(&self.parse(), Binary).unwrap());
                    opt
                }
            }
            .as_mut()
            .map(f)
            .unwrap()
        })
    }
}

impl Storage for MemcachedCache {
    fn get(&self, key: &str) -> SFuture<Cache> {
        let key = key.to_owned();
        let me = self.clone();
        Box::new(self.pool.spawn_fn(move || {
            me.exec(|c| c.get(&key.as_bytes()))
                .map(|(d, _)| CacheRead::from(Cursor::new(d)).map(Cache::Hit))
                .unwrap_or(Ok(Cache::Miss))
        }))
    }

    fn put(&self, key: &str, entry: CacheWrite) -> SFuture<Duration> {
        let key = key.to_owned();
        let me = self.clone();
        Box::new(self.pool.spawn_fn(move || {
            let start = Instant::now();
            let d = entry.finish()?;
            me.exec(|c| c.set_noreply(&key.as_bytes(), &d, 0, 0))?;
            Ok(start.elapsed())
        }))
    }

    fn location(&self) -> String {
        format!("Memcached: {}", self.url)
    }

    fn current_size(&self) -> SFuture<Option<u64>> {
        f_ok(None)
    }
    fn max_size(&self) -> SFuture<Option<u64>> {
        f_ok(None)
    }
}


text:
package com.quarkworks.dynamicpageradapter_android.single_view_type;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.quarkworks.dynamicpageradapter_android.R;

/**
 * @author jacobamuchow@gmail.com (Jacob Muchow)
 */
public class PagerCardView extends RelativeLayout {
    private static final String TAG = PagerCardView.class.getSimpleName();

    private int position = 0;

    private TextView textView;

    @Nullable private PagerViewCallbacks pagerViewCallbacks;

    public PagerCardView(Context context) {
        super(context);
        initialize();
    }

    public PagerCardView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialize();
    }

    public PagerCardView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize();
    }

    private void initialize() {
        LayoutInflater.from(getContext()).inflate(R.layout.pager_card_view, this);

        textView = (TextView) findViewById(R.id.pager_card_view_text);
        View dismissButton = findViewById(R.id.pager_card_view_dismiss_button);

        dismissButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(pagerViewCallbacks != null) {
                    pagerViewCallbacks.dismissClicked(position);
                }
            }
        });
    }

    public void setViewData(int position) {
        this.position = position;
        textView.setText(String.valueOf(position));
    }

    public int getPosition() {
        return position;
    }

    public void setPagerViewCallbacks(@Nullable PagerViewCallbacks pagerViewCallbacks) {
        this.pagerViewCallbacks = pagerViewCallbacks;
    }

    public interface PagerViewCallbacks {
        void dismissClicked(int position);
    }
}


text:
namespace v8 {
namespace internal {

#ifdef ENABLE_DEBUGGER_SUPPORT
bool BreakLocationIterator::IsDebugBreakAtReturn() {
  return Debug::IsDebugBreakAtReturn(rinfo());
}

void BreakLocationIterator::SetDebugBreakAtReturn() {
  UNIMPLEMENTED_MIPS();
}

// Restore the JS frame exit code.
void BreakLocationIterator::ClearDebugBreakAtReturn() {
  UNIMPLEMENTED_MIPS();
}

// A debug break in the exit code is identified by a call.
bool Debug::IsDebugBreakAtReturn(RelocInfo* rinfo) {
  ASSERT(RelocInfo::IsJSReturn(rinfo->rmode()));
  return rinfo->IsPatchedReturnSequence();
}

#define __ ACCESS_MASM(masm)

void Debug::GenerateLoadICDebugBreak(MacroAssembler* masm) {
  UNIMPLEMENTED_MIPS();
}

void Debug::GenerateStoreICDebugBreak(MacroAssembler* masm) {
  UNIMPLEMENTED_MIPS();
}

void Debug::GenerateKeyedLoadICDebugBreak(MacroAssembler* masm) {
  UNIMPLEMENTED_MIPS();
}

void Debug::GenerateKeyedStoreICDebugBreak(MacroAssembler* masm) {
  UNIMPLEMENTED_MIPS();
}

void Debug::GenerateCallICDebugBreak(MacroAssembler* masm) {
  UNIMPLEMENTED_MIPS();
}

void Debug::GenerateConstructCallDebugBreak(MacroAssembler* masm) {
  UNIMPLEMENTED_MIPS();
}

void Debug::GenerateReturnDebugBreak(MacroAssembler* masm) {
  UNIMPLEMENTED_MIPS();
}

void Debug::GenerateStubNoRegistersDebugBreak(MacroAssembler* masm) {
  UNIMPLEMENTED_MIPS();
}

void Debug::GeneratePlainReturnLiveEdit(MacroAssembler* masm) {
  masm->Abort("LiveEdit frame dropping is not supported on mips");
}

void Debug::GenerateFrameDropperLiveEdit(MacroAssembler* masm) {
  masm->Abort("LiveEdit frame dropping is not supported on mips");
}

#undef __

void Debug::SetUpFrameDropperFrame(StackFrame* bottom_js_frame,
                                   Handle<Code> code) {
  UNREACHABLE();
}
const int Debug::kFrameDropperFrameSize = -1;

#endif  // ENABLE_DEBUGGER_SUPPORT

} }  // namespace v8::internal

#endif  // V8_TARGET_ARCH_MIPS


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

  <title>{% if page.title %}{{ page.title }}{% else %}{{ site.title }}{% endif %}</title>
  <meta name="description" content="{% if page.excerpt %}{{ page.excerpt | strip_html | strip_newlines | truncate: 160 }}{% endif %}">

  <link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}">
  <link rel="stylesheet" href="{{ "/custom.css" | prepend: site.baseurl }}">
  <link rel="canonical" href="{{ page.url | replace:'index.html','' | prepend: site.baseurl | prepend: site.url }}">
  <link rel="alternate" type="application/rss+xml" title="{{ site.title }}" href="{{ "/feed.xml" | prepend: site.baseurl | prepend: site.url }}" />
  <link rel="alternate" type="application/json" title="{{ site.title }}" href="{{ "/feed.json" | prepend: site.baseurl | prepend: site.url }}" />
  <link rel="EditURI" type="application/rsd+xml" href="{{ site.baseurl }}/rsd.xml" />
  <link rel="me" href="https://micro.blog/{{ site.username }}" />
  {% if site.twitter_username != "" %}
  	<link rel="me" href="https://twitter.com/{{ site.twitter_username }}" />
  {% endif %}
  {% if site.github_username != "" %}
  	<link rel="me" href="https://github.com/{{ site.github_username }}" />
  {% endif %}
  {% if site.instagram_username != "" %}
  	<link rel="me" href="https://instagram.com/{{ site.instagram_username }}" />
  {% endif %}
  <link rel="authorization_endpoint" href="https://indieauth.com/auth" />
  <link rel="token_endpoint" href="https://tokens.indieauth.com/token" />
  <link rel="micropub" href="https://micro.blog/micropub" />
  <link rel="webmention" href="https://micro.blog/webmention" />
</head>


text:
/*
* (C) 2015,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include "fuzzers.h"
#include <botan/pk_keys.h>
#include <botan/pkcs8.h>
#include <botan/data_src.h>

void fuzz(const uint8_t in[], size_t len)
   {
   try
      {
      Botan::DataSource_Memory input(in, len);
      Botan::Null_RNG null_rng;
      std::unique_ptr<Botan::Private_Key> key(Botan::PKCS8::load_key(input, null_rng));
      }
   catch(Botan::Exception& e) { }
   }


text:
import date = require("../date")
import Candle = require("../models/candle");

class CandleResampler {
    private destCandle: Candle;
    private opposingVolume: number;
    private buy_opposingVolume: number;
    private sell_opposingVolume: number;

    constructor(private period: number, private onCandle: (c: Candle) => void) { }

    private resetCandle(start: Date) {
        this.destCandle = new Candle(date.roundDown(start, this.period), this.period);
        this.opposingVolume = 0;
        this.buy_opposingVolume = 0;
        this.sell_opposingVolume = 0;
    }

    private sendCandle() {
        if (this.destCandle.volume)
            this.destCandle.vwap = this.opposingVolume / this.destCandle.volume;
        if (this.destCandle.buy_volume)
            this.destCandle.buy_vwap = this.buy_opposingVolume / this.destCandle.buy_volume;
        if (this.destCandle.sell_volume)
            this.destCandle.sell_vwap = this.sell_opposingVolume / this.destCandle.sell_volume;
        this.onCandle(this.destCandle);
        this.destCandle = null;
    }

    public sendIncompleteCandle() {
        if (this.destCandle)
            this.sendCandle();
    }

    public feedCandle(c: Candle) {
        if (this.destCandle && c.start >= this.destCandle.end)
            this.sendCandle();
        if (!this.destCandle)
            this.resetCandle(c.start);

        if (this.destCandle.open === undefined)
            this.destCandle.open = c.open;
        if (c.close !== undefined)
            this.destCandle.close = c.close;
        if (this.destCandle.low === undefined || c.low < this.destCandle.low)
            this.destCandle.low = c.low;
        if (this.destCandle.high === undefined || c.high > this.destCandle.high)
            this.destCandle.high = c.high;
        this.destCandle.volume += c.volume;
        if (c.volume)
            this.opposingVolume += c.volume * c.vwap;
        this.destCandle.count += c.count;

        if (this.destCandle.buy_open === undefined)
            this.destCandle.buy_open = c.buy_open;
        if (c.buy_close !== undefined)
            this.destCandle.buy_close = c.buy_close;
        if (this.destCandle.buy_low === undefined || c.buy_low < this.destCandle.buy_low)
            this.destCandle.buy_low = c.buy_low;
        if (this.destCandle.buy_high === undefined || c.buy_high > this.destCandle.buy_high)
            this.destCandle.buy_high = c.buy_high;
        this.destCandle.buy_volume += c.buy_volume;
        if (c.buy_volume)
            this.buy_opposingVolume += c.buy_volume * c.buy_vwap;
        this.destCandle.buy_count += c.buy_count;

        if (this.destCandle.sell_open === undefined)
            this.destCandle.sell_open = c.sell_open;
        if (c.sell_close !== undefined)
            this.destCandle.sell_close = c.sell_close;
        if (this.destCandle.sell_low === undefined || c.sell_low < this.destCandle.sell_low)
            this.destCandle.sell_low = c.sell_low;
        if (this.destCandle.sell_high === undefined || c.sell_high > this.destCandle.sell_high)
            this.destCandle.sell_high = c.sell_high;
        this.destCandle.sell_volume += c.sell_volume;
        if (c.sell_volume)
            this.sell_opposingVolume += c.sell_volume * c.sell_vwap;
        this.destCandle.sell_count += c.sell_count;

        if (c.end >= this.destCandle.end)
            this.sendCandle();
    }
}

export = CandleResampler;


text:
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Chutzpah.Models;
using Microsoft.VisualStudio.TestPlatform.ObjectModel;

namespace Chutzpah.VS2012.TestAdapter
{
    public class ChutzpahAdapterSettings : TestRunSettings
    {
        public const string SettingsName = "ChutzpahAdapterSettings";

        private static readonly XmlSerializer serializer = new XmlSerializer(typeof(ChutzpahAdapterSettings));

        public ChutzpahAdapterSettings() : base(SettingsName)
        {
            TimeoutMilliseconds = null;
            TestingMode = TestingMode.JavaScript;
            MaxDegreeOfParallelism = 1;
        }

        /// <summary>
        /// How long to wait for a given test to finish before timing out? (Defaults to 5000 ms)
        /// </summary>
        public int? TimeoutMilliseconds { get; set; }

        /// <summary>
        /// Determines if we are testing JavaScript files (and creating harnesses for them), testing html test harnesses directly or both
        /// </summary>
        public TestingMode TestingMode { get; set; }

        /// <summary>
        /// Determines the maximum degree of paralleism Chutzpah should use
        /// </summary>
        public int MaxDegreeOfParallelism { get; set; }

        public override XmlElement ToXml()
        {
            var stringWriter = new StringWriter();
            serializer.Serialize(stringWriter, this);
            var xml = stringWriter.ToString();
            var document = new XmlDocument();
            document.LoadXml(xml);
            return document.DocumentElement;
        }

    }
}


text:
package org.wso2.carbon.integration.common.tests;

import org.apache.axis2.AxisFault;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.wso2.carbon.automation.engine.annotations.ExecutionEnvironment;
import org.wso2.carbon.automation.engine.annotations.SetEnvironment;
import org.wso2.carbon.automation.engine.context.AutomationContext;
import org.wso2.carbon.integration.common.admin.client.LogViewerClient;
import org.wso2.carbon.logging.view.stub.LogViewerLogViewerException;
import org.wso2.carbon.logging.view.stub.types.carbon.LogEvent;

import javax.xml.xpath.XPathExpressionException;
import java.rmi.RemoteException;

import static org.testng.Assert.assertFalse;

public abstract class ServerStartupBaseTest {
    private LogViewerClient logViewerClient;
    private static final Log log = LogFactory.getLog(ServerStartupBaseTest.class);
    private static final String SERVER_START_LINE = "Starting WSO2 Carbon";
    private static final String MANAGEMENT_CONSOLE_URL = "Mgt Console URL";
    public String productName;

    @BeforeSuite(alwaysRun = true)
    public void initialize() throws XPathExpressionException, AxisFault {
        AutomationContext autoContext = new AutomationContext();
        logViewerClient = new LogViewerClient(autoContext.getContextUrls().getBackEndUrl(),
                autoContext.getSuperTenant().getTenantAdmin().getUserName(),
                autoContext.getSuperTenant().getTenantAdmin().getPassword());
    }

    @Test(groups = "wso2.all", description = "verify server startup errors")
    @SetEnvironment(executionEnvironments = {ExecutionEnvironment.STANDALONE})
    public void testVerifyLogs() throws RemoteException, LogViewerLogViewerException {
        boolean status = false;
        int startLine = 0;
        int stopLine = 0;
        String errorMessage = "";
        LogEvent[] logEvents = logViewerClient.getAllRemoteSystemLogs();
        if (logEvents.length > 0) {
            for (int i = 0; i < logEvents.length; i++) {
                if (logEvents[i] != null) {
                    if (logEvents[i].getMessage().contains(SERVER_START_LINE)) {
                        stopLine = i;
                        log.info("Server started message found - " + logEvents[i].getMessage());
                    }
                    if (logEvents[i].getMessage().contains(MANAGEMENT_CONSOLE_URL)) {
                        startLine = i;
                        log.info("Server stopped message found - " + logEvents[i].getMessage());
                    }
                }
                if (startLine != 0 && stopLine != 0) {
                    break;
                }
            }
            while (startLine <= stopLine) {
                if (logEvents[startLine].getPriority().contains("ERROR")) {
                    errorMessage = logEvents[startLine].getMessage() +"\n" +logEvents[startLine].getStacktrace();
                    log.error("Startup contain errors - " + errorMessage);
                    status = true;
                    break;
                }
                startLine++;
            }
        }
        assertFalse(status, "Server started with errors. [" + errorMessage + "]");
    }
}


text:
/**
 * Autogenerated by Thrift Compiler (0.7.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 */
package backtype.storm.generated;

import org.apache.commons.lang.builder.HashCodeBuilder;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ComponentObject extends org.apache.thrift.TUnion<ComponentObject, ComponentObject._Fields> {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("ComponentObject");
  private static final org.apache.thrift.protocol.TField SERIALIZED_JAVA_FIELD_DESC = new org.apache.thrift.protocol.TField("serialized_java", org.apache.thrift.protocol.TType.STRING, (short)1);
  private static final org.apache.thrift.protocol.TField SHELL_FIELD_DESC = new org.apache.thrift.protocol.TField("shell", org.apache.thrift.protocol.TType.STRUCT, (short)2);
  private static final org.apache.thrift.protocol.TField JAVA_OBJECT_FIELD_DESC = new org.apache.thrift.protocol.TField("java_object", org.apache.thrift.protocol.TType.STRUCT, (short)3);

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    SERIALIZED_JAVA((short)1, "serialized_java"),
    SHELL((short)2, "shell"),
    JAVA_OBJECT((short)3, "java_object");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // SERIALIZED_JAVA
          return SERIALIZED_JAVA;
        case 2: // SHELL
          return SHELL;
        case 3: // JAVA_OBJECT
          return JAVA_OBJECT;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.SERIALIZED_JAVA, new org.apache.thrift.meta_data.FieldMetaData("serialized_java", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING        , true)));
    tmpMap.put(_Fields.SHELL, new org.apache.thrift.meta_data.FieldMetaData("shell", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, ShellComponent.class)));
    tmpMap.put(_Fields.JAVA_OBJECT, new org.apache.thrift.meta_data.FieldMetaData("java_object", org.apache.thrift.TFieldRequirementType.DEFAULT,
        new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, JavaObject.class)));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(ComponentObject.class, metaDataMap);
  }

  public ComponentObject() {
    super();
  }

  public ComponentObject(_Fields setField, Object value) {
    super(setField, value);
  }

  public ComponentObject(ComponentObject other) {
    super(other);
  }
  public ComponentObject deepCopy() {
    return new ComponentObject(this);
  }

  public static ComponentObject serialized_java(ByteBuffer value) {
    ComponentObject x = new ComponentObject();
    x.set_serialized_java(value);
    return x;
  }

  public static ComponentObject serialized_java(byte[] value) {
    ComponentObject x = new ComponentObject();
    x.set_serialized_java(ByteBuffer.wrap(value));
    return x;
  }

  public static ComponentObject shell(ShellComponent value) {
    ComponentObject x = new ComponentObject();
    x.set_shell(value);
    return x;
  }

  public static ComponentObject java_object(JavaObject value) {
    ComponentObject x = new ComponentObject();
    x.set_java_object(value);
    return x;
  }

  @Override
  protected void checkType(_Fields setField, Object value) throws ClassCastException {
    switch (setField) {
      case SERIALIZED_JAVA:
        if (value instanceof ByteBuffer) {
          break;
        }
        throw new ClassCastException("Was expecting value of type ByteBuffer for field 'serialized_java', but got " + value.getClass().getSimpleName());
      case SHELL:
        if (value instanceof ShellComponent) {
          break;
        }
        throw new ClassCastException("Was expecting value of type ShellComponent for field 'shell', but got " + value.getClass().getSimpleName());
      case JAVA_OBJECT:
        if (value instanceof JavaObject) {
          break;
        }
        throw new ClassCastException("Was expecting value of type JavaObject for field 'java_object', but got " + value.getClass().getSimpleName());
      default:
        throw new IllegalArgumentException("Unknown field id " + setField);
    }
  }

  @Override
  protected Object readValue(org.apache.thrift.protocol.TProtocol iprot, org.apache.thrift.protocol.TField field) throws org.apache.thrift.TException {
    _Fields setField = _Fields.findByThriftId(field.id);
    if (setField != null) {
      switch (setField) {
        case SERIALIZED_JAVA:
          if (field.type == SERIALIZED_JAVA_FIELD_DESC.type) {
            ByteBuffer serialized_java;
            serialized_java = iprot.readBinary();
            return serialized_java;
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
            return null;
          }
        case SHELL:
          if (field.type == SHELL_FIELD_DESC.type) {
            ShellComponent shell;
            shell = new ShellComponent();
            shell.read(iprot);
            return shell;
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
            return null;
          }
        case JAVA_OBJECT:
          if (field.type == JAVA_OBJECT_FIELD_DESC.type) {
            JavaObject java_object;
            java_object = new JavaObject();
            java_object.read(iprot);
            return java_object;
          } else {
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
            return null;
          }
        default:
          throw new IllegalStateException("setField wasn't null, but didn't match any of the case statements!");
      }
    } else {
      org.apache.thrift.protocol.TProtocolUtil.skip(iprot, field.type);
      return null;
    }
  }

  @Override
  protected void writeValue(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    switch (setField_) {
      case SERIALIZED_JAVA:
        ByteBuffer serialized_java = (ByteBuffer)value_;
        oprot.writeBinary(serialized_java);
        return;
      case SHELL:
        ShellComponent shell = (ShellComponent)value_;
        shell.write(oprot);
        return;
      case JAVA_OBJECT:
        JavaObject java_object = (JavaObject)value_;
        java_object.write(oprot);
        return;
      default:
        throw new IllegalStateException("Cannot write union with unknown field " + setField_);
    }
  }

  @Override
  protected org.apache.thrift.protocol.TField getFieldDesc(_Fields setField) {
    switch (setField) {
      case SERIALIZED_JAVA:
        return SERIALIZED_JAVA_FIELD_DESC;
      case SHELL:
        return SHELL_FIELD_DESC;
      case JAVA_OBJECT:
        return JAVA_OBJECT_FIELD_DESC;
      default:
        throw new IllegalArgumentException("Unknown field id " + setField);
    }
  }

  @Override
  protected org.apache.thrift.protocol.TStruct getStructDesc() {
    return STRUCT_DESC;
  }

  @Override
  protected _Fields enumForId(short id) {
    return _Fields.findByThriftIdOrThrow(id);
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public byte[] get_serialized_java() {
    set_serialized_java(org.apache.thrift.TBaseHelper.rightSize(buffer_for_serialized_java()));
    ByteBuffer b = buffer_for_serialized_java();
    return b == null ? null : b.array();
  }

  public ByteBuffer buffer_for_serialized_java() {
    if (getSetField() == _Fields.SERIALIZED_JAVA) {
      return (ByteBuffer)getFieldValue();
    } else {
      throw new RuntimeException("Cannot get field 'serialized_java' because union is currently set to " + getFieldDesc(getSetField()).name);
    }
  }

  public void set_serialized_java(byte[] value) {
    set_serialized_java(ByteBuffer.wrap(value));
  }

  public void set_serialized_java(ByteBuffer value) {
    if (value == null) throw new NullPointerException();
    setField_ = _Fields.SERIALIZED_JAVA;
    value_ = value;
  }

  public ShellComponent get_shell() {
    if (getSetField() == _Fields.SHELL) {
      return (ShellComponent)getFieldValue();
    } else {
      throw new RuntimeException("Cannot get field 'shell' because union is currently set to " + getFieldDesc(getSetField()).name);
    }
  }

  public void set_shell(ShellComponent value) {
    if (value == null) throw new NullPointerException();
    setField_ = _Fields.SHELL;
    value_ = value;
  }

  public JavaObject get_java_object() {
    if (getSetField() == _Fields.JAVA_OBJECT) {
      return (JavaObject)getFieldValue();
    } else {
      throw new RuntimeException("Cannot get field 'java_object' because union is currently set to " + getFieldDesc(getSetField()).name);
    }
  }

  public void set_java_object(JavaObject value) {
    if (value == null) throw new NullPointerException();
    setField_ = _Fields.JAVA_OBJECT;
    value_ = value;
  }

  public boolean is_set_serialized_java() {
    return setField_ == _Fields.SERIALIZED_JAVA;
  }

  public boolean is_set_shell() {
    return setField_ == _Fields.SHELL;
  }

  public boolean is_set_java_object() {
    return setField_ == _Fields.JAVA_OBJECT;
  }

  public boolean equals(Object other) {
    if (other instanceof ComponentObject) {
      return equals((ComponentObject)other);
    } else {
      return false;
    }
  }

  public boolean equals(ComponentObject other) {
    return other != null && getSetField() == other.getSetField() && getFieldValue().equals(other.getFieldValue());
  }

  @Override
  public int compareTo(ComponentObject other) {
    int lastComparison = org.apache.thrift.TBaseHelper.compareTo(getSetField(), other.getSetField());
    if (lastComparison == 0) {
      return org.apache.thrift.TBaseHelper.compareTo(getFieldValue(), other.getFieldValue());
    }
    return lastComparison;
  }

  @Override
  public int hashCode() {
    HashCodeBuilder hcb = new HashCodeBuilder();
    hcb.append(this.getClass().getName());
    org.apache.thrift.TFieldIdEnum setField = getSetField();
    if (setField != null) {
      hcb.append(setField.getThriftFieldId());
      Object value = getFieldValue();
      if (value instanceof org.apache.thrift.TEnum) {
        hcb.append(((org.apache.thrift.TEnum)getFieldValue()).getValue());
      } else {
        hcb.append(value);
      }
    }
    return hcb.toHashCode();
  }
  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

}


text: <!DOCTYPE html>


text:
"""Unit tests for watchlists.py."""

# pylint: disable=E1103,E1120,W0212

import os
import sys

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from testing_support import super_mox

import watchlists

class WatchlistsTest(super_mox.SuperMoxTestBase):

  def setUp(self):
    super_mox.SuperMoxTestBase.setUp(self)
    self.mox.StubOutWithMock(watchlists.Watchlists, '_HasWatchlistsFile')
    self.mox.StubOutWithMock(watchlists.Watchlists, '_ContentsOfWatchlistsFile')
    self.mox.StubOutWithMock(watchlists.logging, 'error')

  def testMissingWatchlistsFileOK(self):
    """Test that we act gracefully if WATCHLISTS file is missing."""
    watchlists.Watchlists._HasWatchlistsFile().AndReturn(False)
    self.mox.ReplayAll()

    wl = watchlists.Watchlists('/some/random/path')
    self.assertEqual(wl.GetWatchersForPaths(['some_path']), [])

  def testGarbledWatchlistsFileOK(self):
    """Test that we act gracefully if WATCHLISTS file is garbled."""
    contents = 'some garbled and unwanted text'
    watchlists.Watchlists._HasWatchlistsFile().AndReturn(True)
    watchlists.Watchlists._ContentsOfWatchlistsFile().AndReturn(contents)
    watchlists.logging.error(super_mox.mox.IgnoreArg())
    self.mox.ReplayAll()

    wl = watchlists.Watchlists('/a/path')
    self.assertEqual(wl.GetWatchersForPaths(['some_path']), [])

  def testNoWatchers(self):
    contents = \
      """{
        'WATCHLIST_DEFINITIONS': {
          'a_module': {
            'filepath': 'a_module',
          },
        },

        'WATCHLISTS': {
          'a_module': [],
        },
      } """
    watchlists.Watchlists._HasWatchlistsFile().AndReturn(True)
    watchlists.Watchlists._ContentsOfWatchlistsFile().AndReturn(contents)
    self.mox.ReplayAll()

    wl = watchlists.Watchlists('/a/path')
    self.assertEqual(wl.GetWatchersForPaths(['a_module']), [])

  def testValidWatcher(self):
    watchers = ['abc@def.com', 'x1@xyz.org']
    contents = \
      """{
        'WATCHLIST_DEFINITIONS': {
          'a_module': {
            'filepath': 'a_module',
          },
        },
        'WATCHLISTS': {
          'a_module': %s,
        },
      } """ % watchers
    watchlists.Watchlists._HasWatchlistsFile().AndReturn(True)
    watchlists.Watchlists._ContentsOfWatchlistsFile().AndReturn(contents)
    self.mox.ReplayAll()

    wl = watchlists.Watchlists('/a/path')
    self.assertEqual(wl.GetWatchersForPaths(['a_module']), watchers)

  def testMultipleWatchlistsTrigger(self):
    """Test that multiple watchlists can get triggered for one filepath."""
    contents = \
      """{
        'WATCHLIST_DEFINITIONS': {
          'mac': {
            'filepath': 'mac',
          },
          'views': {
            'filepath': 'views',
          },
        },
        'WATCHLISTS': {
          'mac': ['x1@chromium.org'],
          'views': ['x2@chromium.org'],
        },
      } """
    watchlists.Watchlists._HasWatchlistsFile().AndReturn(True)
    watchlists.Watchlists._ContentsOfWatchlistsFile().AndReturn(contents)
    self.mox.ReplayAll()

    wl = watchlists.Watchlists('/a/path')
    self.assertEqual(wl.GetWatchersForPaths(['file_views_mac']),
        ['x1@chromium.org', 'x2@chromium.org'])

  def testDuplicateWatchers(self):
    """Test that multiple watchlists can get triggered for one filepath."""
    watchers = ['someone@chromium.org']
    contents = \
      """{
        'WATCHLIST_DEFINITIONS': {
          'mac': {
            'filepath': 'mac',
          },
          'views': {
            'filepath': 'views',
          },
        },
        'WATCHLISTS': {
          'mac': %s,
          'views': %s,
        },
      } """ % (watchers, watchers)
    watchlists.Watchlists._HasWatchlistsFile().AndReturn(True)
    watchlists.Watchlists._ContentsOfWatchlistsFile().AndReturn(contents)
    self.mox.ReplayAll()

    wl = watchlists.Watchlists('/a/path')
    self.assertEqual(wl.GetWatchersForPaths(['file_views_mac']), watchers)

  def testWinPathWatchers(self):
    """Test watchers for a windows path (containing backward slashes)."""
    watchers = ['abc@def.com', 'x1@xyz.org']
    contents = \
      """{
        'WATCHLIST_DEFINITIONS': {
          'browser': {
            'filepath': 'chrome/browser/.*',
          },
        },
        'WATCHLISTS': {
          'browser': %s,
        },
      } """ % watchers
    saved_sep = watchlists.os.sep
    watchlists.os.sep = '\\'  # to pose as win32
    watchlists.Watchlists._HasWatchlistsFile().AndReturn(True)
    watchlists.Watchlists._ContentsOfWatchlistsFile().AndReturn(contents)
    self.mox.ReplayAll()

    wl = watchlists.Watchlists(r'a\path')
    returned_watchers = wl.GetWatchersForPaths(
          [r'chrome\browser\renderer_host\render_widget_host.h'])
    watchlists.os.sep = saved_sep  # revert back os.sep before asserts
    self.assertEqual(returned_watchers, watchers)

if __name__ == '__main__':
  import unittest
  unittest.main()


text:
"""
Sensitivity analysis for all versions of bridge cut
using the threshold parameters.

@author Aaron Zampaglione <azampagl@my.fit.edu>
@copyright 2011 Aaron Zampaglione
@license MIT
"""
import commands
import os

INPUT = '../data/polbooks/polbooks.txt'
OUTPUT = '../results/polbooks'

for d in range(3, 5):

    results = {'edge-c': {},
               'vertex-c': {},
            }

    start = 0
    stop = 0.96
    inc = 0.05

    DIR = OUTPUT + '/d' + str(d)

    if not os.path.exists(DIR):
        os.mkdir(DIR)

    while start < stop:
        for version in results:
            cmd = 'python main.py ' + \
                  '-i "' + INPUT + '" ' + \
                  '-o "' + DIR + '/results-' + str(version) + \
                  '-' + str(start) + '.txt" ' + \
                  '-v ' + str(version) + ' ' + \
                  '-t ' + str(start) + ' ' + \
                  '-d ' + str(d)

            # Save our response
            _, response = commands.getstatusoutput(cmd)
            results[version][start] = commands.getstatusoutput(cmd)[1].split("\t")

        start += inc

    # Print excel like table for each metric (2).
    for index in range(2):
        output = 'DEPTH: ' + str(d)
        output += 'THRESH\t' + '\t'.join(results.keys()) + '\n'
        start = 0
        while start <= stop:
            output += str(start) + "\t"
            for algo, result in results.items():
                output += result[start][index] + '\t'
            output += '\n'
            start += inc
        print(output)
        print('')
    print('')


text:
from geometry_msgs.msg import (Point, Pose, Quaternion, TransformStamped,
                               Vector3)

## Pose ##
##
def ToPose(p, o):
    return Pose(position=ToPoint(p), orientation=ToQuaternion(o))

## Point ##
##
def NewPoint(x, y, z):
    return Point(x=x, y=y, z=z)

def ToPoint(p):
    return NewPoint(*p)

def FromPoint(p):
    return (p.x, p.y, p.z)

## Orientation ##
##
def NewQuaternion(x, y, z, w):
    return Quaternion(x=x, y=y, z=z, w=w)

def ToQuaternion(q):
    return NewQuaternion(*q)

def FromQuaternion(o):
    return (o.x, o.y, o.z, o.w)

## Vector3 ##
##
def NewVector3(x, y, z):
    return Vector3(x=x, y=y, z=z)

def ToVector3(p):
    return NewVector3(*p)

def FromVector3(v):
    return (v.x, v.y, v.z)

## TransformStamped ##
##
def FromTransformStamped(msg):
    return (FromVector3(msg.transform.translation),
            FromQuaternion(msg.transform.rotation))

def ToTransformStamped(translation, rotation, stamp, child, parent):
    t = TransformStamped()
    t.header.stamp = stamp
    t.header.frame_id = parent
    t.child_frame_id = child
    t.transform.translation = ToVector3(translation)
    t.transform.rotation = ToQuaternion(rotation)
    return t

# eof


text:
/**
 * @name SDL.Label
 * @desc Universal label component for SDL application
 * @category Controlls
 * @filesource app/controlls/Label.js
 * @version 1.0
 */

SDL.Label = Em.View.extend( {
    classNameBindings: [
        'disabled'
    ],
    classNames: 'label',

    // component default template
    defaultTemplate: Em.Handlebars.compile('{{view.content}}'),

    templates: {
        icon: Em.Handlebars
            .compile(''
                + '{{view.content}}')
    }

/** Define button template */
/*
 * template: Ember.Handlebars.compile( '{{#with view}}'+ '{{#if icon}}{{/if}}'+ '{{content}}'+
 * '{{/with}}' )
 */
});


text:
#ifndef _IRTKPOINTRIGIDREGISTRATION_H

#define _IRTKPOINTRIGIDREGISTRATION_H

#include <irtkImage.h>

#include <irtkTransformation.h>

/**
 * Filter for point-based registration.
 *
 * This class implements a registration filter for point-based registration
 * of two sets of points. As an output, it returns the rigid transformation
 * coefficients in a irtkRigidTransformation class.
 *
*/

class irtkPointRigidRegistration : public irtkPointRegistration
{

protected:

  /// Initial set up for the registration
  virtual void Initialize();

  /// Optimize registration using closed form solution
  virtual void ClosedFormOptimizer();

public:

  /// Constructor
  irtkPointRigidRegistration();

  /// Destructor
  virtual ~irtkPointRigidRegistration();

  /// Sets output for the registration filter
  virtual void SetOutput(irtkTransformation *);

  /// Run the filter
  virtual void Run();

  /// Returns the name of the class
  virtual const char *NameOfClass();

};

#endif


text:
<code_scheme name="onai" version="173">
  <option name="RIGHT_MARGIN" value="95" />
</code_scheme>


text:
using namespace std;

TEST_CASE( "queue_lockfree_total stress", "[stress]" ) {
    queue_lockfree_total<int> p;
    unsigned int num_threads = 10000;
    stress_pool::stress_put_get_int( num_threads, p );
}


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new OldSound\RabbitMqBundle\OldSoundRabbitMqBundle(),
            new Beberlei\Bundle\MetricsBundle\BeberleiMetricsBundle(),

            new Alvi\Bundle\ImageProcessor\JobSubmissionBundle\AlviImageProcessorJobSubmissionBundle(),
            new Alvi\Bundle\ImageProcessor\MonitoringBundle\AlviImageProcessorMonitoringBundle(),
            new Alvi\Bundle\ImageProcessor\ProvisionerBundle\AlviImageProcessorProvisionerBundle(),
            new Alvi\Bundle\ImageProcessor\ScalerBundle\AlviImageProcessorScalerBundle(),
            new Alvi\Bundle\ImageProcessor\SchedulerBundle\AlviImageProcessorSchedulerBundle(),
            new Alvi\Bundle\ImageProcessor\WorkerBundle\AlviImageProcessorWorkerBundle(),
            new Alvi\Bundle\ImageProcessor\ZookeeperBundle\AlviImageProcessorZookeeperBundle(),
        );

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
package de.gebatzens.sia.fragment;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import java.util.Date;
import java.util.List;

import de.gebatzens.sia.SIAApp;
import de.gebatzens.sia.MainActivity;
import de.gebatzens.sia.R;
import de.gebatzens.sia.data.Subst;

public class SubstFragment extends RemoteDataFragment {

    public ViewPager mViewPager;
    public SubstAdapter substAdapter;
    public Bundle bundle;
    public TabLayout mTabLayout;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        ((MainActivity) getActivity()).updateMenu(R.menu.toolbar_menu);
        return inflater.inflate(R.layout.fragment_subst, container, false);
    }

    private int toPixels(int dp) {
        float scale = getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    public void updateTime(Date newTime) {
        List<Fragment> frags = getChildFragmentManager().getFragments();
        if(frags != null) {
            for(Fragment fr : frags) {
                if(fr != null) {
                    View v = fr.getView();
                    if (v != null) {
                        v = v.findViewWithTag("gg_time");
                        if (v != null) {
                            String diff = SubstPagerFragment.getTimeDiff(getActivity(), newTime);
                            TextView tv = (TextView) v;
                            tv.setText(diff);
                        }
                    }
                }
            }
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        bundle = ((MainActivity) getActivity()).savedState;
        mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
        substAdapter = new SubstAdapter(this, savedInstanceState, mViewPager);
        /*if(bundle != null) {
            for(int i = 0; i < substAdapter.fragments.size(); i++)
                substAdapter.fragments.get(i).spinnerPos = bundle.getInt("ggvp_frag_spinner_" + i);
        }*/
        mViewPager.setAdapter(substAdapter);
        mViewPager.setOffscreenPageLimit(2);
        if(bundle != null)
            mViewPager.setCurrentItem(bundle.getInt("ggvp_tab"));

        mTabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
        mTabLayout.setupWithViewPager(mViewPager);
        if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            mTabLayout.setPadding(toPixels(48), 0, toPixels(48), 0);
            mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        } else if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            mTabLayout.setTabMode(TabLayout.MODE_FIXED);
        }

        FrameLayout contentFrame = (FrameLayout) getActivity().findViewById(R.id.content_fragment);
        contentFrame.setVisibility(View.VISIBLE);

    }

    @Override
    public void saveInstanceState(Bundle b) {

        /*for(int i = 0; i < substAdapter.fragments.size(); i++)
            b.putInt("ggvp_frag_spinner_" + i, substAdapter.fragments.get(i).spinnerPos);*/
        b.putInt("ggvp_tab", mViewPager.getCurrentItem());
    }

    @Override
    public void createView(LayoutInflater inflater, ViewGroup vg) {

    }

    @Override
    public ViewGroup getContentView() {
        return null;
    }

    @Override
    public void setFragmentLoading() {
        substAdapter.setFragmentsLoading();
    }

    @Override
    public void updateFragment() {
        SIAApp.SIA_APP.activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if(substAdapter != null) {
                    substAdapter.update((Subst.GGPlans) getFragment().getData());
                    mTabLayout.setupWithViewPager(mViewPager);
                }
            }
        });

    }

    public void resetScrollPositions() {
        List<Fragment> frags = getChildFragmentManager().getFragments();
        if(frags != null) {
            for (Fragment fr : frags) {
                if(fr != null) {
                    View v = fr.getView();
                    if (v != null) {
                        v = v.findViewWithTag("gg_scroll");
                        if (v != null) {
                            v.setScrollY(0);
                        }
                    }
                }
            }
        }
    }
}


text:
package oj.dump;

import oj.OjLibrary;
import oj.Options;
import oj.options.NanDump;
import org.jruby.RubyArray;
import org.jruby.RubyHash;
import org.jruby.RubyModule;
import org.jruby.RubyRange;
import org.jruby.RubyRational;
import org.jruby.RubyString;
import org.jruby.RubyStruct;
import org.jruby.RubyTime;
import org.jruby.ext.bigdecimal.RubyBigDecimal;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;

public class NullDump extends Dump {
    NullDump(ThreadContext context, OjLibrary oj, Options opts) {
        super(context, oj, opts);
    }

    @Override
    protected void dump_array(RubyArray array, int depth) {
        if (opts.circular && check_circular(array) < 0) {
            dump_nil();
            return;
        }

        int d2 = depth + 1;

        append('[');

        if (array.isEmpty()) {
            append(']');
        } else {
            int cnt = array.getLength() - 1;

            for (int i = 0; i <= cnt; i++) {
                indent(d2, opts.dump_opts.array_nl);
                dump_val(array.eltInternal(i), d2);
                if (i < cnt) append(',');
            }
            indent(depth, opts.dump_opts.array_nl);
            append(']');
        }
    }

    @Override
    protected void dump_bigdecimal(RubyBigDecimal bigdecimal, int depth) {
        dump_raw(stringToByteList(bigdecimal, "to_s"));
    }

    @Override
    protected void dump_str(RubyString string) {
        dump_cstr(string.getByteList(), false, false);
    }

    @Override
    protected void dump_time(RubyTime time, int depth) {
        dump_nil();
    }

    @Override
    protected void dump_class(RubyModule clas) {
        dump_nil();
    }

    @Override
    protected void dump_hash(IRubyObject obj, int dep) {
        RubyHash hash = (RubyHash) obj;

        if (opts.circular && check_circular(hash) < 0) {
            dump_nil();
            return;
        }

        if (hash.isEmpty()) {
            append(EMPTY_HASH);
        } else {
            append('{');
            depth = dep + 1;
            hash.visitAll(context,
                    new RubyHash.VisitorWithState<Dump>() {
                        @Override
                        public void visit(ThreadContext threadContext, RubyHash rubyHash, IRubyObject key, IRubyObject value, int index, Dump dump) {
                            visit_hash(key, value);
                        }
                    }, this);
            if (',' == get(-1)) pop(); // backup to overwrite last comma
            indent(dep, opts.dump_opts.hash_nl);
            append('}');
        }
    }

    @Override
    protected String modeName() {
        return "null";
    }

    @Override
    protected void dump_other(IRubyObject obj, int depth) {
        dump_nil();
    }

    @Override
    protected void dump_complex(IRubyObject obj, int depth) {
        dump_nil();
    }

    @Override
    protected void dump_regexp(IRubyObject obj, int depth) {
        dump_nil();
    }

    @Override
    protected void dump_range(RubyRange obj, int depth) {
        dump_nil();
    }

    @Override
    protected void dump_rational(RubyRational rational, int depth) {
        dump_nil();
    }

    @Override
    protected void dump_struct(RubyStruct obj, int depth) {
        dump_nil();
    }

    @Override
    protected void dumpNanNanForFloat(IRubyObject value) {
        NanDump nd = opts.dump_opts.nan_dump;

        if (nd == NanDump.AutoNan) nd = NanDump.NullNan;

        switch(nd) {
            case RaiseNan:
            case WordNan:
                raise_strict(value); break;
            case NullNan:
                append(NULL_VALUE); break;
            case HugeNan:
            default:
                append(NAN_NUMERIC_VALUE); break;
        }
    }

    @Override
    protected void dumpInfNanForFloat(IRubyObject value, byte[] inf_value, boolean positive) {
        NanDump nd = opts.dump_opts.nan_dump;

        if (nd == NanDump.AutoNan) nd = NanDump.NullNan;

        switch(nd) {
            case RaiseNan:
            case WordNan:
                raise_strict(value); break;
            case NullNan:
                append(NULL_VALUE); break;
            case HugeNan:
            default:
                append(positive ? INF_VALUE : NINF_VALUE); break;
        }
    }
}


text:
package com.groupon.odo.proxylib;

import com.groupon.odo.proxylib.models.Client;
import com.groupon.odo.proxylib.models.Profile;
import com.groupon.odo.proxylib.models.ServerGroup;
import com.groupon.odo.proxylib.models.ServerRedirect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ServerRedirectService {

    private static ServerRedirectService serviceInstance = null;
    private static final Logger logger = LoggerFactory.getLogger(ServerRedirectService.class);
    private static SQLService sqlService = null;

    public ServerRedirectService() {

    }

    /**
     * Obtain instance of ServerRedirectService
     *
     * @return
     */
    public static ServerRedirectService getInstance() {
        if (serviceInstance == null) {
            serviceInstance = new ServerRedirectService();
            try {
                sqlService = SQLService.getInstance();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return serviceInstance;
    }

    /**
     * Get the server redirects for a given clientId from the database
     *
     * @param clientId
     * @return
     */
    public List<ServerRedirect> tableServers(int clientId) {
        List<ServerRedirect> servers = new ArrayList<ServerRedirect>();

        try {
            Client client = ClientService.getInstance().getClient(clientId);
            servers = tableServers(client.getProfile().getId(), client.getActiveServerGroup());
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return servers;
    }

    /**
     * Get the server redirects belonging to a server group
     *
     * @param profileId
     * @param serverGroupId
     * @return
     */
    public List<ServerRedirect> tableServers(int profileId, int serverGroupId) {
        ArrayList<ServerRedirect> servers = new ArrayList<ServerRedirect>();
        PreparedStatement queryStatement = null;
        ResultSet results = null;

        try (Connection sqlConnection = sqlService.getConnection()) {
            queryStatement = sqlConnection.prepareStatement(
                    "SELECT * FROM " + Constants.DB_TABLE_SERVERS +
                            " WHERE " + Constants.GENERIC_PROFILE_ID + " = ?" +
                            " AND " + Constants.SERVER_REDIRECT_GROUP_ID + " = ?"
            );
            queryStatement.setInt(1, profileId);
            queryStatement.setInt(2, serverGroupId);
            results = queryStatement.executeQuery();
            while (results.next()) {
                ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),
                        results.getString(Constants.SERVER_REDIRECT_REGION),
                        results.getString(Constants.SERVER_REDIRECT_SRC_URL),
                        results.getString(Constants.SERVER_REDIRECT_DEST_URL),
                        results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));
                curServer.setProfileId(profileId);
                servers.add(curServer);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (results != null) results.close();
            } catch (Exception e) {
            }
            try {
                if (queryStatement != null) queryStatement.close();
            } catch (Exception e) {
            }
        }
        return servers;
    }

    /**
     * Return all server groups for a profile
     *
     * @param profileId
     * @return
     */
    public List<ServerGroup> tableServerGroups(int profileId) {
        ArrayList<ServerGroup> serverGroups = new ArrayList<ServerGroup>();
        PreparedStatement queryStatement = null;
        ResultSet results = null;

        try (Connection sqlConnection = sqlService.getConnection()) {
            queryStatement = sqlConnection.prepareStatement(
                    "SELECT * FROM " + Constants.DB_TABLE_SERVER_GROUPS +
                            " WHERE " + Constants.GENERIC_PROFILE_ID + " = ? " +
                            "ORDER BY " + Constants.GENERIC_NAME
            );
            queryStatement.setInt(1, profileId);
            results = queryStatement.executeQuery();
            while (results.next()) {
                ServerGroup curServerGroup = new ServerGroup(results.getInt(Constants.GENERIC_ID),
                        results.getString(Constants.GENERIC_NAME),
                        results.getInt(Constants.GENERIC_PROFILE_ID));
                curServerGroup.setServers(tableServers(profileId, curServerGroup.getId()));
                serverGroups.add(curServerGroup);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (results != null) results.close();
            } catch (Exception e) {
            }
            try {
                if (queryStatement != null) queryStatement.close();
            } catch (Exception e) {
            }
        }
        return serverGroups;
    }

    /**
     * Returns redirect information for the given ID
     *
     * @param id
     * @return
     */
    public ServerRedirect getRedirect(int id) throws Exception {
        PreparedStatement queryStatement = null;
        ResultSet results = null;

        try (Connection sqlConnection = sqlService.getConnection()) {
            queryStatement = sqlConnection.prepareStatement(
                    "SELECT * FROM " + Constants.DB_TABLE_SERVERS +
                            " WHERE " + Constants.GENERIC_ID + " = ?"
            );
            queryStatement.setInt(1, id);
            results = queryStatement.executeQuery();
            if (results.next()) {
                ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),
                        results.getString(Constants.SERVER_REDIRECT_REGION),
                        results.getString(Constants.SERVER_REDIRECT_SRC_URL),
                        results.getString(Constants.SERVER_REDIRECT_DEST_URL),
                        results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));
                curServer.setProfileId(results.getInt(Constants.GENERIC_PROFILE_ID));

                return curServer;
            }
            logger.info("Did not find the ID: {}", id);
        } catch (SQLException e) {
            throw e;
        } finally {
            try {
                if (results != null) results.close();
            } catch (Exception e) {
            }
            try {
                if (queryStatement != null) queryStatement.close();
            } catch (Exception e) {
            }
        }
        return null;
    }

    /**
     * Returns server group by ID
     *
     * @param id
     * @return
     * @throws Exception
     */
    public ServerGroup getServerGroup(int id, int profileId) throws Exception {
        PreparedStatement queryStatement = null;
        ResultSet results = null;

        if (id == 0) {
            return new ServerGroup(0, "Default", profileId);
        }

        try (Connection sqlConnection = sqlService.getConnection()) {
            queryStatement = sqlConnection.prepareStatement(
                    "SELECT * FROM " + Constants.DB_TABLE_SERVER_GROUPS +
                            " WHERE " + Constants.GENERIC_ID + " = ?"
            );
            queryStatement.setInt(1, id);
            results = queryStatement.executeQuery();
            if (results.next()) {
                ServerGroup curGroup = new ServerGroup(results.getInt(Constants.GENERIC_ID),
                        results.getString(Constants.GENERIC_NAME),
                        results.getInt(Constants.GENERIC_PROFILE_ID));
                return curGroup;
            }
            logger.info("Did not find the ID: {}", id);
        } catch (SQLException e) {
            throw e;
        } finally {
            try {
                if (results != null) results.close();
            } catch (Exception e) {
            }
            try {
                if (queryStatement != null) queryStatement.close();
            } catch (Exception e) {
            }
        }
        return null;
    }

    /**
     * Add server redirect to a profile, using current active ServerGroup
     *
     * @param region
     * @param srcUrl
     * @param destUrl
     * @param hostHeader
     * @param profileId
     * @return
     * @throws Exception
     */
    public int addServerRedirectToProfile(String region, String srcUrl, String destUrl, String hostHeader,
                                          int profileId, int clientId) throws Exception {
        int serverId = -1;

        try {
            Client client = ClientService.getInstance().getClient(clientId);
            serverId = addServerRedirect(region, srcUrl, destUrl, hostHeader, profileId, client.getActiveServerGroup());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return serverId;
    }

    /**
     * Add server redirect to a profile
     *
     * @param region
     * @param srcUrl
     * @param destUrl
     * @param hostHeader
     * @param profileId
     * @param groupId
     * @return
     * @throws Exception
     */
    public int addServerRedirect(String region, String srcUrl, String destUrl, String hostHeader, int profileId, int groupId) throws Exception {
        int serverId = -1;
        PreparedStatement statement = null;
        ResultSet results = null;

        try (Connection sqlConnection = sqlService.getConnection()) {
            statement = sqlConnection.prepareStatement("INSERT INTO " + Constants.DB_TABLE_SERVERS
                    + "(" + Constants.SERVER_REDIRECT_REGION + "," +
                    Constants.SERVER_REDIRECT_SRC_URL + "," +
                    Constants.SERVER_REDIRECT_DEST_URL + "," +
                    Constants.SERVER_REDIRECT_HOST_HEADER + "," +
                    Constants.SERVER_REDIRECT_PROFILE_ID + "," +
                    Constants.SERVER_REDIRECT_GROUP_ID + ")"
                    + " VALUES (?, ?, ?, ?, ?, ?);", PreparedStatement.RETURN_GENERATED_KEYS);
            statement.setString(1, region);
            statement.setString(2, srcUrl);
            statement.setString(3, destUrl);
            statement.setString(4, hostHeader);
            statement.setInt(5, profileId);
            statement.setInt(6, groupId);
            statement.executeUpdate();

            results = statement.getGeneratedKeys();

            if (results.next()) {
                serverId = results.getInt(1);
            } else {
                // something went wrong
                throw new Exception("Could not add path");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (results != null) results.close();
            } catch (Exception e) {
            }
            try {
                if (statement != null) statement.close();
            } catch (Exception e) {
            }
        }

        return serverId;
    }

    /**
     * Add a new server group
     *
     * @param groupName name of the group
     * @param profileId ID of associated profile
     * @return id of server group
     * @throws Exception
     */
    public int addServerGroup(String groupName, int profileId) throws Exception {
        int groupId = -1;
        PreparedStatement statement = null;
        ResultSet results = null;

        try (Connection sqlConnection = sqlService.getConnection()) {
            statement = sqlConnection.prepareStatement("INSERT INTO " + Constants.DB_TABLE_SERVER_GROUPS
                    + "(" + Constants.GENERIC_NAME + "," +
                    Constants.GENERIC_PROFILE_ID + ")"
                    + " VALUES (?, ?);", PreparedStatement.RETURN_GENERATED_KEYS);
            statement.setString(1, groupName);
            statement.setInt(2, profileId);
            statement.executeUpdate();

            results = statement.getGeneratedKeys();

            if (results.next()) {
                groupId = results.getInt(1);
            } else {
                // something went wrong
                throw new Exception("Could not add group");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (results != null) results.close();
            } catch (Exception e) {
            }
            try {
                if (statement != null) statement.close();
            } catch (Exception e) {
            }
        }

        return groupId;
    }

    /**
     * Set the group name
     *
     * @param name
     * @param id
     */
    public void setGroupName(String name, int id) {
        PreparedStatement statement = null;

        try (Connection sqlConnection = sqlService.getConnection()) {
            statement = sqlConnection.prepareStatement(
                    "UPDATE " + Constants.DB_TABLE_SERVER_GROUPS +
                            " SET " + Constants.GENERIC_NAME + " = ?" +
                            " WHERE " + Constants.GENERIC_ID + " = ?"
            );
            statement.setString(1, name);
            statement.setInt(2, id);
            statement.executeUpdate();
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) statement.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * Activate a server group
     *
     * @param groupId
     * @param clientId
     */
    public void activateServerGroup(int groupId, int clientId) {
        PreparedStatement statement = null;

        try (Connection sqlConnection = sqlService.getConnection()) {
            statement = sqlConnection.prepareStatement(
                    "UPDATE " + Constants.DB_TABLE_CLIENT +
                            " SET " + Constants.CLIENT_ACTIVESERVERGROUP + " = ? " +
                            " WHERE " + Constants.GENERIC_ID + " = ? "
            );
            statement.setInt(1, groupId);
            statement.setInt(2, clientId);

            statement.executeUpdate();
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) statement.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * Set source url for a server
     *
     * @param newUrl
     * @param id
     */
    public void setSourceUrl(String newUrl, int id) {
        PreparedStatement statement = null;

        try (Connection sqlConnection = sqlService.getConnection()) {
            statement = sqlConnection.prepareStatement(
                    "UPDATE " + Constants.DB_TABLE_SERVERS +
                            " SET " + Constants.SERVER_REDIRECT_SRC_URL + " = ?" +
                            " WHERE " + Constants.GENERIC_ID + " = ?"
            );
            statement.setString(1, newUrl);
            statement.setInt(2, id);
            statement.executeUpdate();
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) statement.close();
            } catch (Exception e) {
            }
        }

    }

    /**
     * Set destination url for a server
     *
     * @param newUrl
     * @param id
     */
    public void setDestinationUrl(String newUrl, int id) {
        PreparedStatement statement = null;

        try (Connection sqlConnection = sqlService.getConnection()) {
            statement = sqlConnection.prepareStatement(
                    "UPDATE " + Constants.DB_TABLE_SERVERS +
                            " SET " + Constants.SERVER_REDIRECT_DEST_URL + " = ?" +
                            " WHERE " + Constants.GENERIC_ID + " = ?"
            );
            statement.setString(1, newUrl);
            statement.setInt(2, id);
            statement.executeUpdate();
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) statement.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * Set (optional) host header for a server
     *
     * @param newHost
     * @param id
     */
    public void setHostHeader(String newHost, int id) {
        PreparedStatement statement = null;

        try (Connection sqlConnection = sqlService.getConnection()) {
            statement = sqlConnection.prepareStatement(
                    "UPDATE " + Constants.DB_TABLE_SERVERS +
                            " SET " + Constants.SERVER_REDIRECT_HOST_HEADER + " = ?" +
                            " WHERE " + Constants.GENERIC_ID + " = ?"
            );
            statement.setString(1, newHost);
            statement.setInt(2, id);
            statement.executeUpdate();
            statement.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (statement != null) statement.close();
            } catch (Exception e) {
            }
        }
    }

    /**
     * Deletes a redirect by id
     *
     * @param id
     */
    public void deleteRedirect(int id) {
        try {
            sqlService.executeUpdate("DELETE FROM " + Constants.DB_TABLE_SERVERS +
                    " WHERE " + Constants.GENERIC_ID + " = " + id + ";");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Delete a server group by id
     *
     * @param id
     */
    public void deleteServerGroup(int id) {
        try {
            sqlService.executeUpdate("DELETE FROM " + Constants.DB_TABLE_SERVER_GROUPS +
                    " WHERE " + Constants.GENERIC_ID + " = " + id + ";");

            sqlService.executeUpdate("DELETE FROM " + Constants.DB_TABLE_SERVERS +
                    " WHERE " + Constants.SERVER_REDIRECT_GROUP_ID + " = " + id);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * This returns all profiles associated with a server name
     *
     * @param serverName
     * @return profile UUID
     */
    public Profile[] getProfilesForServerName(String serverName) throws Exception {
        int profileId = -1;
        ArrayList<Profile> returnProfiles = new ArrayList<Profile>();

        PreparedStatement queryStatement = null;
        ResultSet results = null;
        try (Connection sqlConnection = sqlService.getConnection()) {
            queryStatement = sqlConnection.prepareStatement(
                    "SELECT " + Constants.GENERIC_PROFILE_ID + " FROM " + Constants.DB_TABLE_SERVERS +
                            " WHERE " + Constants.SERVER_REDIRECT_SRC_URL + " = ? GROUP BY " +
                            Constants.GENERIC_PROFILE_ID
            );
            queryStatement.setString(1, serverName);
            results = queryStatement.executeQuery();

            while (results.next()) {
                profileId = results.getInt(Constants.GENERIC_PROFILE_ID);

                Profile profile = ProfileService.getInstance().findProfile(profileId);

                returnProfiles.add(profile);
            }
        } catch (SQLException e) {
            throw e;
        } finally {
            try {
                if (results != null) results.close();
            } catch (Exception e) {
            }
            try {
                if (queryStatement != null) queryStatement.close();
            } catch (Exception e) {
            }
        }

        if (returnProfiles.size() == 0)
            return null;
        return returnProfiles.toArray(new Profile[0]);
    }

    /**
     * Returns true or false depending on whether or not Odo can handle the request for this server/clientUUID pair
     *
     * @param serverName
     * @return
     * @throws Exception
     */
    public Boolean canHandleRequest(String serverName) throws Exception {
        // TODO: Future optimizations
        try {
            Profile[] profiles = this.getProfilesForServerName(serverName);
            if(profiles == null)
            {
                logger.info("No matching profiles found for path");
                return false;
            }
            for (Profile profile : profiles) {
                List<Client> clients = ClientService.getInstance().findAllClients(profile.getId());
                for (Client client : clients) {
                    if (client.getIsActive()) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}


text:
package org.camunda.bpm.engine.impl;

import static org.camunda.bpm.engine.impl.util.CompareUtil.areNotInAscendingOrder;
import static org.camunda.bpm.engine.impl.util.EnsureUtil.ensureNotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.camunda.bpm.engine.exception.NotValidException;
import org.camunda.bpm.engine.history.DurationReportResult;
import org.camunda.bpm.engine.history.HistoricProcessInstanceReport;
import org.camunda.bpm.engine.impl.cfg.CommandChecker;
import org.camunda.bpm.engine.impl.context.Context;
import org.camunda.bpm.engine.impl.db.TenantCheck;
import org.camunda.bpm.engine.impl.interceptor.Command;
import org.camunda.bpm.engine.impl.interceptor.CommandContext;
import org.camunda.bpm.engine.impl.interceptor.CommandExecutor;
import org.camunda.bpm.engine.query.PeriodUnit;
import org.camunda.bpm.engine.repository.ProcessDefinition;

/**
 * @author Roman Smirnov
 *
 */
public class HistoricProcessInstanceReportImpl implements HistoricProcessInstanceReport {

  private static final long serialVersionUID = 1L;

  protected Date startedAfter;
  protected Date startedBefore;
  protected String[] processDefinitionIdIn;
  protected String[] processDefinitionKeyIn;

  protected PeriodUnit durationPeriodUnit;

  protected CommandExecutor commandExecutor;

  protected TenantCheck tenantCheck = new TenantCheck();

  public HistoricProcessInstanceReportImpl(CommandExecutor commandExecutor) {
    this.commandExecutor = commandExecutor;
  }

  // query parameter ///////////////////////////////////////////////

  public HistoricProcessInstanceReport startedAfter(Date startedAfter) {
    ensureNotNull(NotValidException.class, "startedAfter", startedAfter);
    this.startedAfter = startedAfter;
    return this;
  }

  public HistoricProcessInstanceReport startedBefore(Date startedBefore) {
    ensureNotNull(NotValidException.class, "startedBefore", startedBefore);
    this.startedBefore = startedBefore;
    return this;
  }

  public HistoricProcessInstanceReport processDefinitionIdIn(String... processDefinitionIds) {
    ensureNotNull(NotValidException.class, "", "processDefinitionIdIn", (Object[]) processDefinitionIds);
    this.processDefinitionIdIn = processDefinitionIds;
    return this;
  }

  public HistoricProcessInstanceReport processDefinitionKeyIn(String... processDefinitionKeys) {
    ensureNotNull(NotValidException.class, "", "processDefinitionKeyIn", (Object[]) processDefinitionKeys);
    this.processDefinitionKeyIn = processDefinitionKeys;
    return this;
  }

  // report execution /////////////////////////////////////////////

  public List<DurationReportResult> duration(PeriodUnit periodUnit) {
    ensureNotNull(NotValidException.class, "periodUnit", periodUnit);
    this.durationPeriodUnit = periodUnit;

    CommandContext commandContext = Context.getCommandContext();

    if(commandContext == null) {
      return commandExecutor.execute(new Command<List<DurationReportResult>>() {

        @Override
        public List<DurationReportResult> execute(CommandContext commandContext) {
          return executeDurationReport(commandContext);
        }

      });
    }
    else {
      return executeDurationReport(commandContext);
    }

  }

  public List<DurationReportResult> executeDurationReport(CommandContext commandContext) {

    doAuthCheck(commandContext);

    if(areNotInAscendingOrder(startedAfter, startedBefore)) {
      return Collections.emptyList();
    }

    return commandContext
      .getHistoricReportManager()
      .selectHistoricProcessInstanceDurationReport(this);

  }

  protected void doAuthCheck(CommandContext commandContext) {
    // since a report does only make sense in context of historic
    // data, the authorization check will be performed here
    for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
      if (processDefinitionIdIn == null && processDefinitionKeyIn == null) {
        checker.checkReadHistoryAnyProcessDefinition();
      } else {
        List<String> processDefinitionKeys = new ArrayList<String>();
        if (processDefinitionKeyIn != null) {
          processDefinitionKeys.addAll(Arrays.asList(processDefinitionKeyIn));
        }

        if (processDefinitionIdIn != null) {
          for (String processDefinitionId : processDefinitionIdIn) {
            ProcessDefinition processDefinition = commandContext.getProcessDefinitionManager()
              .findLatestProcessDefinitionById(processDefinitionId);

            if (processDefinition != null && processDefinition.getKey() != null) {
              processDefinitionKeys.add(processDefinition.getKey());
            }
          }
        }

        if (!processDefinitionKeys.isEmpty()) {
          for (String processDefinitionKey : processDefinitionKeys) {
            checker.checkReadHistoryProcessDefinition(processDefinitionKey);
          }
        }
      }
    }
  }

  // getter //////////////////////////////////////////////////////

  public Date getStartedAfter() {
    return startedAfter;
  }

  public Date getStartedBefore() {
    return startedBefore;
  }

  public String[] getProcessDefinitionIdIn() {
    return processDefinitionIdIn;
  }

  public String[] getProcessDefinitionKeyIn() {
    return processDefinitionKeyIn;
  }

  public TenantCheck getTenantCheck() {
    return tenantCheck;
  }

  public String getReportPeriodUnitName() {
    return durationPeriodUnit.name();
  }

}


text:
package org.jboss.weld.serialization.spi.helpers;

import org.jboss.weld.context.api.ContextualInstance;

import jakarta.enterprise.context.spi.Contextual;
import jakarta.enterprise.context.spi.CreationalContext;
import java.io.Serializable;

/**
 * A Serializable wrapper for a {@link ContextualInstance}
 *
 * @author Pete Muir
 * @author Marius Bogoevici
 */
public interface SerializableContextualInstance<C extends Contextual<I>, I> extends ContextualInstance<I>, Serializable {
    SerializableContextual<C, I> getContextual();

    I getInstance();

    CreationalContext<I> getCreationalContext();
}