text:
package command

import (
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

type OcCommand struct {
	*defaultCommand
}

func NewOcCommand(command string) *OcCommand {
	defaultCommand := &defaultCommand{rawCommand: command}
	ocCommand := &OcCommand{defaultCommand}
	defaultCommand.fn = ocCommand.doExecute
	return ocCommand
}

func (c *OcCommand) doExecute(ec *ExecutionContext) error {
	// split off the actual 'oc' command. We are using our cached oc version to run oc commands
	cmd := strings.Replace(c.rawCommand, "oc ", "", 1)
	cmd = ec.Interpolate(cmd)
	fmt.Print(".")

	commander := ec.GetOcCommander()
	exitStatus := commander.Run(ec.Interpolate(cmd), ioutil.Discard, os.Stdin)
	if exitStatus != 0 {
		return errors.New(fmt.Sprintf("Error executing command %s.", c.String()))
	}

	return nil
}


text:
import 'testcafe';
import dep1 from './dep1';
import dep2 from './dep2';

fixture `Some fixture`;

test('Test deps', async() => {
    return [await dep1(2), await dep2(2)];
});

redpajama_set_name: RedPajamaGithub


text:
package sonata.kernel.vimadaptor.wrapper;

public interface ResourceDescriptor {

  public String toJson();

}


text:
package com.jotacv.utils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Export {

	private static Connection connection = null;

	private enum DataType{BLOB, LOB, DATE, NUMBER, OTH, NULL}

	private String daPattern = "(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)\\s(\\d\\d):(\\d\\d):(\\d\\d)(\\.?\\d*)";

	private class RollingFileOutputStream {

		private int fileIdx = 1;
		private int cc = 0;
		private FileOutputStream file = null;
		private int rollCount = 50000;

		public RollingFileOutputStream(int rollCount) throws FileNotFoundException {
			this.rollCount = rollCount;
			this.file = new FileOutputStream("output0.sql");
		}

		private void rollFile() throws IOException{
			this.file.close();
			this.file= new FileOutputStream("output"+fileIdx+++".sql");
			this.cc = 0;
		}

		public void write(byte[] b) throws IOException{
			if(cc++>rollCount)
				this.rollFile();
			this.file.write(b);
		}

		public void close() throws IOException{
			this.file.close();
		}

	}

	public static String byteToHex(byte[] bs) {
		StringBuilder sb = new StringBuilder(bs.length);
		for(byte b : bs){
			sb.append(String.format("%02X", b));
		}
		return sb.toString();
	}

	public boolean isLOB(String type){
		if (type!=null &&
				type.contains("CLOB") ||
				type.contains("NCLOB") ||
				type.contains("BFILE")){
			return true;

		}else{
			return false;
		}
	}

	public boolean isBLOB(String type){
		if (type!=null && type.contains("BLOB")){
			return true;
		}else{
			return false;
		}
	}
	public boolean isNumber(String type){
		if (type!=null && type.contains("NUMBER")){
			return true;
		}else{
			return false;
		}
	}
	public boolean isDate(String type){
		if (type!=null &&
				type.contains("TIMESTAMP") ||
				type.equals("DATE")){
			return true;

		}else{
			return false;
		}
	}

	private class Data{
		public DataType type;
		public String val;

		public Data(String  type, String val){
			if (val!=null){
				if (isDate(type)){
					this.type=DataType.DATE;
					this.val= val;
				}else if(isLOB(type)){
					this.type = DataType.LOB;
					this.val=val;
				}else if(isBLOB(type)){
					this.type = DataType.BLOB;
					this.val=val;
				}else if(isNumber(type)){
					this.type = DataType.NUMBER;
					this.val=val;
				}else{
					this.type=DataType.OTH;
					this.val = val;
				}
			}else{
				this.type= DataType.NULL;
				this.val = null;
			}
		}

		@Override
		public String toString(){
			String ret = null;
			switch (this.type){
			case LOB:
				ret = "q'{"+this.val+"}'";
				break;
			case BLOB:
				ret = "hextoraw('"+this.val+"')";
				break;
			case DATE:
				Matcher m = Pattern.compile(daPattern).matcher(this.val);
				if(m.matches()){
					ret= new StringBuilder()
							.append("TO_DATE('")
							.append(m.group(1)).append("-")
							.append(m.group(2)).append("-")
							.append(m.group(3)).append(" ")
							.append(m.group(4)).append(":")
							.append(m.group(5)).append(":")
							.append(m.group(6)).append("', 'YYYY-MM-DD HH24:MI:SS')").toString();
				}else{
					//Default, it will blow up in the insert but no data is lost and u can manually fix it
					ret = this.val;
					System.out.println("WARN: DEFAULTED DATE: "+ret);
				}
				break;
			case NULL:
				ret = "null";
				break;
			case NUMBER:
				ret = this.val;
				break;
			case OTH:
				ret = "'"+this.val.replace("'", "''")+"'";
				break;
			}
			return ret;
		}
	}

	private String createSqlPart1(String tableName, List<String> columns){
		StringBuilder ret = new StringBuilder();
		ret.append("INSERT INTO "+tableName+" (");
		for(int i=0;i<columns.size();i++){
			ret.append(columns.get(i));
			if(i!=columns.size()-1)
				ret.append(", ");
			else
				ret.append(") VALUES ");
		}
		return ret.toString();
	}

	private String createSqlPart2(List<Data> data){
		StringBuilder ret = new StringBuilder();
		ret.append("(");
		for(int i=0;i<data.size();i++){
			ret.append(data.get(i));
			if(i!=data.size()-1)
				ret.append(", ");
			else
				ret.append(");\n");
		}
		return ret.toString();
	}

	private List<String> findTablesByFilter(String owner, List<String> tablesFilter, boolean excludeFlag) throws SQLException{
		Statement statm=null;
		ResultSet res=null;
		List<String> tables=null;

		statm = connection.createStatement();
		res = statm.executeQuery("SELECT table_name FROM all_tables WHERE owner = '"+owner+"'");
		tables = new ArrayList<String>();
		while(res.next()){
			tables.add(res.getString(1));
		}
		res.close(); statm.close();
		System.out.println("\nGot "+tables.size()+" tables.");
		//Filter tables
		if(tablesFilter!=null && !tablesFilter.isEmpty()){
			List<String> tablesFiltered = new ArrayList<String>();
			for (String tableFilter : tablesFilter){
				if (tables.contains(tableFilter)^excludeFlag)
					tablesFiltered.add(tableFilter);
			}
			if(!tablesFiltered.isEmpty())
				tables = tablesFiltered;
			System.out.println("Narrowed down to "+tables.size());
		}
		return tables;
	}

	private void ExportAll(String owner, List<String> tablesFilter, boolean excludeFlag, boolean orderFlag) throws SQLException, IOException{

		//Tables list & order
		Statement statm=null;
		ResultSet res=null;
		List<String> tables=null;
		try{
			if(orderFlag){
				OrderFinder orderFinder = new OrderFinder(connection, owner, tablesFilter, excludeFlag);
				tables = orderFinder.getOrderedList();
			}else{
				System.out.print("  Using input order.");
				tables = findTablesByFilter(owner, tables, orderFlag);
			}
		}catch(Exception e){
			System.out.println(" ERROR: Cannot get tables order");
			tables = findTablesByFilter(owner, tables, orderFlag);
		}

		//Retrieving data & export
		String columnType = "";
		String columnContent = "";
		RollingFileOutputStream rfos = new RollingFileOutputStream(50000);
		int tableidx=0;
		for(String tableName: tables){
			tableidx++;
			try{
				List<String> columnsHeaders = new ArrayList<String>();
				System.out.println("Fetching table "+tableName);
				statm = connection.createStatement();
				res = statm.executeQuery("select COLUMN_NAME from USER_TAB_COLUMNS where table_name='"+tableName+"' order by column_id");
				while(res.next()){
					columnsHeaders.add(res.getString(1));
				}
				res.close(); statm.close();
				String insert_part1 = createSqlPart1(tableName,columnsHeaders);
				statm = connection.createStatement();
				res = statm.executeQuery("select * FROM "+tableName);
				ResultSetMetaData rmd = res.getMetaData();
				while(res.next()){
					List<Data> row = new ArrayList<Data>();
					for(int j=1;j<=columnsHeaders.size();j++){
						try{
							columnType 		= rmd.getColumnTypeName(j);
							columnContent	= null;
							if(rmd!=null && isLOB(columnType)){
								if(res.getClob(j)!=null){
									Clob clob = res.getClob(j);
									columnContent = clob!=null?clob.getSubString(1,(int)clob.length()):"";
									row.add(new Data(columnType,columnContent));
								}else{
									columnContent="";
									row.add(new Data(columnType,null));
								}
							}else if(rmd!=null && isBLOB(columnType)){
								Blob blob = res.getBlob(j);
								columnContent = blob!=null?byteToHex(blob.getBytes(1l,(int)blob.length())):"";
								row.add(new Data(columnType,columnContent));
							}else{
								columnContent=res.getString(j);
								row.add(new Data(columnType,columnContent));
							}
						}catch(Exception e){
							System.out.print("- ERROR IN TABLE "+tableName+",ROW "+tableidx+", COLUMN "+j+": ");
							e.printStackTrace();
							System.out.println("-- ColumnType: "+columnType);
							System.out.println("-- ColumnContent: "+columnContent);
						}
					}
					String insert_part2 = createSqlPart2(row);
					rfos.write((insert_part1+insert_part2).getBytes());
				}
			}catch(Exception e){
				System.out.print("- ERROR IN TABLE "+tableName+": ");
				e.printStackTrace();
				System.out.println("-- ColumnType: "+columnType);
				System.out.println("-- ColumnContent: "+columnContent);
			}finally{
				res.close();
				statm.close();
			}
			rfos.write("COMMIT;\n\n".getBytes());
		}
		rfos.close();
	}

	public static void main(String[] argv) throws Exception {
		System.out.println("------ Oracle JDBC Database Export ------");
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			System.out.println("Where is your Oracle JDBC Driver?");
			e.printStackTrace();
			return;
		}

		List<String> listaTablas = null;
		boolean excludeFlag = false;
		boolean orderFlag = true;
		try {
			if (argv.length==3 || argv.length==4 || argv.length==5 ){
				connection = DriverManager.getConnection(argv[0],argv[1],argv[2]);
				if(argv.length>=4){
					String list = null;

					if(argv.length==4){
						list = argv[3];
					}else{
						list = argv[4];
						if(argv[3].equals("-e")){
							excludeFlag = true;
						}else if(argv[3].equals("-o")){
							orderFlag=false;
						}else{
							throw new IllegalArgumentException();
						}

					}

					try{
						listaTablas = Arrays.asList(list.replace(" ", "").split(","));
					}catch(Exception e){
						System.out.println("Cannot parse tables list. Make sure 4th argument is a comma separated list of tables");
					}
				}
			}else{
				throw new IllegalArgumentException("Usage: java -jar this.jar url user password [-e/-o] [tableList]");
			}
		} catch (SQLException e) {
			System.out.println("Connection Failed! Check output console");
			e.printStackTrace();
			return;
		}

		if (connection != null) {
			System.out.println("Oracle JDBC Driver Connected!");
			Locale.setDefault(Locale.US);
			Export main = new Export();
			main.ExportAll(argv[1],listaTablas,excludeFlag, orderFlag);
			System.out.println("----------------- DONE! -----------------");
			connection.close();
		} else {
			System.out.println("Failed to make connection!");
		}
	}

}


text:
/*
 * Title:	Pathfinder Class (A* Algorithm)
 * File:	pathfinder.hpp
 * Author:	R.Samarasekara
 * Date:	June 2014
 * License:	MIT License (see license.txt)
 *
*/

#ifndef PATHFINDER_HPP
#define PATHFINDER_HPP
#include <iostream>
#include <cmath> 	// required for using abs().
#include <vector>
#include <limits.h>	// required for UINT_MAX.

static const int STATE_WALKABLE = 0;		// move constants to a namespace(?)
static const int STATE_START_NODE = 1;
static const int STATE_END_NODE = 2;
static const int STATE_NOT_IN_LIST = 3;
static const int STATE_IN_OPEN_LIST = 4;
static const int STATE_IN_CLOSED_LIST = 5;
static const int NEIGHBOUR_COUNT = 8;

typedef struct node{
	int x,y;
	node* parent_node;
	int g;
	int h;
	int state;
	int list_state;
	bool part_of_path;

	node():	x(-1),
			y(-1),
			parent_node(NULL),
			g(0),
			h(0),
			state(STATE_WALKABLE),
			list_state(STATE_NOT_IN_LIST),
			part_of_path(false){}
}node;

class pathfinder{
	public:
		pathfinder( int w, int h );
		~pathfinder();

		void print_grid();
		void set_node_as_wall( int x, int y );
		void set_start_and_end_nodes( int x0, int y0, int x1, int y1 );
		node* get_node( int x, int y ) const;
		int calculate_heuristic( node *from_this_node );
		void run_astar();
		node* get_node_with_lowest_score() const;
		void remove_node_from_open_list( node *arg );
		void set_current_neighbours();
		bool is_path_found(){ return m_path_found; }

	private:
		node *m_grid;							// Array of nodes defining the grid.
		node *m_start_node;						// Pointer to Start/End nodes.
		node *m_end_node;
		node *m_current_node;					// The current node being looked@ in a given iteration cycle.
		node* m_neighbours[NEIGHBOUR_COUNT];	// A nodes neighbours. (Change to node**?).

		int m_grid_width;
		int m_grid_height;

		bool m_path_found;

		std::vector<node*> m_open_list;
		std::vector<node*> m_closed_list;
};
#endif


text:
using namespace CoreAnimation;
using namespace Microsoft::WRL;
using namespace UIKit::Xaml::Private::CoreAnimation;
using namespace Windows::Foundation;
using namespace Windows::Storage::Streams;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Media::Imaging;

static const wchar_t* TAG = L"LayerAnimation";

__inline CoreAnimation::StoryboardManager^ _GetStoryboardManager(const Microsoft::WRL::ComPtr<IInspectable>& storyboardManager) {
    return dynamic_cast<CoreAnimation::StoryboardManager^>(reinterpret_cast<Platform::Object^>(storyboardManager.Get()));
}

__inline FrameworkElement^ _GetXamlElement(ILayerProxy& layer) {
    return dynamic_cast<FrameworkElement^>(reinterpret_cast<Platform::Object^>(reinterpret_cast<LayerProxy*>(&layer)->GetXamlElement().Get()));
};

LayerAnimation::LayerAnimation() {
    easingFunction = EaseInEaseOut;
}

void LayerAnimation::_CreateXamlAnimation() {
    auto storyboardManager = ref new CoreAnimation::StoryboardManager(
        beginTime, duration, autoReverse, repeatCount, repeatDuration, speed, timeOffset);

    switch (easingFunction) {
        case Easing::EaseInEaseOut: {
            auto easing = ref new Media::Animation::QuadraticEase();
            easing->EasingMode = Media::Animation::EasingMode::EaseInOut;
            storyboardManager->AnimationEase = easing;
        } break;

        case Easing::EaseIn: {
            auto easing = ref new Media::Animation::QuadraticEase();
            easing->EasingMode = Media::Animation::EasingMode::EaseIn;
            storyboardManager->AnimationEase = easing;
        } break;

        case Easing::EaseOut: {
            auto easing = ref new Media::Animation::QuadraticEase();
            easing->EasingMode = Media::Animation::EasingMode::EaseOut;
            storyboardManager->AnimationEase = easing;
        } break;

        case Easing::Default: {
            auto easing = ref new Media::Animation::QuadraticEase();
            easing->EasingMode = Media::Animation::EasingMode::EaseInOut;
            storyboardManager->AnimationEase = easing;
        } break;

        case Easing::Linear: {
            storyboardManager->AnimationEase = nullptr;
        } break;
    }

    _storyboardManager = reinterpret_cast<IInspectable*>(storyboardManager);
}

void LayerAnimation::_Start() {
    CoreAnimation::StoryboardManager^ storyboardManager = _GetStoryboardManager(_storyboardManager);

    std::weak_ptr<LayerAnimation> weakThis = shared_from_this();
    storyboardManager->Completed = ref new CoreAnimation::AnimationMethod([weakThis](Platform::Object^ sender) {
        std::shared_ptr<LayerAnimation> strongThis = weakThis.lock();
        if (strongThis) {
            strongThis->_Completed();
            CoreAnimation::StoryboardManager^ storyboardManager = _GetStoryboardManager(strongThis->_storyboardManager);
            storyboardManager->Completed = nullptr;
        }
    });

    storyboardManager->Start();
}

void LayerAnimation::Stop() {
    CoreAnimation::StoryboardManager^ storyboardManager = _GetStoryboardManager(_storyboardManager);
    if (storyboardManager) {
        storyboardManager->Stop();
        storyboardManager->Completed = nullptr;
        _storyboardManager = nullptr;
    }
}

concurrency::task<void> LayerAnimation::_AddAnimation(ILayerProxy& layer, const char* propertyName, bool fromValid, float from, bool toValid, float to) {
    auto xamlLayer = _GetXamlElement(layer);
    auto storyboardManager = _GetStoryboardManager(_storyboardManager);

    storyboardManager->Animate(xamlLayer,
        propertyName,
        fromValid ? (Platform::Object^)(double)from : nullptr,
        toValid ? (Platform::Object^)(double)to : nullptr);

    return concurrency::task_from_result();
}

concurrency::task<Layer^> _SnapshotLayer(Layer^ layer) {
    if (((layer->Height == 0) && (layer->Width == 0)) || (layer->Opacity == 0)) {
        return concurrency::task_from_result<Layer^>(nullptr);
    }
    else {
        RenderTargetBitmap^ snapshot = ref new RenderTargetBitmap();
        return concurrency::create_task(
                snapshot->RenderAsync(layer))
            .then([snapshot, layer](concurrency::task<void> result) noexcept {
            try {
                result.get();
            } catch (Platform::InvalidArgumentException^ ex) {
                // Handle exceptions related to invalid layer attribute passed to RenderAsync
                TraceWarning(TAG,
                             L"RenderAsync threw InvalidArgumentException exception - [%ld]%s",
                             ex->HResult,
                             ex->Message);
                return static_cast<Layer^>(nullptr);
            }

            // Return a new 'copy' layer with the rendered content
            Layer^ newLayer = ref new Layer();
            newLayer->Name = "_Temporary_CoreAnimation_SnapshotLayer";
            LayerCoordinator::InitializeFrameworkElement(newLayer);

            // Copy display properties from the old layer to the new layer
            LayerCoordinator::SetValue(newLayer, "opacity", LayerCoordinator::GetValue(layer, "opacity"));
            LayerCoordinator::SetValue(newLayer, "position", LayerCoordinator::GetValue(layer, "position"));
            LayerCoordinator::SetValue(newLayer, "size", LayerCoordinator::GetValue(layer, "size"));
            LayerCoordinator::SetValue(newLayer, "anchorPoint", LayerCoordinator::GetValue(layer, "anchorPoint"));

            auto dispInfo = Windows::Graphics::Display::DisplayInformation::GetForCurrentView();

            // Set the snapshot as the content of the new layer
            LayerCoordinator::SetContent(
                newLayer,
                snapshot,
                static_cast<float>(layer->Width),
                static_cast<float>(layer->Height),
                static_cast<float>(DisplayProperties::RawScreenScale() * dispInfo->RawPixelsPerViewPixel));

            // There seems to be a bug in Xaml where Render'd layers get sized to their visible content... sort of.
            // If the UIViewController being transitioned away from has transparent content, the height returned is less the
            // navigation bar, as though Xaml sizes the buffer to the largest child Visual, and only expands where needed.
            // Top/bottom switched due to geometric origin of CALayer so read this as UIViewContentModeTopLeft
            LayerCoordinator::SetContentGravity(newLayer, ContentGravity::BottomLeft);

            return newLayer;
        }, concurrency::task_continuation_context::use_current());
    }
}

concurrency::task<void> LayerAnimation::_AddTransitionAnimation(ILayerProxy& layer, const char* type, const char* subtype) {
    auto xamlLayer = _GetXamlElement(layer);
    auto storyboardManager = _GetStoryboardManager(_storyboardManager);

    std::string stype(type);
    std::wstring wtype(stype.begin(), stype.end());
    std::string ssubtype(subtype);
    std::wstring wsubtype(ssubtype.begin(), ssubtype.end());

    // We currently only support layer snapshots/transitions on our default Layer implementation
    auto coreAnimationLayer = dynamic_cast<Layer^>(xamlLayer);
    if (!coreAnimationLayer) {
        UNIMPLEMENTED_WITH_MSG(
            "Layer transition animations not supported on this Xaml element: [%ws].",
            xamlLayer->GetType()->FullName->Data());
        return concurrency::task_from_result();
    }

    // Render a layer snapshot, then kick off the animation
    return _SnapshotLayer(coreAnimationLayer)
        .then([this, storyboardManager, coreAnimationLayer, wtype, wsubtype](Layer^ snapshotLayer) noexcept {

        storyboardManager->AddTransition(
            coreAnimationLayer,
            snapshotLayer,
            ref new Platform::String(wtype.data()),
            ref new Platform::String(wsubtype.data()));

        _Start();
    }, concurrency::task_continuation_context::use_current());
}


text:
<!doctype html>
	<meta charset="utf-8">
	<title> veneer demo </title>
	<meta name=author content="dandavis">
	<meta name=description content="">
	<link rel=stylesheet href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">

Pushing out change()es using a veneer tag's subscribed attrib

Example 1 - <veneer-item> to <veneer-mustache> syncing options

Example Data Source (a simple form)

		<veneer-item id="myItem" subscribed=.pushed >
			 Name <input name="name" type="text" value="Jane">
			 Age <input name="age" type="number" min="1" max="99" value="22">
				  <input name="male" type="checkbox"> Male
		</veneer-item>

Updated via  <var>subscribed</var>  attribute on <veneer-item>

		<veneer-mustache object=myItem.value class=pushed >
			{{name}} is {{age}} years old.
		</veneer-mustache>

Updated via 2 second polling from  <var>interval</var> attribute on template

		<veneer-mustache object=myItem.value interval=2 >
			{{name}} is {{age}} years old.
		</veneer-mustache>

Updated manually via calling  <var>change()</var> method on template
			<button onclick=manual1.change()> Apply Update</button>

		<veneer-mustache object=myItem.value id=manual1 >
			{{name}} is {{age}} years old.
		</veneer-mustache>

Updated nevermore because of <var>static</var> attribute on template
			<button onclick=manual3.change()> Apply Update</button>

		<veneer-mustache object=myItem.value id=manual3 static >
			{{name}} is {{age}} years old.
		</veneer-mustache>

Init/update manually via  <var>render(data)</var> method on template (no  <var>object</var> attribute on template)
			<button onclick=manual2.render(myItem.value)> Apply Update</button>

		<veneer-mustache id=manual2 >
			{{name}} is {{age}} years old.
		</veneer-mustache>

Example 2 - <veneer-dateinput> to page title via <veneer-timer>

		<veneer-dateinput subscribed=veneer-timer ></veneer-dateinput>

		<veneer-timer onchange="if(event.e)document.title=event.e.value.toLocaleDateString()" ></veneer-timer>

  Back to gists


text:
import sys
import unittest
import rospy
import rostest
import simplejson
from o3d3xx.srv import Dump, Config

class TestServices(unittest.TestCase):

    def __init__(self, *args):
        super(TestServices, self).__init__(*args)

    def test_services(self):
        rospy.init_node('test_services')
        rospy.wait_for_service("/Dump")
        rospy.wait_for_service("/Config")

        self.dump_srv = rospy.ServiceProxy("/Dump", Dump)
        self.config_srv = rospy.ServiceProxy("/Config", Config)

        dump_resp = self.dump_srv()
        json = simplejson.loads(dump_resp.config)
        idx = int(json["o3d3xx"]["Device"]["ActiveApplication"])
        self.assertTrue(idx > 0)

        params = [(idx, 5, "upto30m_moderate"),
                  (idx, 10, "under5m_low"),
                  (idx, 5, "upto30m_moderate")]
        for param_set in params:
            self._dump_config(*param_set)

    def _dump_config(self, idx, frame_rate, im_type):
        dump_resp = self.dump_srv()
        json = simplejson.loads(dump_resp.config)

        real_idx = 0
        for app in json["o3d3xx"]["Apps"]:
            if int(app["Index"]) == idx:
                break
            else:
                real_idx += 1

        json["o3d3xx"]["Apps"][real_idx]["Imager"]["FrameRate"] = \
          str(frame_rate)
        json["o3d3xx"]["Apps"][real_idx]["Imager"]["Type"] = str(im_type)

        config_resp = self.config_srv(simplejson.dumps(json))
        self.assertTrue(config_resp.status == 0)

        dump_resp = self.dump_srv()
        json = simplejson.loads(dump_resp.config)

        fr = int(json["o3d3xx"]["Apps"][real_idx]["Imager"]["FrameRate"])
        it = json["o3d3xx"]["Apps"][real_idx]["Imager"]["Type"]
        self.assertTrue(fr == frame_rate)
        self.assertTrue(it == im_type)

def main():
    rostest.rosrun('o3d3xx', 'test_services', TestServices, sys.argv)
    return 0

if __name__ == '__main__':
    sys.exit(main())


text:
import os
import uuid
from datetime import datetime

from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.core.urlresolvers import reverse
from django.template.defaultfilters import filesizeformat

import commonware.log
import waffle
from PIL import Image
from tower import ugettext as _

import amo
from amo.helpers import absolutify
from editors.models import EscalationQueue
from lib.video import library as video_library
from mkt.comm.utils import create_comm_note
from mkt.constants import APP_PREVIEW_MINIMUMS
from mkt.constants import comm
from mkt.reviewers.utils import send_mail

log = commonware.log.getLogger('z.devhub')

def uri_to_pk(uri):
    """
    Convert a resource URI to the primary key of the resource.
    """
    return uri.rstrip('/').split('/')[-1]

def check_upload(file_obj, upload_type, content_type):
    errors = []
    upload_hash = ''
    is_icon = upload_type == 'icon'
    is_preview = upload_type == 'preview'
    is_video = content_type in amo.VIDEO_TYPES

    if not any([is_icon, is_preview, is_video]):
        raise ValueError('Unknown upload type.')

    # By pushing the type onto the instance hash, we can easily see what
    # to do with the file later.
    ext = content_type.replace('/', '-')
    upload_hash = '%s.%s' % (uuid.uuid4().hex, ext)
    loc = os.path.join(settings.TMP_PATH, upload_type, upload_hash)

    with storage.open(loc, 'wb') as fd:
        for chunk in file_obj:
            fd.write(chunk)

    # A flag to prevent us from attempting to open the image with PIL.
    do_not_open = False

    if is_video:
        if not video_library:
            errors.append(_('Video support not enabled.'))
        else:
            video = video_library(loc)
            video.get_meta()
            if not video.is_valid():
                errors.extend(video.errors)

    else:
        check = amo.utils.ImageCheck(file_obj)
        if (not check.is_image() or
            content_type not in amo.IMG_TYPES):
            do_not_open = True
            if is_icon:
                errors.append(_('Icons must be either PNG or JPG.'))
            else:
                errors.append(_('Images must be either PNG or JPG.'))

        if check.is_animated():
            do_not_open = True
            if is_icon:
                errors.append(_('Icons cannot be animated.'))
            else:
                errors.append(_('Images cannot be animated.'))

    max_size = (settings.MAX_ICON_UPLOAD_SIZE if is_icon else
                settings.MAX_VIDEO_UPLOAD_SIZE if is_video else
                settings.MAX_IMAGE_UPLOAD_SIZE if is_preview else None)

    if max_size and file_obj.size > max_size:
        do_not_open = True
        if is_icon or is_video:
            errors.append(_('Please use files smaller than %s.') %
                filesizeformat(max_size))

    if (is_icon or is_preview) and not is_video and not do_not_open:
        file_obj.seek(0)
        try:
            im = Image.open(file_obj)
            im.verify()
        except IOError:
            if is_icon:
                errors.append(_('Icon could not be opened.'))
            elif is_preview:
                errors.append(_('Preview could not be opened.'))
        else:
            size_x, size_y = im.size
            if is_icon:
                # TODO: This should go away when we allow uploads for
                # individual icon sizes.
                if size_x < 128 or size_y < 128:
                    errors.append(_('Icons must be at least 128px by 128px.'))

                if size_x != size_y:
                    errors.append(_('Icons must be square.'))

            elif is_preview:
                if (size_x < APP_PREVIEW_MINIMUMS[0] or
                    size_y < APP_PREVIEW_MINIMUMS[1]) and (
                        size_x < APP_PREVIEW_MINIMUMS[1] or
                        size_y < APP_PREVIEW_MINIMUMS[0]):
                    errors.append(
                        # L10n: {0} and {1} are the height/width of the preview
                        # in px.
                        _('App previews must be at least {0}px by {1}px or '
                          '{1}px by {0}px.').format(*APP_PREVIEW_MINIMUMS))

    return errors, upload_hash

def handle_vip(addon, version, user):
    msg = u'VIP app updated'

    # Add to escalation queue
    EscalationQueue.objects.get_or_create(addon=addon)

    # Create comm note
    create_comm_note(addon, version, user, msg, note_type=comm.ESCALATION,
                     perms={'developer': False})

    # Log action
    amo.log(amo.LOG.ESCALATION_VIP_APP, addon, version, created=datetime.now(),
            details={'comments': msg})
    log.info(u'[app:%s] escalated - %s' % (addon.name, msg))

    # Special senior reviewer email.
    if not waffle.switch_is_active('comm-dashboard'):
        context = {'name': addon.name,
                   'review_url': absolutify(reverse('reviewers.apps.review',
                                                     args=[addon.app_slug],
                                                     add_prefix=False)),
                   'SITE_URL': settings.SITE_URL}
        send_mail(u'%s: %s' % (msg, addon.name),
                   'developers/emails/vip_escalation.ltxt', context,
                   [settings.MKT_SENIOR_EDITORS_EMAIL])


text:
/**
 * @fileoverview Tests for VisualStudio format.
 * @author Ronald Pijnacker
 */

"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

const assert = require("chai").assert,
    formatter = require("../../../lib/formatters/visualstudio");

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

describe("formatter:visualstudio", () => {
    describe("when passed no messages", () => {
        const code = [{
            filePath: "foo.js",
            messages: []
        }];

        it("should return nothing", () => {
            const result = formatter(code);

            assert.equal(result, "no problems");
        });
    });

    describe("when passed a single message", () => {
        const code = [{
            filePath: "foo.js",
            messages: [{
                message: "Unexpected foo.",
                severity: 2,
                line: 5,
                column: 10,
                ruleId: "foo"
            }]
        }];

        it("should return a string in the format filename(x,y): error z for errors", () => {
            const result = formatter(code);

            assert.equal(result, "foo.js(5,10): error foo : Unexpected foo.\n\n1 problem");
        });

        it("should return a string in the format filename(x,y): warning z for warnings", () => {
            code[0].messages[0].severity = 1;
            const result = formatter(code);

            assert.equal(result, "foo.js(5,10): warning foo : Unexpected foo.\n\n1 problem");
        });
    });

    describe("when passed a fatal error message", () => {
        const code = [{
            filePath: "foo.js",
            messages: [{
                fatal: true,
                message: "Unexpected foo.",
                line: 5,
                column: 10,
                ruleId: "foo"
            }]
        }];

        it("should return a string in the format filename(x,y): error  z", () => {
            const result = formatter(code);

            assert.equal(result, "foo.js(5,10): error foo : Unexpected foo.\n\n1 problem");
        });
    });

    describe("when passed multiple messages", () => {
        const code = [{
            filePath: "foo.js",
            messages: [{
                message: "Unexpected foo.",
                severity: 2,
                line: 5,
                column: 10,
                ruleId: "foo"
            }, {
                message: "Unexpected bar.",
                severity: 1,
                line: 6,
                column: 11,
                ruleId: "bar"
            }]
        }];

        it("should return a string with multiple entries", () => {
            const result = formatter(code);

            assert.equal(result, "foo.js(5,10): error foo : Unexpected foo.\nfoo.js(6,11): warning bar : Unexpected bar.\n\n2 problems");
        });
    });

    describe("when passed multiple files with 1 message each", () => {
        const code = [{
            filePath: "foo.js",
            messages: [{
                message: "Unexpected foo.",
                severity: 2,
                line: 5,
                column: 10,
                ruleId: "foo"
            }]
        }, {
            filePath: "bar.js",
            messages: [{
                message: "Unexpected bar.",
                severity: 1,
                line: 6,
                column: 11,
                ruleId: "bar"
            }]
        }];

        it("should return a string with multiple entries", () => {
            const result = formatter(code);

            assert.equal(result, "foo.js(5,10): error foo : Unexpected foo.\nbar.js(6,11): warning bar : Unexpected bar.\n\n2 problems");
        });
    });

    describe("when passed one file not found message", () => {
        const code = [{
            filePath: "foo.js",
            messages: [{
                fatal: true,
                message: "Couldn't find foo.js."
            }]
        }];

        it("should return a string without line and column", () => {
            const result = formatter(code);

            assert.equal(result, "foo.js(0): error : Couldn't find foo.js.\n\n1 problem");
        });
    });
});


text: Tests that paint profiler is properly update when an event is selected in Flame Chart


text:
{% from "macros/_form.html" import render_form %}

{% set page_title = 'Sign up' %}

{% extends "layouts/base.html" %}

{% block body %}

Sign up Already have an account? Sign in, please.

    {{ render_form(url_for('frontend.signup'), form) }}

{% endblock %}


text:
function calcB() {
  var result = varOne + varTwo + 13;
  return ++result;
}


text:
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');

var JadestylGenerator = yeoman.generators.Base.extend({
  init: function () {
    this.pkg = require('../package.json');

    this.on('end', function () {
      if (!this.options['skip-install']) {
        this.installDependencies();
      }
    });
  },

  askFor: function () {
    var done = this.async();

    // Have Yeoman greet the user.
    this.log(yosay('Welcome to the marvelous Jadestyl generator!'));

    var prompts = [{
      name: 'title',
      message: 'What is the title of your application?',
      default: this.appname
    },{
      type: 'confirm',
      name: 'jQuery',
      message: 'Would you like jQuery ?',
      default: true
    },{
      type: 'confirm',
      name: 'imgProgress',
      message: 'Would you like add a progressbar according with the number of image in the page ?',
      default: false
    },{
      type: 'confirm',
      name: 'animateCss',
      message: 'Would you like Animate.css ?',
      default: true
    },{
      type: 'confirm',
      name: 'velocity',
      message: 'Would you like Velocity JS ?',
      default: false
    }];

    this.prompt(prompts, function (props) {
      this.title = props.title;
      this.animateCss = props.animateCss;
      this.jQuery = props.jQuery;
      this.imgProgress = props.imgProgress;
      this.velocity = props.velocity;
      this.htmlmin = props.htmlmin;

      done();

      var extractGeneratorName = function (_, appname) {
        var slugged = _.slugify(title);
        var match = slugged.match(/^$/);

        if (match && match.length === 2) {
          return match[1].toLowerCase();
      }

      return slugged;
      };
        }.bind(this));
      },

     bower: function () {
        var bower = {
          name: this._.slugify(this.title + '-jadestyl'),
          private: true,
          dependencies: {}
        };

        if (this.jQuery) {
         bower.dependencies.jquery = '1.11.0'
        }

        if (this.animateCss) {
          var ani = 'animate.css'
          bower.dependencies[ani] = '~3.1.1';
        }

         if (this.imgProgress) {
          bower.dependencies.imgprogress = 'https://github.com/cedced19/imgprogress.git';
        }

        if (this.velocity) {
          bower.dependencies.velocity = 'https://github.com/julianshapiro/velocity.git';
        }

        this.write('bower.json', JSON.stringify(bower, null, 2));
      },

    app: function () {
      this.mkdir('src');
      this.mkdir('src/scripts');
      this.mkdir('src/styles');

      this.template('src/index.jade', 'src/index.jade');
      this.template('src/scripts/main.js', 'src/scripts/main.js');
      this.template('src/styles/main.styl', 'src/styles/main.styl');
      this.copy('_package.json', 'package.json');
      this.copy('gitignore', '.gitignore');
      this.copy('bowerrc', '.bowerrc');
      this.template('gulpfile.js', 'gulpfile.js');
      this.template('README.md', 'README.md');
    }
  });

module.exports = JadestylGenerator;


text:
@class EAGLContext;
@interface EJCanvasContext : NSObject {
	short width, height;

	BOOL msaaEnabled;
	BOOL needsPresenting;
	int msaaSamples;
	EAGLContext *glContext;
}

- (void)create;
- (void)flushBuffers;
- (void)prepare;

@property (nonatomic) BOOL msaaEnabled;
@property (nonatomic) int msaaSamples;
@property (nonatomic) short width;
@property (nonatomic) short height;
@property (nonatomic, readonly) EAGLContext *glContext;

@end


text:
package lib.hash;

import org.apache.jena.tdb.store.Hash ;

public interface HashFunction<T>
{
    public Hash hash(T object) ;
    public int hashToInt(T object) ;
}


text:
The scripts are written in C# and work with Unity3d Engine and Unity Personal edition.
Unity Personal edition is a free alternative for game developers.:

- Play foodstep sounds on terrain and object's simultaniously
- AI
- Basic Inventory
- Game Patching
- Saving/Loading Games
- Interactable events
- Cutscene creation
- Xbox,Playstation,Wii,etc. Controller Support
- Movement System
- Weapon System
- Inventory System

Using these will give you a huge boost in the process of your game making.
Note: This does make use of the following packages:

- [daemon3000's Input Manager](https://github.com/daemon3000/InputManager)

Legacy Packages Included (Not being developed anymore):
- [Rain AI](https://www.assetstore.unity3d.com/en/#!/content/23569)
- Panda AI
- [Octodiff](https://github.com/OctopusDeploy/Octodiff)

## Legal
----
You may use everything contained within this repository for personal or commercial products. This is not required but I always do appreciate it when endorsments are thrown my way. If you feel so enclined throw my name in the credits.

This is released under the [MIT License](https://opensource.org/licenses/MIT).

**Important Note:** Inside Scripts/GameManager/InputManager is code that belongs to [daemon3000's Input Manager](https://github.com/daemon3000/InputManager). That repository is release under the [MIT License](https://opensource.org/licenses/MIT). If you don't understand how to use it look at his repository as it has amazing documentation.
Also the "Octodiff" repository is released under the Apache 2.0 License [Read License](https://github.com/OctopusDeploy/Octodiff/blob/master/LICENSE).
Rain AI is release under the Unity Asset Store For free. Read about their licencing model [here](https://unity3d.com/legal/as_terms). In short anything you get in the Unity Asset store you can use personally or commercially.


text:
"""
package containing classes for testing combination of features, predictor
on specified datasets

@arthor: Wittawat
"""

from seizures.prediction.PredictorBase import PredictorBase
from seizures.features.FeatureExtractBase import FeatureExtractBase
from seizures.Global import Global
from seizures.data.DataLoader_v2 import DataLoader
from seizures.evaluation.XValidation import XValidation
from seizures.evaluation.performance_measures import accuracy, auc
from seizures.data.SubjectEEGData import SubjectEEGData
from abc import abstractmethod
from sklearn import cross_validation
from seizures.preprocessing import preprocessing
import numpy as np

from IPython.core.debugger import Tracer

class FeaturePredictorTestBase(object):
    """
    Abstract class for all feature-predictor testers.

    @author: Wittawat
    """
    def __init__(self, feature_extractor, predictor, patient, data_path):
        """
        feature_extractor: an instance of FeatureExtractBase
        predictor: an instance of PredictorBase
        patient: a string indicating a subject e.g., Dog_1
        data_path: full path to directory containing Dog_1, .. Patient_1,..
        """

        #assert(isinstance(feature_extractor, FeatureExtractBase))
        #assert(isinstance(predictor, PredictorBase))
        assert(isinstance(patient, basestring))

    @abstractmethod
    def test_combination(self, **options):
        """
        Test the predictor using features given by feature_extractor
        on the data specified by the patient argument.
        """
        raise NotImplementedError()

class FeaturesPredictorsTestBase(object):
    """
    Abstract class for all features-predictors testers.
    The only difference to FeaturePredictorTestBase is that this class
    accepts a list of feature_extractor's and a list of predictor's.

    @author: Wittawat
    """
    def __init__(self, feature_extractors, predictors, patient, data_path):
        """
        feature_extractors: list of FeatureExtractBase's
        predictors: list of PredictorBase's
        patient: a string indicating a subject e.g., Dog_1
        data_path: full path to directory containing Dog_1, .. Patient_1,..
        """

        assert(type(feature_extractors)==type([]))
        assert(type(predictors)==type([]))
        assert(isinstance(patient, basestring))

    @abstractmethod
    def test_combination(self, **options):
        """
        Test the predictors using features given by each feature_extractor
        on the data specified by the patient argument.
        """
        raise NotImplementedError()

class CVFeaturePredictorTester(FeaturePredictorTestBase):
    """
    An implementation of FeaturePredictorTestBase which test
    by cross validation the given predictor using features from
    feature_extractor on the patient data.

    @author: Wittawat
    """

    def __init__(self, feature_extractor, predictor, patient,
            data_path=Global.path_map('clips_folder')):
        """
        feature_extractor: an instance of FeatureExtractBase
        predictor: an instance of PredictorBase
        patient: a string indicating a subject e.g., Dog_1
        """

        assert(isinstance(feature_extractor, FeatureExtractBase))
        assert(isinstance(predictor, PredictorBase))
        assert(isinstance(patient, basestring))

        self._feature_extractor = feature_extractor
        self._predictor = predictor
        self._patient = patient
        self._data_path = data_path

    def test_combination(self, fold=3, max_segments=-1):
        """
        Test the predictor using features given by feature_extractor
        on the data specified by the patient argument.
        Based on examples/cross_validation_test.py

        :param max_segments: maximum segments to load. -1 to use the number of
        total segments available. Otherwise, all segments (ictal and interictal)
        will be randomly subsampled without replacement.

        return: a dictionary containing error report
        """
        predictor = self._predictor
        loader = DataLoader(self._data_path, self._feature_extractor)

        X_list,y_seizure, y_early = loader.blocks_for_Xvalidation(
                self._patient, fold, max_segments)

        # running cross validation
        #print 'Testing %d-fold CV on data of %s'%(fold, self._patient)
        #print "\ncross validation: seizures vs not"
        result_seizure = XValidation.evaluate(X_list, y_seizure, predictor, evaluation=auc)
        #print 'cross-validation results: mean = %.3f, sd = %.3f, raw scores = %s' \
                #% (np.mean(result_seizure), np.std(result_seizure), result_seizure)

        #print "\ncross validation: early_vs_not"
        result_early = XValidation.evaluate(X_list, y_early, predictor, evaluation=auc)
        #print 'cross-validation results: mean = %.3f, sd = %.3f, raw scores = %s' \
                #% (np.mean(result_early), np.std(result_early), result_early)

        # dict containing bunch of reports
        r = {}
        r['predictor'] = predictor
        r['feature_extractor'] = self._feature_extractor
        # total features extracted. X_i is n x d
        r['total_features'] = X_list[0].shape[1]
        r['cv_fold'] = fold
        r['seizure_mean_auc'] = np.mean(result_seizure)
        r['seizure_std_auc'] = np.std(result_seizure)
        r['early_mean_auc'] = np.mean(result_early)
        r['early_std_auc'] = np.std(result_early)
        return r

class CVFeaturesPredictorsTester(FeaturePredictorTestBase):
    """
    An implementation of FeaturesPredictorsTestBase which test
    by cross validation the given predictors using features from each
    feature_extractor on the patient data.

    @author: Wittawat
    """

    def __init__(self, feature_extractors, predictors, patient,
            data_path=Global.path_map('clips_folder')):

        assert(type(feature_extractors)==type([]))
        assert(type(predictors)==type([]))
        assert(isinstance(patient, basestring))
        self._feature_extractors = feature_extractors
        self._predictors = predictors
        self._patient = patient
        self._data_path = data_path

    @staticmethod
    def test_all_combinations(features, feature_extractors, predictors):
        """
        features is a list [(X_seizure, y_seizure, X_early, y_early)] where each element
        in the tuple is itself a list of length = fold containing data in each
        CV fold

        return an instance of FeaturesPredictsTable
        """
        # these loops can be parallelized.
        # !! Can be improved !!
        L = []
        for i, feature_extractor in enumerate(feature_extractors):
            feature_list = []
            X_seizure, y_seizure, X_early, y_early = features[i]
            for j, predictor in enumerate(predictors):
                print 'Evaluating feat: %s + pred: %s on seizure task'%(str(feature_extractor), str(predictor) )
                result_seizure = XValidation.evaluate(X_seizure, y_seizure, predictor, evaluation=auc)
                print 'Evaluating feat: %s + pred: %s on early seizure task'%(str(feature_extractor), str(predictor) )
                result_early = XValidation.evaluate(X_early, y_early, predictor, evaluation=auc)
                r = {}
                r['predictor'] = predictor
                r['feature_extractor'] = feature_extractor
                # total features extracted. X_i is n x d
                r['total_features'] = X_early[0].shape[1]
                r['cv_fold'] = len(X_early)
                r['seizure_mean_auc'] = np.mean(result_seizure)
                r['seizure_std_auc'] = np.std(result_seizure)
                r['early_mean_auc'] = np.mean(result_early)
                r['early_std_auc'] = np.std(result_early)
                feature_list.append(r)
            L.append(feature_list)
        return FeaturesPredictsTable(L)

    def test_combination(self, fold=3, max_segments=-1):
        """
        Test the predictors using features given by each feature_extractor
        in feature_extractors on the data specified by the patient argument.

        :param max_segments: maximum segments to load. -1 to use the number of
        total segments available. Otherwise, all segments (ictal and interictal)
        will be randomly subsampled without replacement.

        return: an instance of FeaturesPredictsTable         """
        # preload data and extract features
        features = [] # list of feature tuples. list length = len(self._feature_extractors)
        for i, feature_extractor in enumerate(self._feature_extractors):
            loader = DataLoader(self._data_path, feature_extractor)
            X_list,y_seizure, y_early = loader.blocks_for_Xvalidation(
                self._patient, fold, max_segments)
            features.append( (X_list, y_seizure, X_list, y_early) )

        T = CVFeaturesPredictorsTester.test_all_combinations(features,
                self._feature_extractors, self._predictors)
        return T

class FeaturesPredictsTable(object):
    """
    Simple class to manipuldate data table returned by
    CVFeaturesPredictorsTester.

    To export the results in other ways,
    just add your own methods here. See print_ascii_table() as an example.

    @author Wittawat
    """
    def __init__(self, features_predictors_results):
        """
        features_predictors_results: a two-dimensional list L of dictionaries
        containing error report such that L[i] is a list of reports for
        feature_extractor i on all predictors.
        """
        self.raw_table = features_predictors_results

    def print_table(self, attribute):

        """
        Report result in a feature_extractors x predictors table.
        attribute specifies what entries to report in the table.
        attribute is a string with possible values given in
        CVFeaturePredictorTester.test_combination() (the key in the returned
        dictionary)
        """
        print "# From " + type(self).__name__.split('.')[-1]
        print "Reporting %s" % attribute
        L = self.raw_table

        from prettytable import PrettyTable
        predictors_strs = [str(rep['predictor']) for rep in L[0]]
        extractor_strs = [str(l[0]['feature_extractor']) for l in L]
        # see https://code.google.com/p/prettytable/wiki/Tutorial
        T = PrettyTable(['feat. \ pred.'] + predictors_strs)
        T.padding_width = 1 # One space between column edges and contents (default)
        for i, feature_extractor in enumerate(extractor_strs):
            predictors_values = [r[attribute] for r in L[i]]
            if isinstance(predictors_values[0], float):
                predictors_values = ['%.3g'%v for v in predictors_values]
            extractor_col = extractor_strs[i]
            T.add_row([extractor_col] + predictors_values )

        print T

    def to_csv(self, file_name):
        raise NotImplementedError('Can someone implement this ? ')

    def __str__(self):
        self.print_ascii_table('seizure_mean_auc')

class CachedCVFeaPredTester(FeaturePredictorTestBase):
    """
    An implementation of FeaturesPredictorsTestBase which test
    by cross validation the given predictors using features from each
    feature_extractor on the patient data. Cache loaded raw data so that
    loading is done only once.

    @author: Wittawat
    """

    def __init__(self, feature_extractors, predictors, patient,
            data_path=Global.path_map('clips_folder'),params=None):

        assert(type(feature_extractors)==type([]))
        assert(type(predictors)==type([]))
        assert(isinstance(patient, basestring))
        self._feature_extractors = feature_extractors
        self._predictors = predictors
        self._patient = patient
        self._data_path = data_path
        self.params = params

    def test_combination(self, fold=3, max_segments=-1):
        """
        Test the predictors using features given by each feature_extractor
        in feature_extractors on the data specified by the patient argument.

        :param max_segments: maximum segments to load. -1 to use the number of
        total segments available. Otherwise, all segments (ictal and interictal)
        will be randomly subsampled without replacement.

        return: an instance of FeaturesPredictsTable         """

        loader = SubjectEEGData(self._patient, self._data_path, use_cache=True,
                max_train_segments=max_segments)

        # a list of (Instance, y_seizure, y_early)'s
        train_data = loader.get_train_data()
        fs = train_data[0][0].sample_rate

        # preprocessing.
        #params = {'fs':fs,
        #  'anti_alias_cutoff': 100.,
        ##  'anti_alias_width': 30.,
        #  'anti_alias_attenuation' : 40,
        #  'elec_noise_width' :3.,
        #  'elec_noise_attenuation' : 60.0,
        #  'elec_noise_cutoff' : [49.,51.]}
        # list of preprocessed tuples
        params = self.params
        params['fs']=fs
#        for (x, y_seizure, y_early) in train_data:
#            x.eeg_data = preprocessing.preprocess_multichannel_data(x.eeg_data, self.params)

        #train_data2 = []
        #for (x, y_seizure, y_early) in train_data:
        #    x.eeg_data = preprocessing.preprocess_multichannel_data(x.eeg_data, params)
        #    train_data2.append(((x, y_seizure, y_early)))
        #train_data =train_data2

        # pre-extract features
        features = [] # list of feature tuples. list length = len(self._feature_extractors)
        Y_seizure = np.array([y_seizure for (x, y_seizure, y_early) in train_data])
        Y_early = np.array([y_early for (x, y_seizure, y_early) in train_data])
        skf_seizure = cross_validation.StratifiedKFold(Y_seizure, n_folds=fold)
        skf_early = cross_validation.StratifiedKFold(Y_early, n_folds=fold)
        for i, feature_extractor in enumerate(self._feature_extractors):
            #print 'Extracting features with %s'%str(feature_extractor)
            #Xlist = [feature_extractor.extract(x) for  (x, y_seizure, y_early)
            #        in train_data]
            Xlist = []
            for (x, y_seizure, y_early) in train_data:
                #print '---------'
                #print x.eeg_data.shape
                params['fs']=x.sample_rate
                x.eeg_data = preprocessing.preprocess_multichannel_data(x.eeg_data, params)
                feat =feature_extractor.extract(x)
                #print x.eeg_data.shape
                #print feat.shape
                Xlist.append(feat)
            #Tracer()()
            # Xlist = list of ndarray's
            #print len(Xlist), Xlist[0].shape,len(Xlist[0])
            n = len(Xlist)
            #d = len(Xlist[0])
            d = Xlist[0].shape[0]
            # make 2d numpy array
            #print n,d
            X = np.zeros((n, d))
            #print X.shape
            for i in xrange(len(Xlist)):
                #print Xlist[i].shape, X[i, :].shape
                X[i, :] = Xlist[i].T

            # chunk data for cross validation
            # construct a list of 2d numpy arrays to be fed to XValidation
            # tr_I = train index, te_I = test index
            X_seizure = []
            y_seizure = []

            #Tracer()()
            for tr_I, te_I in skf_seizure:
                X_seizure.append(X[tr_I, :])
                y_seizure.append(Y_seizure[tr_I])
            X_early = []
            y_early = []
            for tr_I, te_I in skf_early:
                X_early.append(X[tr_I, :])
                y_early.append(Y_early[tr_I])
            features.append( (X_seizure, y_seizure, X_early, y_early) )

        T = CVFeaturesPredictorsTester.test_all_combinations(features,
                self._feature_extractors, self._predictors)
        return T


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Taskling.Blocks.ObjectBlocks;

namespace Taskling.InfrastructureContracts.Blocks.ObjectBlocks
{
    public class ObjectBlockCreateResponse<T>
    {
        public ObjectBlock<T> Block { get; set; }
    }
}


text:
#ifndef OPTIONSMODEL_H
#define OPTIONSMODEL_H

#include <QAbstractListModel>

class CWallet;

/* Interface from QT to configuration data structure for bitcoin client.
   To QT, the options are presented as a list with the different options
   laid out vertically.
   This can be changed to a tree once the settings become sufficiently
   complex.
 */
class OptionsModel : public QAbstractListModel
{
    Q_OBJECT
public:
    explicit OptionsModel(CWallet *wallet, QObject *parent = 0);

    enum OptionID {
        StartAtStartup,
        MinimizeToTray,
        MapPortUPnP,
        MinimizeOnClose,
        ConnectSOCKS4,
        ProxyIP,
        ProxyPort,
        Fee,
        OptionIDRowCount
    };

    int rowCount(const QModelIndex & parent = QModelIndex()) const;
    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
    bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole);

    /* Explicit getters */
    qint64 getTransactionFee();
    bool getMinimizeToTray();
    bool getMinimizeOnClose();
private:
    // Wallet stores persistent options
    CWallet *wallet;
signals:

public slots:

};

#endif // OPTIONSMODEL_H


text:
Contact Us

        <form id="checkForm" action="send_form.php" method="post">

			Name*
       		<input id="name" type="text" name="name" />

   			Phone*
      		<input id="phone" type="tel" name="phone" />

     		Email*
			<input id="email" type="email" name="email" />

    		Message
   			<textarea id="comments" name="comments" /></textarea>

      		What is  +    ?*
  			<input type="text" name="captcha" id="captcha" style="width:30px;" />
 			<input type="hidden" name="captcha_sum" class="sumTotal" value="" />

  			<input type="submit" name="submit" value="Submit" class="submitButton"/>
   		</form>


text:
source helpers.sh

TIMESTAMP_FILE=/tmp/.LAST_TIMESTAMP

ENV_VARS=(
  LASP_BRANCH
  DCOS
  ELB_HOST
  PEER_SERVICE
  MODE
  BROADCAST
  SIMULATION
  EVAL_ID
  EVAL_TIMESTAMP
  CLIENT_NUMBER
  HEAVY_CLIENT
  REACTIVE_SERVER
  PARTITION_PROBABILITY
  STATE_INTERVAL
  DELTA_INTERVAL
  INSTRUMENTATION
  LOGS
  EXTENDED_LOGGING
  MAILBOX_LOGGING
  AWS_ACCESS_KEY_ID
  AWS_SECRET_ACCESS_KEY
)

for ENV_VAR in "${ENV_VARS[@]}"
do
  if [ -z "${!ENV_VAR}" ]; then
    echo ">>> ${ENV_VAR} is not configured; please export it."
    exit 1
  fi
done

echo ">>> Beginning deployment!"

if [ -e "$TIMESTAMP_FILE" ]; then
  # Last timestamp used to deploy an experiment
  LAST_TIMESTAMP=$(cat $TIMESTAMP_FILE)

  echo ">>> Removing lasp-server-$LAST_TIMESTAMP from Marathon"
  curl -s -k -H 'Content-type: application/json' -X DELETE $DCOS/service/marathon/v2/apps/lasp-server-$LAST_TIMESTAMP > /dev/null
  sleep 2

  echo ">>> Removing lasp-client-$LAST_TIMESTAMP from Marathon"
  curl -s -k -H 'Content-type: application/json' -X DELETE $DCOS/service/marathon/v2/apps/lasp-client-$LAST_TIMESTAMP > /dev/null
  sleep 2

  echo ">>> Waiting for Mesos to kill all tasks."
  wait_for_completion $LAST_TIMESTAMP
else
  echo ">>> No apps to be removed from Marathon"
fi

echo ">>> Configuring Lasp"
cd /tmp

# Memory of each VM.
SERVER_MEMORY=4096.0
CLIENT_MEMORY=1024.0

# CPU of each VM.
SERVER_CPU=2
CLIENT_CPU=0.5

# Docker image
IMAGE=vitorenesduarte/lasp-dev

cat <<EOF > lasp-server.json
{
  "acceptedResourceRoles": [
    "slave_public"
  ],
  "id": "lasp-server-$EVAL_TIMESTAMP",
  "dependencies": [],
  "constraints": [["hostname", "UNIQUE", ""]],
  "cpus": $SERVER_CPU,
  "mem": $SERVER_MEMORY,
  "instances": 1,
  "container": {
    "type": "DOCKER",
    "docker": {
      "image": "$IMAGE",
      "network": "HOST",
      "forcePullImage": true,
      "parameters": [
        { "key": "oom-kill-disable", "value": "true" }
      ]
    }
  },
  "ports": [0, 0],
  "env": {
    "LASP_BRANCH": "$LASP_BRANCH",
    "AD_COUNTER_SIM_SERVER": "true",
    "TAG": "server",
    "DCOS": "$DCOS",
    "PEER_SERVICE": "$PEER_SERVICE",
    "MODE": "$MODE",
    "BROADCAST": "$BROADCAST",
    "SIMULATION": "$SIMULATION",
    "EVAL_ID": "$EVAL_ID",
    "EVAL_TIMESTAMP": "$EVAL_TIMESTAMP",
    "CLIENT_NUMBER": "$CLIENT_NUMBER",
    "HEAVY_CLIENT": "$HEAVY_CLIENT",
    "REACTIVE_SERVER": "$REACTIVE_SERVER",
    "PARTITION_PROBABILITY": "$PARTITION_PROBABILITY",
    "STATE_INTERVAL": "$STATE_INTERVAL",
    "DELTA_INTERVAL": "$DELTA_INTERVAL",
    "INSTRUMENTATION": "$INSTRUMENTATION",
    "LOGS": "$LOGS",
    "EXTENDED_LOGGING": "$EXTENDED_LOGGING",
    "MAILBOX_LOGGING": "$MAILBOX_LOGGING",
    "AWS_ACCESS_KEY_ID": "$AWS_ACCESS_KEY_ID",
    "AWS_SECRET_ACCESS_KEY": "$AWS_SECRET_ACCESS_KEY"
  },
  "labels": {
      "HAPROXY_GROUP":"external",
      "HAPROXY_0_VHOST":"$ELB_HOST"
  },
  "healthChecks": [
    {
      "path": "/api/health",
      "portIndex": 0,
      "protocol": "HTTP",
      "gracePeriodSeconds": 300,
      "intervalSeconds": 60,
      "timeoutSeconds": 20,
      "maxConsecutiveFailures": 3,
      "ignoreHttp1xx": false
    }
  ]
}
EOF

echo ">>> Adding lasp-server-$EVAL_TIMESTAMP to Marathon"
curl -s -k -H 'Content-type: application/json' -X POST -d @lasp-server.json "$DCOS/service/marathon/v2/apps?force=true" > /dev/null
sleep 10

cat <<EOF > lasp-client.json
{
  "acceptedResourceRoles": [
    "slave_public"
  ],
  "id": "lasp-client-$EVAL_TIMESTAMP",
  "dependencies": [],
  "cpus": $CLIENT_CPU,
  "mem": $CLIENT_MEMORY,
  "instances": $CLIENT_NUMBER,
  "container": {
    "type": "DOCKER",
    "docker": {
      "image": "$IMAGE",
      "network": "HOST",
      "forcePullImage": true,
      "parameters": [
        { "key": "oom-kill-disable", "value": "true" }
      ]
    }
  },
  "ports": [0, 0],
  "env": {
    "LASP_BRANCH": "$LASP_BRANCH",
    "AD_COUNTER_SIM_CLIENT": "true",
    "TAG": "client",
    "DCOS": "$DCOS",
    "PEER_SERVICE": "$PEER_SERVICE",
    "MODE": "$MODE",
    "BROADCAST": "$BROADCAST",
    "SIMULATION": "$SIMULATION",
    "EVAL_ID": "$EVAL_ID",
    "EVAL_TIMESTAMP": "$EVAL_TIMESTAMP",
    "CLIENT_NUMBER": "$CLIENT_NUMBER",
    "HEAVY_CLIENT": "$HEAVY_CLIENT",
    "REACTIVE_SERVER": "$REACTIVE_SERVER",
    "PARTITION_PROBABILITY": "$PARTITION_PROBABILITY",
    "STATE_INTERVAL": "$STATE_INTERVAL",
    "DELTA_INTERVAL": "$DELTA_INTERVAL",
    "INSTRUMENTATION": "$INSTRUMENTATION",
    "LOGS": "$LOGS",
    "EXTENDED_LOGGING": "$EXTENDED_LOGGING",
    "MAILBOX_LOGGING": "$MAILBOX_LOGGING",
    "AWS_ACCESS_KEY_ID": "$AWS_ACCESS_KEY_ID",
    "AWS_SECRET_ACCESS_KEY": "$AWS_SECRET_ACCESS_KEY"
  },
  "healthChecks": [
    {
      "path": "/api/health",
      "portIndex": 0,
      "protocol": "HTTP",
      "gracePeriodSeconds": 300,
      "intervalSeconds": 60,
      "timeoutSeconds": 20,
      "maxConsecutiveFailures": 3,
      "ignoreHttp1xx": false
    }
  ]
}
EOF

echo ">>> Adding lasp-client-$EVAL_TIMESTAMP to Marathon"
curl -s -k -H 'Content-type: application/json' -X POST -d @lasp-client.json "$DCOS/service/marathon/v2/apps?force=true" > /dev/null
sleep 10

echo $EVAL_TIMESTAMP > $TIMESTAMP_FILE


text:
#//! QhullRidge -- Qhull's ridge structure, ridgeT, as a C++ class

#include "libqhullcpp/QhullRidge.h"

#include "libqhullcpp/QhullSets.h"
#include "libqhullcpp/QhullVertex.h"
#include "libqhullcpp/Qhull.h"

#ifdef _MSC_VER  // Microsoft Visual C++ -- warning level 4
#pragma warning( disable : 4611)  // interaction between '_setjmp' and C++ object destruction is non-portable
#pragma warning( disable : 4996)  // function was declared deprecated(strcpy, localtime, etc.)
#endif

namespace orgQhull {

#//!\name Class objects
ridgeT QhullRidge::
s_empty_ridge= {NULL,NULL,NULL,0,    // must match ridgeT -Wmissing-field-initializers
                false,false,false,false,false,false,false};

#//!\name Constructors

QhullRidge::QhullRidge(const Qhull &q)
: qh_ridge(&s_empty_ridge)
, qh_qh(q.qh())
{
}//Default

QhullRidge::QhullRidge(const Qhull &q, ridgeT *r)
: qh_ridge(r ? r : &s_empty_ridge)
, qh_qh(q.qh())
{
}//ridgeT

#//!\name foreach

//! Return True if nextRidge3d
//! Simplicial facets may have incomplete ridgeSets
//! Does not use qh_errexit()
bool QhullRidge::
hasNextRidge3d(const QhullFacet &f) const
{
    if(!qh_qh){
        return false;
    }
    vertexT *v= 0;
    // Does not call qh_errexit(), TRY_QHULL_ not needed
    ridgeT *ridge= qh_nextridge3d(getRidgeT(), f.getFacetT(), &v);
    return (ridge!=0);
}//hasNextRidge3d

//! Return next ridge and optional vertex for a 3d facet and ridge
//! Does not use qh_errexit()
QhullRidge QhullRidge::
nextRidge3d(const QhullFacet &f, QhullVertex *nextVertex) const
{
    vertexT *v= 0;
    ridgeT *ridge= 0;
    if(qh_qh){
        // Does not call qh_errexit(), TRY_QHULL_ not needed
        ridge= qh_nextridge3d(getRidgeT(), f.getFacetT(), &v);
        if(!ridge){
            throw QhullError(10030, "Qhull error nextRidge3d:  missing next ridge for facet %d ridge %d.  Does facet contain ridge?", f.id(), id());
        }
    }
    if(nextVertex!=0){
        *nextVertex= QhullVertex(qh_qh, v);
    }
    return QhullRidge(qh_qh, ridge);
}//nextRidge3d

}//namespace orgQhull

#//!\name Global functions

using std::endl;
using std::ostream;
using orgQhull::QhullRidge;
using orgQhull::QhullVertex;

ostream &
operator<<(ostream &os, const QhullRidge &r)
{
    os << r.print("");
    return os;
}//<< QhullRidge

//! Duplicate of qh_printridge [io_r.c]
ostream &
operator<<(ostream &os, const QhullRidge::PrintRidge &pr)
{
    if(*pr.print_message){
        os << pr.print_message << " ";
    }else{
        os << "     - ";
    }
    QhullRidge r= *pr.ridge;
    os << "r" << r.id();
    if(r.getRidgeT()->tested){
        os << " tested";
    }
    if(r.getRidgeT()->nonconvex){
        os << " nonconvex";
    }
    if(r.getRidgeT()->mergevertex){
      os << " mergevertex";
    }
    if(r.getRidgeT()->mergevertex2){
      os << " mergevertex2";
    }
    if(r.getRidgeT()->simplicialtop){
      os << " simplicialtop";
    }
    if(r.getRidgeT()->simplicialbot){
      os << " simplicialbot";
    }
    os << endl;
    os << r.vertices().print("           vertices:");
    if(r.getRidgeT()->top && r.getRidgeT()->bottom){
        os << "           between f" << r.topFacet().id() << " and f" << r.bottomFacet().id() << endl;
    }else if(r.getRidgeT()->top){
        os << "           top f" << r.topFacet().id() << endl;
    }else if(r.getRidgeT()->bottom){
        os << "           bottom f" << r.bottomFacet().id() << endl;
    }

    return os;
}//<< PrintRidge


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE404_Improper_Resource_Shutdown__freopen_w32CloseHandle_67b.c
Label Definition File: CWE404_Improper_Resource_Shutdown.label.xml
Template File: source-sinks-67b.tmpl.c
*/
/*
 * @description
 * CWE: 404 Improper Resource Shutdown or Release
 * BadSource: freopen Open a file using freopen()
 * Sinks: w32CloseHandle
 *    GoodSink: Close the file using fclose()
 *    BadSink : Close the file using CloseHandle
 * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files
 *
 * */

#include "std_testcase.h"

#include <windows.h>

typedef struct _CWE404_Improper_Resource_Shutdown__freopen_w32CloseHandle_67_structType
{
    FILE * structFirst;
} CWE404_Improper_Resource_Shutdown__freopen_w32CloseHandle_67_structType;

#ifndef OMITBAD

void CWE404_Improper_Resource_Shutdown__freopen_w32CloseHandle_67b_badSink(CWE404_Improper_Resource_Shutdown__freopen_w32CloseHandle_67_structType myStruct)
{
    FILE * data = myStruct.structFirst;
    if (data != NULL)
    {
        /* FLAW: Attempt to close the file using CloseHandle() instead of fclose() */
        CloseHandle((HANDLE)data);
    }
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodB2G uses the BadSource with the GoodSink */
void CWE404_Improper_Resource_Shutdown__freopen_w32CloseHandle_67b_goodB2GSink(CWE404_Improper_Resource_Shutdown__freopen_w32CloseHandle_67_structType myStruct)
{
    FILE * data = myStruct.structFirst;
    if (data != NULL)
    {
        /* FIX: Close the file using fclose() */
        fclose(data);
    }
}

#endif /* OMITGOOD */


text:
package software.amazon.awssdk.codegen.poet.model;

import com.squareup.javapoet.ClassName;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import software.amazon.awssdk.codegen.model.intermediate.IntermediateModel;
import software.amazon.awssdk.codegen.model.intermediate.MemberModel;
import software.amazon.awssdk.codegen.poet.ClassSpec;
import software.amazon.awssdk.codegen.poet.PoetExtension;

public class ServiceModelCopiers {
    private final IntermediateModel intermediateModel;
    private final PoetExtension poetExtensions;
    private final TypeProvider typeProvider;

    public ServiceModelCopiers(IntermediateModel intermediateModel) {
        this.intermediateModel = intermediateModel;
        this.poetExtensions = new PoetExtension(intermediateModel);
        this.typeProvider = new TypeProvider(intermediateModel);
    }

    public Collection<ClassSpec> copierSpecs() {
        Map<ClassName, ClassSpec> memberSpecs = new HashMap<>();
        allShapeMembers().values().stream()
                .filter(m -> !canCopyReference(m))
                .map(m -> new MemberCopierSpec(m, this, typeProvider, poetExtensions))
                .forEach(spec -> memberSpecs.put(spec.className(), spec));

        return memberSpecs.values();
    }

    public Optional<ClassName> copierClassFor(MemberModel memberModel) {
        if (canCopyReference(memberModel)) {
            return Optional.empty();
        }

        // FIXME: Some services (Health) have shapes with names
        // that differ only in the casing of the first letter, and generating
        // classes for them breaks on case insensitive filesystems...
        String shapeName = memberModel.getC2jShape();
        if (shapeName.substring(0, 1).toLowerCase(Locale.ENGLISH).equals(shapeName.substring(0, 1))) {
            shapeName = "_" + shapeName;
        }

        return Optional.of(poetExtensions.getModelClass(shapeName + "Copier"));
    }

    public String copyMethodName() {
        return "copy";
    }

    public String enumToStringCopyMethodName() {
        return "copyEnumToString";
    }

    public String stringToEnumCopyMethodName() {
        return "copyStringToEnum";
    }

    public String copyFromBuilderMethodName() {
        return "copyFromBuilder";
    }

    public String copyToBuilderMethodName() {
        return "copyToBuilder";
    }

    private Map<String, MemberModel> allShapeMembers() {
        Map<String, MemberModel> shapeMembers = new HashMap<>();
        intermediateModel.getShapes().values().stream()
                .flatMap(s -> s.getMembersAsMap().values().stream())
                .forEach(m -> shapeMembers.put(m.getC2jShape(), m));
        return shapeMembers;
    }

    private boolean canCopyReference(MemberModel m) {
        return !m.isList() && !m.isMap();
    }
}