text:
function solve() {

	tfObjSort = {
		init: function () {
			Array.prototype.objSort = function () {
				tfObjSort.setThings(this);
				var a = arguments;
				var x = tfObjSort;
				x.a = [];
				x.d = [];
				for (var i = 0; i < a.length; i++) {
					if (typeof a[i] == "string") {
						x.a.push(a[i]);
						x.d.push(1)
					}
					;
					if (a[i] === -1) {
						x.d[x.d.length - 1] = -1
					}
				}
				return this.sort(tfObjSort.sorter);
			};
			Array.prototype.strSort = function () {
				tfObjSort.setThings(this);
				return this.sort(tfObjSort.charSorter)
			}
		},
		sorter: function (x, y) {
			var a = tfObjSort.a
			var d = tfObjSort.d
			var r = 0
			for (var i = 0; i < a.length; i++) {
				if (typeof x + typeof y != "objectobject") {
					return typeof x == "object" ? -1 : 1
				}
				;
				var m = x[a[i]];
				var n = y[a[i]];
				var t = typeof m + typeof n;
				if (t == "booleanboolean") {
					m *= -1;
					n *= -1
				}
				else if (t.split("string").join("").split("number").join("") != "") {
					continue
				}
				;
				r = m - n;
				if (isNaN(r)) {
					r = tfObjSort.charSorter(m, n)
				}
				;
				if (r != 0) {
					return r * d[i]
				}
			}
			return r
		},
		charSorter: function (x, y) {
			if (tfObjSort.ignoreCase) {
				x = x.toLowerCase();
				y = y.toLowerCase()
			}
			;
			var s = tfObjSort.chars;
			if (!s) {
				return x > y ? 1 : x < y ? -1 : 0
			}
			;
			x = x.split("");
			y = y.split("");
			l = x.length > y.length ? y.length : x.length;
			var p = 0;
			for (var i = 0; i < l; i++) {
				p = s.indexOf(x[i]) - s.indexOf(y[i]);
				if (p != 0) {
					break
				}
				;
			}
			;
			if (p == 0) {
				p = x.length - y.length
			}
			;
			return p
		},
		setThings: function (x) {
			this.ignoreCase = x.sortIgnoreCase;
			var s = x.sortCharOrder;
			if (!s) {
				this.chars = false;
				return true
			}
			;
			if (!s.sort) {
				s = s.split(",")
			}
			;
			var a = "";
			for (var i = 1; i < 1024; i++) {
				a += String.fromCharCode(i)
			}
			;
			for (var i = 0; i < s.length; i++) {
				z = s[i].split("");
				var m = z[0];
				var n = z[1];
				var o = "";
				if (z[2] == "_") {
					o = n + m
				} else {
					o = m + n
				}
				;
				a = a.split(m).join("").split(n).join(o);
			}
			;
			this.chars = a
		}
	};
	tfObjSort.init();

// TODO validation for ID is number
	function isNonEmptyString(param) {
		if (typeof (param) !== 'string') {
			return false;
		}
		return param.length >= 1;
	}
	function isValidString(param) {
		if (typeof (param) !== 'string') {
			return false;
		}
		return param.length >= 2 && param.length <= 40;
	}

	function validateNumber(param) {
		param = +param;
		if (typeof param !== 'number') {
			throw new Error('that is not a number');
		}
	}

	var item = function () {
		var id = 0;

		var item = {
			init: function (description, name) {
				this.description = description;
				this.name = name;
				this.id = id += 1;
				return this;
			},
// IVO on hiding the ID with defineProperty _id :) --> https://youtu.be/_qDJgAeEkoo?t=765
			get description() {
				return this._description;
			},
			set description(val) {
				if (!isNonEmptyString(val)) {
					throw new Error('invalid descritpion');
				}
				this._description = val;
			},
			get name() {
				return this._name;
			},
			set name(val) {
				if (!isValidString(val)) {
					throw new Error('invalid item name');
				}
				this._name = val;
			},
			//play: function () {
			//	return this.id + '. ' + this.title + ' - ' + this.author;
			//}
		};

		return item;
	}();

	var book = function (parent) {
		// https://youtu.be/O_M5bsCJjOM?t=3030 TODO without defineProps?
		var book = Object.create(parent);
		book.init = function (name, isbn, genre, description) {
			parent.init.call(this, name, description); //TODO wtf check whaaa
			this.isbn = isbn;
			this.genre = genre;
			return this;
		};
		Object.defineProperty(book, 'isbn', {
			get: function () {
				return this._isbn;
			},
			set: function (val) {
				if (typeof (val) !== 'string' || (val.length !== 10 && val.length !== 13)) {
					throw new Error('invalid isbn');
				}
				val = +val; //remember to convert values!
				if (typeof(val) !== 'number' || val <= 0) {
					throw new Error('invalid isbn');
				}
				this._isbn = val;
			}
		});
		Object.defineProperty(book, 'genre', {
			get: function () {
				return this._genre;
			},
			set: function (val) {
				if (typeof (val) !== 'string' || val.length < 2 && val.length > 20) {
					throw new Error('invalid genre');
				}
				this._genre = val;
			}
		});
		/*var audio = Object.defineProperties(parent, {
		 init: {
		 value: function (title, author, length) {
		 parent.init.call(this, title, author);
		 this.length = length;
		 return this;
		 }
		 },
		 get length() {
		 return this._length;
		 },
		 set length(val) {
		 if (val <= 0) {
		 throw new Error('invalid length');
		 }
		 this._length = val;
		 }
		 });*/
		//audio.play = function () {
		//	var baseResult = parent.play.call(this);
		//	return baseResult + ' - ' + this.length;
		//}
		return book;
	}(item);

	var media = function (parent) {
		var media = Object.create(parent);
		media.init = function (name, rating, duration, description) {
			parent.init.call(this, name, description); //TODO wtf check whaaa
			this.rating = rating;
			this.duration = duration;
			return this;
		};
		Object.defineProperty(media, 'rating', {
			get: function () {
				return this._rating;
			},
			set: function (val) {
				val = +val;
				if (typeof(val) !== 'number' || val < 1 || val > 5) {
					throw new Error('invalid rating');
				}
				this._rating = val;
			}
		});
		Object.defineProperty(media, 'duration', {
			get: function () {
				return this._duration;
			},
			set: function (val) {
				val = +val;
				if (typeof (val) !== 'number' || val.length <= 0) {
					throw new Error('invalid duration');
				}
				this._duration = val;
			}
		});

		return media;
	}(item);

	var catalog = function () {
		var lastId = 0;

		var catalog = {
			init: function (name) {
				this.name = name;
				this.id = lastId += 1;
				this.items = []; // TODO don't use slice!!!! (for testing reasons???)
				return this;
			},
			get name() {
				return this._name;
			},
			set name(val) {
				if (!isValidString(val)) {
					throw new Error('invalid catalog name');
				}
				this._name = val;
			},
			// ************ METHODS ******************************
			add: function (args) { // TODO many args or an array
				if(!args || args === undefined) {
					throw new Error('no arguments passed')
				}
				else if (Array.isArray(args)) {
					if (args.length < 1) {
						throw new Error('add items array error');
					}
					for (var item in args) {
						if (typeof (item.id) === 'undefined'
							|| typeof (item.name) === 'undefined' || typeof (item.description) === 'undefined') {  // TODO tricky stuff
							throw new Error('not instance of item');
						}
					}
					for (var item in args) {
						this.items.push(item);
					}
				}
				else if (args.length < 1) {
					throw new Error('no arguments');
				}
				else { //args.length >=1
					var i,
						len = args.length;
					for (i = 0; i < len; i+=1) {
						if (typeof (args[i].id) === 'undefined'
							|| !args[i].name || !args[i].description) {  // TODO tricky stuff
							throw new Error('not instance of item');
						}
					}
					for (i = 0; i < len; i += 1) {
						this.items.push(args[i]);
					}
				}
				//	else throw new Error ('stuff to add does not exist...maybe?'); // TODO keep?
				return this; // TODO remember to return this to enable chaining
			},

			find: function (id) {
				if (id === undefined) {
					throw new Error('no arguments passed');
				}
				if (typeof id === 'object') { // TODO try with typeof object
					var obj = id,
						resultArr =[],
						len = this.items.length;
					for (var option in obj){ //TODO fix mishmash
						if (option === 'name') {

							for (i = 0; i < len; i += 1) {
								if (this.items[i].name.toLowerCase() === obj.name.toLowerCase()) {
									resultArr.push(this.items[i]);
								}
							}
						}
						if (option === 'id') {
							for (i = 0; i < len; i += 1) {
								if (this.items[i].id === obj.id) {
									resultArr.push(this.items[i]);
								}
							}
						}
					}

					return resultArr;
				}
				else validateNumber(id);
				var i,
					len = this.items.length;

				for (i = 0; i < len; i += 1) {
					if (this.items[i] === 'undefined') {
						return null;
					}
					else if (this.items[i].id === id) {
						return this.items[i];
					}
				}
				return this;
			},
			search: function (pattern) {
				if (!(pattern instanceof String) || pattern.length < 1) {
					throw new Error('invalid pattern');
				}

				pattern = pattern.toLowerCase();
				/*				return this.items.filter(function (items) {
				 return item.getAllItems()
				 .some(function (item) {
				 return item.name.toLocaleLowerCase()
				 .indexOf(pattern) >= 0
				 || item.description.toLocaleLowerCase()
				 .indexOf(pattern) >= 0;
				 });
				 }); // if empty, filter returns an empty array...*/
				var resultArr2 = [];
				var regex = new RegExp(pattern);
				for (var item in this.items) {
					if (regex.test(item.name) || regex.test(item.description)) {
							resultArr2.push(item);
						}
				}
				return resultArr2;
			},
			getAllItems: function () {
				return this.items; // TODO don't use slice??? ever???
			}
		};

		return catalog;
	}();

	var bookCatalog = function (parent) {
		var bookCatalog = Object.create(parent);
		/*		bookCatalog.init = function (name) {
		 parent.init.call(name);
		 return this;
		 };*/
		bookCatalog.getGenres = function () {
			//TODO return array of lowercase strings, all unique genres
			var resultArr = [],
				len = this.items.length,
				i;
			resultArr.push(this.items[0].genre.toLowerCase());
			for (i = 1; i < len; i+=1) {
				if (this.items[i].genre.toLowerCase() !== this.items[i-1].genre.toLowerCase()){
					resultArr.push(this.items[i].genre.toLowerCase());
				}
			}
			return resultArr;
		}; // WTF no test????????
		bookCatalog.search = function () {
		return parent.search.call(this);
		};
		bookCatalog.add = function (args) {
			//TODO extend twice

			if (!args || args === undefined) {
				throw new Error('no arguments passed')
			}
			else if (Array.isArray(args)) {
				if (args.length < 1) {
					throw new Error('add items array error');
				}
				for (var item in args) {
					if (typeof (item.id) === 'undefined'
						|| typeof (item.name) === 'undefined'
						|| typeof (item.description) === 'undefined'
						|| typeof (item.isbn) === 'undefined'
						|| typeof (item.genre) === 'undefined') {  // TODO tricky stuff for book now
						throw new Error('not instance of book');
					}
				}
				for (var item in args) {
					this.items.push(item);
				}
			}
			else if (args.length < 1) {
				throw new Error('no arguments');
			}
			else { //args.length >=1
				var i,
					len = args.length;
				for (i = 0; i < len; i += 1) {
					if (typeof (args[i].id) === 'undefined'
						|| typeof (args[i].name) === 'undefined' || typeof (args[i].description) === 'undefined'
						|| typeof (args[i].isbn) === 'undefined'
						|| !args[i].genre) {  // TODO tricky stuff for book now
						throw new Error('not instance of book');
					}
				}
				for (i = 0; i < len; i += 1) {
					this.items.push(args[i]);
				}
			}
			return this;
		};
		bookCatalog.find = function (id) {
			//TODO extend, no copy-paste...
			if (id === undefined) {
				throw new Error('no arguments passed');
			}
			if (typeof id === 'object') { // TODO try with typeof object
				var i,
					obj = id,
					resultArr = [],
					len = this.items.length;
				for (var option in obj) { //TODO fix mishmash
					if (option === 'name') {

						for (i = 0; i < len; i += 1) {
							if (this.items[i].name.toLowerCase() === obj.name.toLowerCase()) {
								resultArr.push(this.items[i]);
							}
						}
					}
					if (option === 'id') {
						for (i = 0; i < len; i += 1) {
							if (this.items[i].id === obj.id) {
								resultArr.push(this.items[i]);
							}
						}
					}
					if (option === 'genre') {
						for (i = 0; i < len; i += 1) {
							if (this.items[i].genre.toLowerCase() === obj.genre.toLowerCase()) {
								resultArr.push(this.items[i]);
							}
						}
					}
				}
				return resultArr;
			}

			else validateNumber(id);
			var i,
				len = this.items.length;

			for (i = 0; i < len; i += 1) {
				if (this.items[i] === 'undefined') {
					return null;
				}
				else if (this.items[i].id === id) {
					return this.items[i];
				}
			}

			return this;

		};

		return bookCatalog;
	}(catalog);

	//TODO lots of work on media catalog::::::::::::::::::::::::::::::::::::;;
	var mediaCatalog = function (parent) {
		var mediaCatalog = Object.create(parent);
		var i, obj = {}, resultArr = [];

		mediaCatalog.getTop = function (count) {
			if (typeof count !== 'number' || +count < 1) {
				throw new Error('count is invalid');
			};
			/*
			 this.items.sort(function (pl2, pl1) {
			 if (pl1.rating === pl2.rating) {
			 return pl1.id - pl2.id;
			 }
			 return pl1.rating.localeCompare(pl2.rating); // lexic. comparison
			 });*/ //TODO check if it works! or use additional func...
			this.items = this.items.objSort('rating', -1, 'name');
			for (i = 0; i < count; i+=1) {
				obj.name = this.items[i].name;
				obj.id = this.items[i].id;
				resultArr.push(obj); // TODO push string?
			}
			return resultArr;
		};

		mediaCatalog.search = function (pattern) {
			return parent.search.call();
		};
		mediaCatalog.getSortedByDuration = function () {
			this.items = this.items.objSort('duration', -1, 'id');
			//TODO
		};

		mediaCatalog.add = function () {
			//TODO extend twice
			if (!args || args === undefined) {
				throw new Error('no arguments passed')
			}
			else if (Array.isArray(args)) {
				if (args.length < 1) {
					throw new Error('add items array error');
				}
				for (var item in args) {
					if (typeof (item.id) === 'undefined'
						|| typeof (item.name) === 'undefined'
						|| typeof (item.description) === 'undefined'
						|| typeof (item.duration) === 'undefined'
						|| typeof (item.rating) === 'undefined') {  // TODO tricky stuff for book now
						throw new Error('not instance of book');
					}
				}
				for (var item in args) {
					this.items.push(item);
				}
			}
			else if (args.length < 1) {
				throw new Error('no arguments');
			}
			else { //args.length >=1
				var i,
					len = args.length;
				for (i = 0; i < len; i += 1) {
					if (typeof (args[i].id) === 'undefined'
						|| typeof (args[i].name) === 'undefined' || typeof (args[i].description) === 'undefined'
						|| typeof (args[i].duration) === 'undefined'
						|| !args[i].rating) {  // TODO tricky stuff for book now
						throw new Error('not instance of book');
					}
				}
				for (i = 0; i < len; i += 1) {
					this.items.push(args[i]);
				}
			}
			return this;

		};

		return mediaCatalog;
	}(catalog);

	return {
		getBook: function (name, isbn, genre, description) {
			return Object.create(book).init(name, isbn, genre, description);
		},
		getMedia: function (name, rating, duration, description) {
			return Object.create(media).init(name, rating, duration, description);
		},
		getBookCatalog: function (name) {
			return Object.create(bookCatalog).init(name);
		},
		getMediaCatalog: function (name) {
			return Object.create(mediaCatalog).init(name);
		}
	};
}

// test
var module = solve();
var catalog = module.getBookCatalog('John\'s catalog');

var book1 = module.getBook('The secrets of the JavaScript Ninja', '1234567890', 'IT', 'A book about JavaScript');
var book2 = module.getBook('JavaScript: The Good Parts', '0123456789', 'IT', 'A good book about JS');
catalog.add(book1);
catalog.add(book2);

console.log(catalog.find(book1.genre));
//returns book1
var hmobj = {id: book2.id, genre: 'IT'};

console.log(catalog.search('js'));
// returns book2

console.log(catalog.search('javascript'));
//returns book1 and book2

console.log(catalog.search('Te sa zeleni'))
//returns []


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>All Classes - MediaScanner ANE API Documentation</title>
      <base target="classFrame">
      <link rel="stylesheet" href="style.css" type="text/css" media="screen">
      <link rel="stylesheet" href="print.css" type="text/css" media="print">
      <link rel="stylesheet" href="override.css" type="text/css">

All Classes

            MediaScanner

redpajama_set_name: RedPajamaGithub


text:
class Ccla < ActiveRecord::Base
  validates_uniqueness_of :version

  # Get the latest version based on the config value
  def self.latest
    find_by_version(ENV['CCLA_VERSION'])
  end
end


text:
<?php
namespace Recall\Exceptions;

class ParameterClassNotFoundException extends RecallException
{
	/**
	 * @param string $className
	 * @param \ReflectionParameter $parameter
	 */
	public function __construct($className, \ReflectionParameter $parameter)
	{
		$methodName = $parameter->getDeclaringFunction()->getName();
		$className = $parameter->getDeclaringClass()->getName();

		parent::__construct("Could not find class '$className' when resolving parameter '{$parameter->name}' " .
			"in method {$className}::{$methodName}");
	}
}


text:
import collections
import json
import logging
import os
import re
import signal
import subprocess
import time

import ptrace.debugger as pdbg
import ptrace.error as perror
import ptrace.signames

crash_signals = (signal.SIGILL, signal.SIGABRT, signal.SIGFPE, signal.SIGBUS, signal.SIGSEGV, signal.SIGSYS)

def get_pids(name):
    pgrep = ("pgrep", name)
    pid = subprocess.Popen(pgrep, stdout=subprocess.PIPE).communicate()[0]
    return list(map(int, pid.split()))

def get_pid_command(pid):
    proc_path = "/proc/%s/cmdline" % pid
    try:
        with open(proc_path, "r") as f:
            cmdline = f.read().replace("\x00", " ").strip()
    except IOError:
        cmdline = None
    return cmdline

class PtraceDbg(pdbg.Application):

    def __init__(self, options):
        self.options = options
        self.program = self.options.program
        self.processes = []
        self.processOptions()
        self.debugger = pdbg.debugger.PtraceDebugger()
        self.setupDebugger()
        self.is_running = False
        self.logger = logging.getLogger("PtraceDbg")
        super(PtraceDbg, self).__init__()

    def spawn_traced_process(self):
        try:
            process = self.createProcess()
        except pdbg.child.ChildError as ce:
            raise IOError("Failed to create traced process: %s => %s" % (" ".join(self.program), ce))
        self.logger.info("Successfully attached to process: %d" % process.pid)
        process.cont()
        self.logger.info("Moving process to running state: %d" % process.pid)
        self.processes.append(process)
        return process

    def stop(self):
        for process in self.processes:
            try:
                process.detach()
                self.processes.remove(process)
                self.logger.warn("Detached from process: %d" % process.pid)
                process.terminate()
                self.logger.warn("Terminated process: %d" % process.pid)
            except perror.PtraceError:
                pass
        self.is_running = False

    def watch(self, on_signal, on_event, on_exit):
        # Spawning of tracee MUST be done in same thread as event waitProcessEvent() on Linux
        try:
            self.spawn_traced_process()
        except IOError as ioe:
            self.logger.fatal(ioe)
            # This is realy ugly, it relies on the fuzzmon sigint handler to exit
            # TODO: Implement a queue to relay thread satus to spawner
            os.kill(os.getpid(), signal.SIGINT)
            return
        self.is_running = True
        self.logger.info("Debugger entered event monitoring loop")
        while self.is_running and self.processes != []:
            try:
                event = self.debugger.waitProcessEvent()
            except OSError as oe:
                self.logger.fatal("Debugger event loop failed: %s" % oe)
                self.stop()
                return
            process = event.process
            self.logger.info("Caught event on process: %d => \"%s\". Dispatching to callback" % (process.pid, event))
            if event.__class__ == pdbg.ProcessSignal:
                on_signal(event)
            elif event.__class__ == pdbg.ProcessEvent:
                on_event(event)
            elif event.__class__ == pdbg.ProcessExit:
                on_exit(event)
            else:
                raise RuntimeError("Unexpected process event: %s" % event)
            if not process.is_attached:
                try:
                    self.processes.remove(process)
                    self.logger.info("Detected process as dead: %d" % process.pid)
                except ValueError:
                    pass
        self.logger.info("Debugger exiting event monitoring loop")
        self.is_running = False

class CrashReport(object):

    # Matches
    # 'MAPS: 0x00007fb7b25ae000-0x00007fb7b2730000 => /lib/x86_64-linux-gnu/libc-2.13.so (r-xp)'
    # 'MAPS: 0x0000000000df5000-0x0000000000e16000 => [heap] (rwxp)'
    # 'MAPS: 0x00007fb7b2b56000-0x00007fb7b2b59000 (rwxp)'
    # Into start/stop address, binary, permissions
    MAPS_REGEXP = "MAPS:\s(0x[0-9a-fA-F]+)-(0x[0-9a-fA-F]+)\s(?:=>\s)?(.*?)\s?\((.+)\)"

    def __init__(self, sessid, pid, signum, stream_id):
        self.pid = pid
        self.sessid = sessid
        self.signal = ptrace.signames.signalName(signum)
        self.stream_id = stream_id
        self.time = time.time()
        self.registers = {}
        self.stack = collections.OrderedDict()
        self.backtrace = collections.OrderedDict()
        self.disassembly = collections.OrderedDict()
        self.maps = []
        self.stream = []
        self.history = []
        self.regexp = re.compile(CrashReport.MAPS_REGEXP)

    def to_json(self, f):
        json.dump({"session_id": self.sessid,
                   "stream_count": self.stream_id,
                   "pid": self.pid,
                   "signal": self.signal,
                   "time": self.time,
                   "registers": self.registers,
                   "backtrace": self.backtrace,
                   "disassembly": self.disassembly,
                   "maps": self.maps,
                   "stack": self.stack,
                   "stream": self.stream,
                   "history": self.history},
                  f,
                  indent=4)

    def dump_regs(self, str_):
        try:
            reg, val = list(map(lambda x: x.strip(), str_.split("=")))
            self.registers[reg] = val
        except ValueError:
            pass

    def dump_maps(self, str_):
        try:
            start_addr, stop_addr, binary, perms = self.regexp.match(str_).groups()
            self.maps.append(((start_addr, stop_addr), binary, perms))
        except ValueError:
            pass

    def dump_stack(self, str_):
        try:
            addr, val = list(map(lambda x: x.strip(), str_.split(":")))
            self.stack[addr] = val
        except ValueError:
            pass

    def dump_backtrace(self, frame):
        self.backtrace[hex(frame.ip)] = (frame.name, frame.arguments)

    def dump_code(self, str_):
        self.disassembly[hex(str_.address)] = str_.text


text:
Lean Mapper
===========

Lean Mapper is a tiny ORM based on powerful [dibi database abstraction library](http://dibiphp.com) for PHP 5.

See [www.leanmapper.com](http://www.leanmapper.com) for more informations, usage examples and documentation.

License
-------

MIT

Copyright (c) 2013 Vojtěch Kohout (aka Tharos)


text:
class PostEffect;

///
class RenderGlowMgr : public RenderTexTargetBinManager
{
   typedef RenderTexTargetBinManager Parent;

public:

   RenderGlowMgr();
   virtual ~RenderGlowMgr();

   /// Returns the glow post effect.
   PostEffect* getGlowEffect();

   /// Returns true if the glow post effect is
   /// enabled and the glow buffer should be updated.
   bool isGlowEnabled();

   // RenderBinManager
   virtual void addElement( RenderInst *inst );
   virtual void render( SceneRenderState *state );

   // ConsoleObject
   DECLARE_CONOBJECT( RenderGlowMgr );

protected:

   class GlowMaterialHook : public MatInstanceHook
   {
   public:

      GlowMaterialHook( BaseMatInstance *matInst );
      virtual ~GlowMaterialHook();

      virtual BaseMatInstance *getMatInstance() { return mGlowMatInst; }

      virtual const MatInstanceHookType& getType() const { return Type; }

      /// Our material hook type.
      static const MatInstanceHookType Type;

   protected:

      static void _overrideFeatures(   ProcessedMaterial *mat,
                                       U32 stageNum,
                                       MaterialFeatureData &fd,
                                       const FeatureSet &features );

      BaseMatInstance *mGlowMatInst;
   };

   SimObjectPtr<PostEffect> mGlowEffect;
   RenderParticleMgr *mParticleRenderMgr;
};

#endif // _RENDERGLOWMGR_H_


text:
/*!
 * \brief EdgeTPU runtime that can run tflite model compiled
 *        for EdgeTPU containing only tvm PackedFunc.
 * \file edgetpu_runtime.h
 */
#ifndef TVM_RUNTIME_CONTRIB_EDGETPU_EDGETPU_RUNTIME_H_
#define TVM_RUNTIME_CONTRIB_EDGETPU_EDGETPU_RUNTIME_H_

#include <edgetpu.h>

#include <memory>
#include <string>

#include "../tflite/tflite_runtime.h"
#include "edgetpu.h"

namespace tvm {
namespace runtime {

/*!
 * \brief EdgeTPU runtime.
 *
 *  This runtime can be accessed in various languages via
 *  the TVM runtime PackedFunc API.
 */
class EdgeTPURuntime : public TFLiteRuntime {
 public:
  /*!
   * \brief Destructor of EdgeTPURuntime.
   *
   * NOTE: tflite::Interpreter member should be destruct before the EdgeTpuContext member
   * destruction. If the order is reverse, occurs SEGV in the destructor of tflite::Interpreter.
   */
  ~EdgeTPURuntime() { interpreter_.reset(); }

  /*!
   * \return The type key of the executor.
   */
  const char* type_key() const final { return "EdgeTPURuntime"; }

  /*!
   * \brief Initialize the edge TPU tflite runtime with tflite model and device.
   * \param tflite_model_bytes The tflite model.
   * \param dev The device where the tflite model will be executed on.
   */
  void Init(const std::string& tflite_model_bytes, Device dev);

 private:
  std::shared_ptr<edgetpu::EdgeTpuContext> edgetpu_context_;
};

}  // namespace runtime
}  // namespace tvm

#endif  // TVM_RUNTIME_CONTRIB_EDGETPU_EDGETPU_RUNTIME_H_


text:
#region License

// Copyright © 2016 Tinkoff Bank
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#endregion

using System;
using System.Threading.Tasks;
using Windows.UI.Xaml.Media.Animation;

namespace Tinkoff.Acquiring.UI.Extensions
{
    static class StoryboardExtensions
    {
        public static Task BeginAsync(this Storyboard storyboard)
        {
            var tcs = new TaskCompletionSource<object>();
            EventHandler<object> onCompleted = null;
            onCompleted = (sender, o) =>
            {
                storyboard.Completed -= onCompleted;
                tcs.SetResult(null);
            };
            storyboard.Completed += onCompleted;
            storyboard.Begin();
            return tcs.Task;
        }
    }
}


text:
#define BOOST_TEST_MODULE odeint_integrate_functions_implicit

#include <vector>
#include <cmath>
#include <iostream>

#include <boost/numeric/odeint/config.hpp>

#include <boost/array.hpp>
#include <boost/ref.hpp>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>

#include <boost/test/unit_test.hpp>

#include <boost/mpl/vector.hpp>

#ifndef ODEINT_INTEGRATE_ITERATOR
#include <boost/numeric/odeint/integrate/integrate_const.hpp>
#include <boost/numeric/odeint/integrate/integrate_adaptive.hpp>
#include <boost/numeric/odeint/integrate/integrate_times.hpp>
#include <boost/numeric/odeint/integrate/integrate_n_steps.hpp>
#else
#include <boost/numeric/odeint/iterator/integrate/integrate_const.hpp>
#include <boost/numeric/odeint/iterator/integrate/integrate_adaptive.hpp>
#include <boost/numeric/odeint/iterator/integrate/integrate_times.hpp>
#include <boost/numeric/odeint/iterator/integrate/integrate_n_steps.hpp>
#endif
#include <boost/numeric/odeint/stepper/rosenbrock4.hpp>
#include <boost/numeric/odeint/stepper/rosenbrock4_controller.hpp>
#include <boost/numeric/odeint/stepper/rosenbrock4_dense_output.hpp>

using namespace boost::unit_test;
using namespace boost::numeric::odeint;
namespace mpl = boost::mpl;
namespace ublas = boost::numeric::ublas;

typedef double value_type;
typedef ublas::vector< value_type > state_type;
typedef boost::numeric::ublas::matrix< value_type > matrix_type;

struct sys
{
    void operator()( const state_type &x , state_type &dxdt , const value_type &t ) const
    {
        dxdt( 0 ) = x( 0 ) + 2 * x( 1 );
        dxdt( 1 ) = x( 1 );
    }
};

struct jacobi
{
    void operator()( const state_type &x , matrix_type &jacobi , const value_type &t , state_type &dfdt ) const
    {
        jacobi( 0 , 0 ) = 1;
        jacobi( 0 , 1 ) = 2;
        jacobi( 1 , 0 ) = 0;
        jacobi( 1 , 1 ) = 1;
        dfdt( 0 ) = 0.0;
        dfdt( 1 ) = 0.0;
    }
};

struct push_back_time
{
    std::vector< double >& m_times;

    push_back_time( std::vector< double > &times )
    :  m_times( times ) { }

    void operator()( const state_type &x , double t )
    {
        m_times.push_back( t );
    }
};

template< class Stepper >
struct perform_integrate_const_test
{
    void operator()( void )
    {
        state_type x( 2 , 1.0 );
        const value_type dt = 0.03;
        const value_type t_end = 10.0;

        std::vector< value_type > times;

        integrate_const( Stepper() , std::make_pair( sys() , jacobi() ) , x , 0.0 , t_end ,
                                        dt , push_back_time( times ) );

        BOOST_CHECK_EQUAL( static_cast<int>(times.size()) , static_cast<int>(std::floor(t_end/dt))+1 );

        for( size_t i=0 ; i<times.size() ; ++i )
        {
            //std::cout << i << std::endl;
            // check if observer was called at times 0,1,2,...
            BOOST_CHECK_SMALL( times[i] - static_cast< value_type >(i)*dt , (i+1) * 2.0e-16 );
        }
    }
};

template< class Stepper >
struct perform_integrate_adaptive_test
{
    void operator()( void )
    {
        state_type x( 2 , 1.0 );
        const value_type dt = 0.03;
        const value_type t_end = 10.0;

        std::vector< value_type > times;

        size_t steps = integrate_adaptive( Stepper() , std::make_pair( sys() , jacobi() ) , x , 0.0 , t_end ,
                                        dt , push_back_time( times ) );

        BOOST_CHECK_EQUAL( times.size() , steps+1 );

        BOOST_CHECK_SMALL( times[0] - 0.0 , 2.0e-16 );
        BOOST_CHECK_SMALL( times[times.size()-1] - t_end , times.size() * 3.0e-16 );
    }
};

template< class Stepper >
struct perform_integrate_times_test
{
    void operator()( void )
    {
        state_type x( 2 , 1.0 );

        const value_type dt = 0.03;

        std::vector< double > times;

        // simple stepper
        integrate_times( Stepper() , std::make_pair( sys() , jacobi() ) , x ,
                    boost::counting_iterator<int>(0) , boost::counting_iterator<int>(10) ,
                    dt , push_back_time( times ) );

        BOOST_CHECK_EQUAL( static_cast<int>(times.size()) , 10 );

        for( size_t i=0 ; i<times.size() ; ++i )
            // check if observer was called at times 0,1,2,...
            BOOST_CHECK_EQUAL( times[i] , static_cast<double>(i) );
    }
};

template< class Stepper >
struct perform_integrate_n_steps_test
{
    void operator()( void )
    {
        state_type x( 2 , 1.0 );

        const value_type dt = 0.03;
        const int n = 200;

        std::vector< double > times;

        // simple stepper
        value_type end_time = integrate_n_steps( Stepper() , std::make_pair( sys() , jacobi() ) , x , 0.0 , dt , n , push_back_time( times ) );

        BOOST_CHECK_SMALL( end_time - n*dt , 3.0e-16 );
        BOOST_CHECK_EQUAL( static_cast<int>(times.size()) , n+1 );

        for( size_t i=0 ; i<times.size() ; ++i )
            // check if observer was called at times 0,1,2,...
            BOOST_CHECK_SMALL( times[i] - static_cast< value_type >(i)*dt , (i+1) * 2.0e-16 );
    }
};

class stepper_methods : public mpl::vector<
    rosenbrock4< value_type > ,
    rosenbrock4_controller< rosenbrock4< value_type > > ,
    rosenbrock4_dense_output< rosenbrock4_controller< rosenbrock4< value_type > > >
> { };

BOOST_AUTO_TEST_SUITE( integrate_test )

BOOST_AUTO_TEST_CASE_TEMPLATE( integrate_const_test_case , Stepper, stepper_methods )
{
    perform_integrate_const_test< Stepper > tester;
    tester();
}

BOOST_AUTO_TEST_CASE_TEMPLATE( integrate_adaptive_test_case , Stepper, stepper_methods )
{
    perform_integrate_adaptive_test< Stepper > tester;
    tester();
}

BOOST_AUTO_TEST_CASE_TEMPLATE( integrate_times_test_case , Stepper, stepper_methods )
{
    perform_integrate_times_test< Stepper > tester;
    tester();
}

class simple_stepper_methods : public mpl::vector<
    rosenbrock4< value_type >
> { };

BOOST_AUTO_TEST_CASE_TEMPLATE( integrate_n_steps_test_case , Stepper, simple_stepper_methods )
{
    perform_integrate_n_steps_test< Stepper > tester;
    tester();
}

BOOST_AUTO_TEST_SUITE_END()


text:
categories:
- philosophy
date: 2017-04-16T08:45:39+02:00
tags:
- 'religion'
- 'causation'
title: secularism
---
Religious secularism has become an intensely debated idea all over the world today.
In secular India, especially, secular opinions are sometimes discredited as giving too much
leeway for people with vested interests to take advantage of. Secularism as an idea
is growing subtler and from there it could soon become ambiguous. There are instances
where secular movements are equated to anti-national movements especially when the
interests seem to conflict.  This is where I
feel the need to share my understanding of it. I am a Hindu. The more my intellectual
exploration of existence grew, the more I found fitting into the definition of a Hindu.
I know close to nothing about other religions. From the hinduism tinted view, here
is my take on secularism. After all, we need the idea of secularism between religions.
Hence an atheist's view of secularism doesn't hold practical value.

To present the idea of secularism from the point of view of a Hindu, I must introduce
the religion or the point of this religion.


text:
package org.apache.whirr.service.hadoop.integration.benchmark;

import org.apache.hadoop.fs.TestDFSIO;
import org.apache.hadoop.mapred.JobConf;
import org.apache.whirr.service.hadoop.integration.HadoopServiceController;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HadoopServiceTestDFSIOBenchmark {
  private static final Logger LOG =
    LoggerFactory.getLogger(HadoopServiceTestDFSIOBenchmark.class);

  private static boolean shutdownClusterOnTearDown;
  private static HadoopServiceController controller =
    HadoopServiceController.getInstance();

  @BeforeClass
  public static void setUp() throws Exception {
    shutdownClusterOnTearDown = controller.ensureClusterRunning();
  }

  @AfterClass
  public static void tearDown() throws Exception {
    if (shutdownClusterOnTearDown) {
      controller.shutdown();
    }
  }

  @Test
  public void test() throws Exception {
    // We use TestDFSIO's Tool interface so we can pass the configuration,
    // but this is only available after Hadoop 0.20.2
    // (https://issues.apache.org/jira/browse/MAPREDUCE-1832)
    // so we use a local copy of TestDFSIO with this patch
    int runs = Integer.parseInt(System.getProperty("testDFSIORuns", "3"));
    for (int i = 0; i < runs; i++) {
      LOG.info("Starting TestDFSIO run {} of {}", i + 1, runs);
      TestDFSIO testDFSIO = new TestDFSIO();
      JobConf jobConf = controller.getJobConf();
      jobConf.set("test.build.data", "/user/root/benchmark/TestDFSIO");
      testDFSIO.setConf(jobConf);
      testDFSIO.run("-write -nrFiles 10 -fileSize 1000".split(" "));
      testDFSIO.run("-read -nrFiles 10 -fileSize 1000".split(" "));
      testDFSIO.run(new String[] { "-clean" });
      LOG.info("Completed TestDFSIO run {} of {}", i + 1, runs);
    }
  }
}


text:
#pragma once

#include <stdint.h>
#include "il2cpp-object-internals.h"
#include "il2cpp-config.h"

struct Il2CppObject;
struct Il2CppDelegate;
struct Il2CppReflectionType;
struct Il2CppReflectionMethod;
struct Il2CppReflectionField;
struct Il2CppArray;
struct Il2CppException;
struct Il2CppReflectionModule;
struct Il2CppAssembly;
struct Il2CppAssemblyName;
struct Il2CppAppDomain;

namespace il2cpp
{
namespace icalls
{
namespace System
{
namespace System
{
namespace IO
{
    typedef int32_t InotifyMask;

    class LIBIL2CPP_CODEGEN_API InotifyWatcher
    {
    public:
        static intptr_t RemoveWatch(intptr_t fd, int32_t wd);
        static int32_t AddWatch(intptr_t fd, Il2CppString* name, InotifyMask mask);
        static intptr_t GetInotifyInstance();
    };
} /* namespace IO */
} /* namespace System */
} /* namespace System */
} /* namespace icalls */
} /* namespace il2cpp */


text: The CIFAR10 dataset in the TFRecord format has been uploaded to gs://workshop-datasets/cifar10


text:
package org.apache.camel.idea.util;

import java.io.File;
import java.util.stream.Stream;

import com.intellij.openapi.components.ServiceManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiLiteralExpression;
import com.intellij.testFramework.PsiTestUtil;
import org.apache.camel.idea.CamelLightCodeInsightFixtureTestCaseIT;
import org.apache.camel.idea.service.CamelService;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;

public class IdeaUtilsSkipEndointValidationTestIT extends CamelLightCodeInsightFixtureTestCaseIT {

    private static final String ACTIVEMQ_ARTIFACT = "org.apache.activemq:activemq-camel:5.14.3";

    private static final String CODE = "import org.apache.camel.builder.RouteBuilder;\n"
        + "import org.apache.activemq.camel.component.ActiveMQComponent;\n"
        + "\n"
        + "public class DummyTestData extends RouteBuilder{\n"
        + "\n"
        + "    @Override\n"
        + "    public void configure() throws Exception {\n"
        + "        new org.apache.activemq.ActiveMQConnectionFactory(\"vm://broker\");\n"
        + "        new org.apache.activemq.spring.ActiveMQConnectionFactory(\"vm://spring\");\n"
        + "        new org.apache.activemq.ActiveMQXAConnectionFactory(\"vm://broker-xa\");\n"
        + "        new org.apache.activemq.spring.ActiveMQXAConnectionFactory(\"vm://spring-xa\");\n"
        + "        ActiveMQComponent aq = ActiveMQComponent.activeMQComponent(\"vm://localhost\");\n"
        + "        aq.setBrokerURL(\"tcp://evilhost:666\");\n"
        + "        getContext().addComponent(\"queue\", aq);"
        + "    }\n"
        + "\n"
        + ""
        + "}\n";

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        ServiceManager.getService(myFixture.getProject(), CamelService.class).setCamelPresent(true);
        Stream.of(
            Maven.resolver().resolve(ACTIVEMQ_ARTIFACT)
                .withTransitivity().asFile()
        ).map(File::getAbsolutePath)
            .forEach(path -> PsiTestUtil.addLibrary(myFixture.getModule(), path));
    }

    public void testShouldSkipActiveMQComponentFactoryMethod() {
        myFixture.configureByText("DummyTestData.java", CODE);
        PsiElement element = myFixture.findElementByText("\"vm://localhost\"", PsiLiteralExpression.class);
        assertTrue("ActiveMQComponent.activeMQComponent should be skipped", CamelIdeaUtils.skipEndpointValidation(element));
    }

    public void testShouldSkipSetBrokerUrlMethod() {
        myFixture.configureByText("DummyTestData.java", CODE);
        PsiElement element = myFixture.findElementByText("\"tcp://evilhost:666\"", PsiLiteralExpression.class);
        assertTrue("setBrokerURL method should be skipped", CamelIdeaUtils.skipEndpointValidation(element));
    }

    public void testShouldSkipActiveMQConnectionFactoryConstructor() {
        myFixture.configureByText("DummyTestData.java", CODE);
        PsiElement element = myFixture.findElementByText("\"vm://broker\"", PsiLiteralExpression.class);
        assertTrue("ActiveMQConnectionFactory constructor should be skipped", CamelIdeaUtils.skipEndpointValidation(element));
        element = myFixture.findElementByText("\"vm://spring\"", PsiLiteralExpression.class);
        assertTrue("spring ActiveMQConnectionFactory constructor should be skipped", CamelIdeaUtils.skipEndpointValidation(element));
    }
    public void testShouldSkipActiveMQXAConnectionFactoryConstructor() {
        myFixture.configureByText("DummyTestData.java", CODE);
        PsiElement element = myFixture.findElementByText("\"vm://broker-xa\"", PsiLiteralExpression.class);
        assertTrue("ActiveMQXAConnectionFactory constructor should be skipped", CamelIdeaUtils.skipEndpointValidation(element));
        element = myFixture.findElementByText("\"vm://spring-xa\"", PsiLiteralExpression.class);
        assertTrue("spring ActiveMQXAConnectionFactory constructor should be skipped", CamelIdeaUtils.skipEndpointValidation(element));
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<recipeml version="0.5">
  <recipe>
    <head>
      <title>Barbecued Spareribs</title>
      <categories>
        <cat>Main dish</cat>
        <cat>Meats</cat>
        <cat>Appetizers</cat>
        <cat>Microwave</cat></categories>
      <yield>4</yield></head>
    <ingredients>
      <ing>
        <amt>
          <qty>3</qty>
          <unit>pounds</unit></amt>
        <item>Pork or lamb spareribs, cut into serving pieces</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>teaspoons</unit></amt>
        <item>Chili powder</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>cups</unit></amt>
        <item>Barbecue sauce (recipe)</item></ing>
      <ing>
        <amt>
          <qty>2</qty>
          <unit>tablespoons</unit></amt>
        <item>Lemon juice (optional)</item></ing></ingredients>
    <directions>
      <step>  1. Place spareribs in a large, shallow, heat-resistant, non- metallic
  baking dish. 2. Heat, uncovered, in Microwave Oven 7 minutes. 3. Turn
  spareribs over and heat an additional 7 minutes 4. Drain off excess fat. 5.
  Conmbine chili powder and barbecue sauce. 6. Pour half of sauce over ribs.
  7. Heat, uncovered, in Microwave Oven 4 minutes. 8. Turn spareribs again.
  Sprinkle with lemon juice if desired 9. Pour on remaining sauce and heat,
  uncovered, for 8 minutes or until fork-tender. Pork should always be cooked
  until well-done.

  From Gemini's MASSIVE MealMaster collection at www.synapse.com/~gemini

</step></directions></recipe></recipeml>


text:
<?php

namespace Symfony\Bundle\FrameworkBundle\Tests\Functional\Bundle\TestBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\DependencyInjection\ContainerAware;

class ProfilerController extends ContainerAware
{
    public function indexAction()
    {
        return new Response('Hello');
    }
}


text: Some sample projects to learn SPMeta2.


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<title>Ruby Twitter Gem by John Nunemaker</title>
	<link rel="stylesheet" href="css/common.css" type="text/css" />

Twitter

API wrapper for Twitter and Twitter Search API's

Docs

Github

Rubyforge

Note

The Twitter gem supports OAuth and HTTP Auth (until Twitter deprecates it). OAuth is scary at first, but not once you try it out a little bit. Feel free to read my article on OAuth to get past the scary part. Also, I have created an example app that uses OAuth and the Twitter gem for you to peruse.

Install

$ sudo gem install twitter

Examples

First some OAuth action:

# NOT SHOWN: granting access to twitter on website
# and using request token to generate access token
oauth = Twitter::OAuth.new('consumer token', 'consumer secret')
oauth.authorize_from_access('access token', 'access secret')

client = Twitter::Base.new(oauth)
client.friends_timeline.each  { |tweet| puts tweet.inspect }
client.user_timeline.each     { |tweet| puts tweet.inspect }
client.replies.each           { |tweet| puts tweet.inspect }

client.update('Heeeyyyyoooo from Twitter Gem!')

Now some HTTP Auth action:

httpauth = Twitter::HTTPAuth.new('username', 'password')
base = Twitter::Base.new(httpauth)
base.update('Heeeeyyyyooo from the Twitter Gem')
base.friends_timeline.each { |tweet| puts tweet.text }

Search API Examples

#searches all tweets for httparty
Twitter::Search.new('httparty').each do |r|
  puts r.inspect
end

# searches all of jnunemaker's tweets for httparty
Twitter::Search.new('httparty').from('jnunemaker').each do |r|
  puts r.inspect
end

# searches all tweets from jnunemaker to oaknd1
Twitter::Search.new.from('jnunemaker').to('oaknd1').each do |r|
  puts r.inspect
end

# you can also use fetch to actually just get the parsed response
Twitter::Search.new.from('jnunemaker').to('oaknd1').fetch()

Trends API Examples

Twitter::Trends.current
Twitter::Trends.current(:exclude => 'hashtags')

Twitter::Trends.daily # current day
Twitter::Trends.daily(:exclude => 'hashtags')
Twitter::Trends.daily(:date => Date.new(2009, 5, 1))

Twitter::Trends.weekly # current day
Twitter::Trends.weekly(:exclude => 'hashtags')
Twitter::Trends.weekly(:date => Date.new(2009, 5, 1))

Support

Conversations welcome in the google group and bugs/features over at Github

Created by John Nunemaker


text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module GhostLang.Compiler.ModuleFileReader
    ( runModuleReader
    , parseGhostModules
    ) where

import Control.Exception (SomeException, try)
import Control.Monad.State (MonadState, StateT, evalStateT, modify', get)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Data.List (delete, find)
import GhostLang.Interpreter (IntrinsicSet)
import GhostLang.Compiler.Grammar (ghostModuleDef)
import GhostLang.Types ( ImportDecl (..)
                       , GhostModule (..)
                       )
import Text.Parsec (ParseError)
import Text.Parsec.String (parseFromFile)
import Text.Printf (printf)
import System.FilePath

type ParseResult = Either ParseError (GhostModule IntrinsicSet)
type PendList = [(FilePath, Bool)]
data Result = Ok | FailedWith String
    deriving Eq

data State = State { baseDir  :: !FilePath
                   , pendList :: ![(FilePath, Bool)]
                   , modList  :: ![GhostModule IntrinsicSet] }

-- | Monad stack for module reading. Just StateT on top of IO.
newtype ModuleReader a =
    ModuleReader { extrModuleReader :: StateT State IO a }
    deriving (Functor, Applicative, Monad, MonadState State, MonadIO)

-- | Run the ModuleReader monad stack.
runModuleReader :: ModuleReader a -> IO a
runModuleReader act = evalStateT (extrModuleReader act) emptyState

-- | Entry for the parsing of modules parsing.
parseGhostModules :: FilePath
                  -> ModuleReader (Either String [GhostModule IntrinsicSet])
parseGhostModules path = do
  -- Save the base directory for the input - Main - file. It will be
  -- used as base for all file reads.
  setBaseDir $ takeDirectory path

  -- Add the first pending. Pendings is what make the engine run.
  addPending $ takeFileName path

  result <- parseLoop
  case result of
    Ok             -> do
        mods <- getModList
        return $ Right mods
    FailedWith msg -> return $ Left msg

-- | Parse until all pending files are consumed or an error has
-- occurred.
parseLoop :: ModuleReader Result
parseLoop = do
  pending <- nextPending
  case pending of
    Just file -> do
        result <- parseGhostMod file
        if result == Ok then parseLoop
        else return result

    -- No more modules to read, and no errors. Done!
    Nothing   -> return Ok

-- | The parsing workhorse.
parseGhostMod :: FilePath -> ModuleReader Result
parseGhostMod file = do
  -- Combine the filename with the stored base to form a complete
  -- path.
  path <- combineWithBaseDir file

  -- Invoke the parser. The result is Either in two levels, exception
  -- level and parser error level.
  maybeFailed <- liftIO $ tryParse path
  case maybeFailed of
    Right res -> case res of
                   Right m  -> do togglePending file
                                  addModule m
                                  mapM_ addPending $ importSet m
                                  return Ok
                   Left msg -> return $ FailedWith (show msg)
    Left exc  -> return $ FailedWith (printf "Got %s when reading %s"
                                     (show exc) path)

  where
    tryParse :: FilePath -> IO (Either SomeException ParseResult)
    tryParse path = try $ parseFromFile ghostModuleDef path

combineWithBaseDir :: FilePath -> ModuleReader FilePath
combineWithBaseDir file = combine <$> (baseDir <$> get) <*> pure file

setBaseDir :: FilePath -> ModuleReader ()
setBaseDir path = modify' $ \s -> s { baseDir = path }

addPending :: FilePath -> ModuleReader ()
addPending file = modify' $ \s -> s { pendList = addPending' file (pendList s) }

nextPending :: ModuleReader (Maybe FilePath)
nextPending = do
  xs <- pendList <$> get
  return $ fmap fst (find snd xs)

togglePending :: FilePath -> ModuleReader ()
togglePending file =
    modify' $ \s -> s { pendList = togglePending' file (pendList s) }

addModule :: GhostModule IntrinsicSet -> ModuleReader ()
addModule m = modify' $ \s -> s { modList = m : modList s }

getModList :: ModuleReader [GhostModule IntrinsicSet]
getModList = modList <$> get

emptyState :: State
emptyState = State { baseDir = "", pendList = [], modList = [] }

addPending' :: FilePath -> PendList -> PendList
addPending' fp xs = maybe ((fp, True):xs) (const xs) (lookup fp xs)

togglePending' :: FilePath -> PendList -> PendList
togglePending' file xs = maybe xs (\tup -> (file, False):delete tup xs)
                                  (find ((==file) . fst) xs)

importSet :: GhostModule IntrinsicSet -> [FilePath]
importSet (GhostModule _ idecl _ _) = map makeRoot idecl
    where
      makeRoot :: ImportDecl -> FilePath
      makeRoot (ImportDecl decl) = addExtension (joinPath decl) "gl"


text:
/**
 * @file ControlAllocationPseudoInverse.hpp
 *
 * Simple Control Allocation Algorithm
 *
 * @author Julien Lecoeur <julien.lecoeur@gmail.com>
 */

#include "ControlAllocationPseudoInverse.hpp"

void
ControlAllocationPseudoInverse::setEffectivenessMatrix(
	const matrix::Matrix<float, ControlAllocation::NUM_AXES, ControlAllocation::NUM_ACTUATORS> &effectiveness,
	const matrix::Vector<float, ControlAllocation::NUM_ACTUATORS> &actuator_trim, int num_actuators)
{
	ControlAllocation::setEffectivenessMatrix(effectiveness, actuator_trim, num_actuators);
	_mix_update_needed = true;
}

void
ControlAllocationPseudoInverse::updatePseudoInverse()
{
	if (_mix_update_needed) {
		_mix = matrix::geninv(_effectiveness);
		_mix_update_needed = false;
	}
}

void
ControlAllocationPseudoInverse::allocate()
{
	//Compute new gains if needed
	updatePseudoInverse();

	// Allocate
	_actuator_sp = _actuator_trim + _mix * (_control_sp - _control_trim);

	// Clip
	clipActuatorSetpoint(_actuator_sp);

	// Compute achieved control
	_control_allocated = _effectiveness * _actuator_sp;
}


text:
import numpy as np
from scipy.interpolate import interp1d

def sharpen_templates(fname_templates, fname_out=None):

    templates = np.load(fname_templates)

    n_units, n_times, n_channels = templates.shape
    mcs = templates.ptp(1).argmax(1)

    t_range = np.arange(n_times)

    templates_new = np.zeros_like(templates)
    for unit in range(n_units):

        temp_ = templates[unit, :, mcs[unit]]
        f = interp1d(t_range, -temp_, 'cubic')
        shift = find_peak_binary_search(-temp_, f) - np.argmin(temp_)

        vis_chan = np.where(templates[unit].ptp(0) > 1)[0]
        temp_new = np.copy(templates[unit])
        t_range_new = t_range + shift
        for c in vis_chan:
            f = interp1d(t_range, templates[unit,:,c], 'cubic', fill_value='extrapolate')
            temp_new[:, c] = f(t_range_new)
        templates_new[unit] = temp_new

    if fname_out is None:
        fname_out = fname_templates
    np.save(fname_out, templates_new)

    return fname_out

def find_peak_binary_search(obj, func, threshold= 0.0001):
    small, big = np.argsort(obj)[-2:]
    big_val = obj[big]
    small = small
    big = big
    mid = (small+big)/2
    mid_val = func(mid)

    while np.abs(big_val - mid_val) > threshold:
        if mid_val > big_val:
            small = big
            big = mid
            big_val = mid_val

        else:
            small = mid
        mid = (small+big)/2
        mid_val = func(mid)

    return big


text:
from __future__ import absolute_import, unicode_literals, print_function, division

import re
import sublime_plugin
import sublime
from collections import defaultdict
import tempfile
import binascii

try:
    from .sublimerepl import manager, SETTINGS_FILE
except (ImportError, ValueError):
    from sublimerepl import manager, SETTINGS_FILE

def default_sender(repl, text, view=None, repl_view=None):
    if repl.apiv2:
        repl.write(text, location=repl_view.view.size() - len(text))
    else:
        repl.write(text)

    if view is None or not sublime.load_settings(SETTINGS_FILE).get('focus_view_on_transfer'):
        return
    active_window = sublime.active_window()
    active_view = active_window.active_view()
    target_view = repl_view.view
    if target_view == active_view:
        return  #
    active_group = sublime.active_window().active_group()
    if target_view in active_window.views_in_group(active_group):
        return  # same group, dont switch
    active_window.focus_view(target_view)
    active_window.focus_view(view)

"""Senders is a dict of functions used to transfer text to repl as a repl
   specific load_file action"""
SENDERS = defaultdict(lambda: default_sender)

def sender(external_id,):
    def wrap(func):
        SENDERS[external_id] = func
    return wrap

@sender("coffee")
def coffee(repl, text, view=None, repl_view=None):
    """
        use CoffeeScript multiline hack
        http://coffeescript.org/documentation/docs/repl.html
    """
    default_sender(repl, text.replace("\n", u'\uFF00') + "\n", view, repl_view)

@sender("python")
def python_sender(repl, text, view=None, repl_view=None):
    text_wo_encoding = re.sub(
        pattern=r"#.*coding[:=]\s*([-\w.]+)",
        repl="# <SublimeREPL: encoding comment removed>",
        string=text,
        count=1)
    code = binascii.hexlify(text_wo_encoding.encode("utf-8"))
    execute = ''.join([
        'from binascii import unhexlify as __un; exec(compile(__un("',
        str(code.decode('ascii')),
        '").decode("utf-8"), "<string>", "exec"))\n'
    ])
    return default_sender(repl, execute, view, repl_view)

@sender("ruby")
def ruby_sender(repl, text, view=None, repl_view=None):
    code = binascii.b2a_base64(text.encode("utf-8"))
    payload = "begin require 'base64'; eval(Base64.decode64('%s'), binding=TOPLEVEL_BINDING) end\n" % (code.decode("ascii"),)
    return default_sender(repl, payload, view, repl_view)

# custom clojure sender that makes sure that all selections are
# evaluated in the namespace declared by the file they are in
@sender("clojure")
def clojure_sender(repl, text, view, repl_view=None):
    # call (load-string) instead of just writing the string so
    # that syntax errors are caught and thrown back immediately.
    # also, escape backslashes and double-quotes
    text = '(load-string "' + text.strip().replace('\\', r'\\').replace('"', r'\"') + '")'

    # find the first non-commented statement from the start of the file
    namespacedecl = view.find(r"^[^;]*?\(", 0)

    # if it's a namespace declaration, go search for the namespace name
    if namespacedecl and view.scope_name(namespacedecl.end()-1).startswith("source.clojure meta.function.namespace.clojure"):
        namespacedecl = view.extract_scope(namespacedecl.end()-1)

        # we're looking for the first symbol within the declaration that
        # looks like a namespace and isn't metadata, a comment, etc.
        pos = namespacedecl.begin() + 3
        while pos < namespacedecl.end():
            # see http://clojure.org/reader for a description of valid
            # namespace names. the inital } or whitespace make sure we're
            # not matching on keywords etc.
            namespace = view.find(r"[\}\s][A-Za-z\_!\?\*\+\-][\w!\?\*\+\-:]*(\.[\w!\?\*\+\-:]+)*", pos)

            if not namespace:
                # couldn't find the namespace name within the declaration. suspicious.
                break
            elif view.scope_name(namespace.begin() + 1).startswith("source.clojure meta.function.namespace.clojure entity.name.namespace.clojure"):
                # looks alright, we've got our namespace!
                # switch to namespace before executing command

                # we could do this explicitly by calling (ns), (in-ns) etc:
                # text = "(ns " + view.substr(namespace)[1:] + ") " + text
                # but this would not only result in an extra return value
                # printed to the user, the repl would also remain in that
                # namespace after execution, so instead we do the same thing
                # that swank-clojure does:
                text = "(binding [*ns* (or (find-ns '" + view.substr(namespace)[1:] + ") (find-ns 'user))] " + text + ')'
                # i.e. we temporarily switch to the namespace if it has already
                # been created, otherwise we execute it in 'user. the most
                # elegant option for this would probably be:
                # text = "(binding [*ns* (create-ns '" + view.substr(namespace)[1:] + ")] " + text + ')'
                # but this can lead to problems because of newly created
                # namespaces not automatically referring to clojure.core
                # (see https://groups.google.com/forum/?fromgroups=#!topic/clojure/Th-Bqq68hfo)
                break
            else:
                # false alarm (metadata or a comment), keep looking
                pos = namespace.end()
    return default_sender(repl, text + repl.cmd_postfix, view, repl_view)

class ReplViewWrite(sublime_plugin.TextCommand):
    def run(self, edit, external_id, text):
        for rv in manager.find_repl(external_id):
            rv.append_input_text(text)
            break  # send to first repl found
        else:
            sublime.error_message("Cannot find REPL for '{0}'".format(external_id))

class ReplSend(sublime_plugin.TextCommand):
    def run(self, edit, external_id, text, with_auto_postfix=True):
        for rv in manager.find_repl(external_id):
            if with_auto_postfix:
                text += rv.repl.cmd_postfix
            if sublime.load_settings(SETTINGS_FILE).get('show_transferred_text'):
                rv.append_input_text(text)
                rv.adjust_end()
            SENDERS[external_id](rv.repl, text, self.view, rv)
            break
        else:
            sublime.error_message("Cannot find REPL for '{}'".format(external_id))

class ReplTransferCurrent(sublime_plugin.TextCommand):
    def run(self, edit, scope="selection", action="send"):
        text = ""
        if scope == "selection":
            text = self.selected_text()
        elif scope == "lines":
            text = self.selected_lines()
        elif scope == "function":
            text = self.selected_functions()
        elif scope == "block":
            text = self.selected_blocks()
        elif scope == "file":
            text = self.selected_file()
        cmd = "repl_" + action
        self.view.window().run_command(cmd, {"external_id": self.repl_external_id(), "text": text})

    def repl_external_id(self):
        return self.view.scope_name(0).split(" ")[0].split(".", 1)[1]

    def selected_text(self):
        v = self.view
        parts = [v.substr(region) for region in v.sel()]
        return "".join(parts)

    def selected_blocks(self):
        # TODO: Clojure only for now
        v = self.view
        strs = []
        old_sel = list(v.sel())
        v.run_command("expand_selection", {"to": "brackets"})
        v.run_command("expand_selection", {"to": "brackets"})
        for s in v.sel():
            strs.append(v.substr(s))
        v.sel().clear()
        for s in old_sel:
            v.sel().add(s)
        return "\n\n".join(strs)

    def selected_lines(self):
        v = self.view
        parts = []
        for sel in v.sel():
            for line in v.lines(sel):
                parts.append(v.substr(line))
        return "\n".join(parts)

    def selected_file(self):
        v = self.view
        return v.substr(sublime.Region(0, v.size()))


text:
Title: My First Review
Date: 2010-12-03 10:20
Category: Review
Tags: JavaScript, CSS

Following is a review of my favorite mechanical keyboard.


text:
(function( $ ){

	//instantiating the utility library. ignore these two lines for now if you are confused.
	var utility = new Utility,
		collectedArticles,
		mapOptions = {
			center: new google.maps.LatLng(39.997050, -76.354334),
			zoom: 15,
			scrollwheel: false,
			draggable: false
		},
		map = new google.maps.Map( document.getElementById('map-container'), mapOptions );

	//First, we make the map
	// google.maps.event.addDomListener( window, 'load', initializeMap );

	/*
	 * At the very basic level, there are 2 ways to organize your functions
	 *
	 * Method 1: Defining functions as Functions
	 *
	 * Pop Quiz:
	 * What is an invocation?
	 * How do you invoke a function that is defined as a function?
	 * And what is the name of this invocation?
	 *
	 */

	/*
	 * @func loadArticles: loads all the articles from a JSON source.
	 * @param string dataPath: the path to the data source.
	 */
	function loadData( dataPath, callback ){
		//using ajax() from jQuery – aka $.ajax. The dollar sign signifies a jQuery instance/object.
		$.ajax({
			url: dataPath,
			type: 'GET',
			dataType: 'json',
			cache: false,
			success: callback,
		});
	}
	/*
	 * The following function are callback functions used with @func loadData. A callback function is a function that is invoked inside a function. A callback is usually invoked when the origial function is finished doing its job, it is invoked as the last step of the original function.

	 For example, if we use loadData as such: loadData("[my path to data]", loadArticleOnSuccess);, the loadArticleOnSuccess will replace "callback" in the member "success" and become the function to be invoked when the $.ajax() is finished getting data from the path.
	 *
	 */
	 //data is included as parameter because we know that the success member from an $.ajax function will automatically give us the data it found from the source path.
	function loadArticlesOnSuccess( data ){
		//cache the received data into a local variable called collectedArticles so that we dont not have to keep asking the "server" and using http request; let the utility to parse the articles for us, after the parsing is done, the function will return the articles in an array.
		collectedArticles = utility.parseArticle( data );

	}
	function makeMutantMapMarker( data ){
		var collectedMutants =  data.mutants.foundMutants,
			marker = null,
			latLong = null;

		$('.mutant-counter').find('strong').html(data.mutants.mutantCount);

		collectedMutants.forEach(function( e, i ){
			latLong = new google.maps.LatLng(e.lat, e.long);
			marker = new google.maps.Marker({
				position: latLong,
				title: e.title,
				map: map
			});
		});
	}
	/*
	 * @func loadAnArticle: load only one article based on given parameters.
	 * @param number index: the index of the article to be loaded. This index value aligns with what is specified in the JSON.
	 * @param string type: the type of article to laod as.
	 	possible values: trending, featured
	 * @param number trendingIndex: optional, only needed when loading an article as a trending article. This index specifies which trending article image the new article should replace. This index is based on the index of the trending article elements in the DOM.
	 */
	function loadAnArticle( index, type, trendingIndex ){
		var curArticle;
		if( type === 'featured'){
			curArticle = utility.parseItemAsFeatued( collectedArticles[ index ] );
		}
		else if( type === 'trending'){
			curArticle = utility.parseItemAsTrending( collectedArticles[ index ], trendingIndex );
		}
		curArticle.data('cur-article', index );
	}

	/*
	 *
	 * Method 2: Defining as Object Literals
	 *
	 * Pop Quiz:
	 * 1. Can an object literal store other data types?
	 * 2. What are some of the Javascript data types?
	 * 3. Does JS really have data types?
	 * 4. How do you invoke a function stored in anobject literal?
	 * 5. And what kind of invocation is that called?
	 *
	 */
	var userActions = {
		/*
		 * @func launchMenu: opens the mutants menu
		 * @param object event: This is not a param that we pass in manually. The event object will be passed in to this function as a parameter when used with .on() to set up an event.
		 */
		launchMenu: function( event ){
			var theNav = $(event.target).parents('nav');
			if( theNav.hasClass('active') ){
				theNav.removeClass('active');
			} else {
				theNav.addClass('active');
			}
			return false;
		},
		/*
		 * @func swapContent: swapping the content with the featured content when a trending article is clicked.
		 *
		 */
		swapContent: function( event ){
			//if the user click on the image in the .article element, chances are that event.target will be the image, and not the .article element iteself. In which case, we will process "target" at a later point so that we can make sure we are getting .article, and not the image inside it.
			var target = $(event.target),
				currentMainContent = $('.featured-content').data('cur-article'),
				//we are defining triggeredArticle by using an anonymous function.
				clickedIndex = target.index(),
				triggeredArticle = (function(){
					//if the current clicked element does not have any cur-article data, we move up in the DOM to the find the parent that has the class .article, because we know we stored a cur-article data there when we load in the article from the library.
					if( !target.data('cur-article') ){
						//change target back to the .article element
						target = target.parents('.article');
						//also update the index so that it is the index for the .article element, no longer for the image.
						clickedIndex = target.index();
						//the following returns a value back to triggeredArticle. Remember, we are currently in an anonymous funciton that is helping to define triggeredArticle.
						return target.data('cur-article');
					}
				}());
			//using the laodAnArticle function defined before.
			loadAnArticle( triggeredArticle, 'featured' );
			//clickedIndex needs to substract 1 because the index in the article JSON object is not aligned with the index of the  .article elements. Note that the first index in an Array is 0. When $ returns a list of elements, it is stored in an array.
			loadAnArticle( currentMainContent, 'trending', (clickedIndex - 1) );

			return false;
		}
	}

	//Event binding
	/*
	 * Pop Quiz:
	 * 1. Can you name other events?
	 * 2. Other than ways like .click(), what other jQuery methods can you use to bind events? (hint: x2 )
	 * 3. What are the differences between the 3 ways of binding events?
	 *
	 */
	$(document)
		//remember the event parameter, it in here when the "event" is passed into userActions.launchMenu
		.on('click', '.site-menu-click-area', userActions.launchMenu )
		//same here
		.on('click', '.trending-content .article', userActions.swapContent );

	//initialize the page by loading in the articles from our JSON source.
	loadData('data-fixtures/articles.json', loadArticlesOnSuccess);
	loadData('data-fixtures/map.json', makeMutantMapMarker);
	/*
	 * Pop Quiz:
	 * 1. What is a namespace.
	 * 2. Name some of the differences between classical languages and JS.
	 * 3. What is an anonymous function?
	 * 4. What is scope?
	 * 5. What is closure?
	 *
	 */

}( jQuery ));


text:
from __future__ import absolute_import, division, print_function
__metaclass__ = type

import logging
import qb.logging

# Find a Display if possible
try:
    from __main__ import display
except ImportError:
    try:
        from ansible.utils.display import Display
    except ImportError:
        display = None
    else:
        display = Display()

class DisplayHandler(logging.Handler):
    '''
    A handler class that writes messages to Ansible's
    `ansible.utils.display.Display`, which then writes them to the user output.

    Includes static methods that let it act as a sort of a singleton, with
    a single instance created on-demand.
    '''

    # Singleton instance
    _instance = None

    @staticmethod
    def getDisplay():
        '''
        Get the display instance, if we were able to import or create one.

        :rtype:     None
        :return:    No display could be found or created.

        :rtype:     ansible.util.display.Display
        :return:    The display we're using.
        '''
        return display
    # .getDisplay

    @staticmethod
    def getInstance():
        '''
        :rtype:     DisplayHandler
        :return:    The singleton instance.
        '''
        if DisplayHandler._instance is None:
            DisplayHandler._instance = DisplayHandler()
        return DisplayHandler._instance
    # .getInstance

    @staticmethod
    def enable():
        '''
        Enable logging to Ansible's display by sending {.getInstance()} to
        {qb.logging.addHandler()}.

        :raises:
        '''
        instance = DisplayHandler.getInstance()

        if instance.display is None:
            raise RuntimeError("No display available")

        return qb.logging.addHandler(instance)
    # .enable

    def disable():
        '''
        Disable logging to Ansible's display be sending {.getInstance()} to
        {qb.logging.removeHandler()}.
        '''
        return qb.logging.removeHandler(DisplayHandler.getInstance())
    # .disable

    def is_enabled():
        return qb.logging.hasHandler(DisplayHandler.getInstance())
    # .is_enabled

    def __init__(self, display=None):
        logging.Handler.__init__(self)

        if display is None:
            display = DisplayHandler.getDisplay()

        self.display = display
    # #__init__

    def emit(self, record):
        '''
        Overridden to send log records to Ansible's display.
        '''

        if self.display is None:
            # Nothing we can do, drop it
            return

        try:
            self.format(record)

            if record.levelname == 'DEBUG':
                return self.display.verbose(record.message, caplevel=1)

            elif record.levelname == 'INFO':
                return self.display.verbose(record.message, caplevel=0)

            elif record.levelname == 'WARNING':
                self.display.warning(record.message)

            elif record.levelname == 'ERROR':
                self.display.error(record.message)

            elif record.levelname == 'CRITICAL':
                self.display.error("(CRITICAL) {}".format(record.message))

            else:
                pass
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            raise
            # self.handleError(record)
    # #emit


text:
[![Build Status](https://travis-ci.org/xsist10/HaveIBeenPwned.svg?branch=master)](hhttps://travis-ci.org/xsist10/HaveIBeenPwned)

## Install

``` json
{
    "require": {
        "xsist10/haveibeenpwned": "~1.0"
    }
}
```

## Usage

### Create manager instance
``` php
use xsist10\HaveIBeenPwned\HaveIBeenPwned;
use xsist10\HaveIBeenPwned\Adapter\Curl;
use xsist10\HaveIBeenPwned\Adapter\FileGetContents;

// By default the $manager will use a Curl adapter
$manager = new HaveIBeenPwned();

// You can create a new manager with a specified adapter
$manager = new HaveIBeenPwned(new Curl());

// You can also set the adapter after creation
$manager->setAdapter(new FileGetContents());

```

### Check if you've been pwned
``` php
$manager->checkAccount("your_email_address");
```

### Check if your account has been leaked in a paste
``` php
$manager->getPasteAccount("your_email_address");
```

### Check if your password has been leaked before
``` php
// Your password is not sent to the remote API. Only a partial of the SHA1
// value is sent and all matching full SHA1 results are returned and compared.
$numberOfTimesCompromised = $manager->isPasswordCompromised("your_password");
```

### List all breaches that have are on record
``` php
$manager->getBreaches();

$manager->getBreach('specific_breach_by_name');
```

### List the types of data that are covered when describing a leak
``` php
$manager->getDataClasses();
```

## Logger Support

The adapters support [PSR-3 Logger](http://www.php-fig.org/psr/psr-3/). I recommend using [monolog](https://github.com/Seldaek/monolog).

### Install Monolog
```bash
$ composer require monolog/monolog
```

### Use Monolog with HaveIBeenPwned
```php
use xsist10\HaveIBeenPwned\HaveIBeenPwned;
use xsist10\HaveIBeenPwned\Adapter\Curl;

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

$log = new Logger('name');
// Push all logging up to the level of DEBUG to our log file
$log->pushHandler(new StreamHandler('[full log filename]', Logger::DEBUG));

$adapter = new Curl();
$adapter->setLogger($log);
$manager = new HaveIBeenPwned($adapter);

// Calls made to HaveIBeenPwned will be logged to your log file now
```

## Credits

- [Troy Hunt](https://github.com/troyhunt) for creating https://haveibeenpwned.com/
- [Thomas Shone](https://github.com/xsist10)
- [Chung-Sheng, Li](https://github.com/peter279k)

## License

The MIT License (MIT). Please see [License File](https://github.com/xsist10/HaveIBeenPwned/blob/master/LICENSE) for more information.


text:
/* Agar icon reference file */
/* Generated by agarpaint 1.1 */

#include <agar/vg/begin.h>
/* Begin generated block */
__BEGIN_DECLS
extern DECLSPEC AG_StaticIcon vgIconPoints;
extern DECLSPEC AG_StaticIcon vgIconLine;
extern DECLSPEC AG_StaticIcon vgIconCircle;
extern DECLSPEC AG_StaticIcon vgIconBezier;
extern DECLSPEC AG_StaticIcon vgIconBlock;
extern DECLSPEC AG_StaticIcon vgIconText;
extern DECLSPEC AG_StaticIcon vgIconSnapFree;
extern DECLSPEC AG_StaticIcon vgIconSnapRint;
extern DECLSPEC AG_StaticIcon vgIconSnapGrid;
extern DECLSPEC AG_StaticIcon vgIconSnapEndpt;
extern DECLSPEC AG_StaticIcon vgIconSnapEndptDist;
extern DECLSPEC AG_StaticIcon vgIconSnapClosest;
extern DECLSPEC AG_StaticIcon vgIconSnapCenterPt;
extern DECLSPEC AG_StaticIcon vgIconSnapMiddlePt;
extern DECLSPEC AG_StaticIcon vgIconSnapIntsectAuto;
extern DECLSPEC AG_StaticIcon vgIconSnapIntsectManual;
extern DECLSPEC AG_StaticIcon vgIconPolygon;
extern DECLSPEC AG_StaticIcon vgIconDrawing;
extern DECLSPEC AG_StaticIcon vgIconProximity;
extern DECLSPEC AG_StaticIcon vgIconSelectArrow;
__END_DECLS
/* Close generated block */
#include <agar/vg/close.h>


text:
var render = require( ".." );
var getContent = require( "./helper" ).getContent;

describe( "Testing fixtures", function(){

  it( "simple", function(){
    var content = getContent( "simple" );
    var output = render( content );
  });

});


text:
require 'smartcard'

class Card
  def initialize(name:)
    @name = name
  end

  def tap
    Context.tap do |context|
      begin
        card = context.card(@name, :shared)
        yield card
      ensure
        card.disconnect unless card.nil?
      end
    end
  end

  class Context
    def self.tap
      context = Smartcard::PCSC::Context.new
      yield context
    ensure
      context.release
    end
  end
end


text:
package attributes

import (
	"encoding/json"
)

type BoolValue struct {
	Value    *bool
	Provided bool
}

func (bv *BoolValue) MarshalJSON() ([]byte, error) {
	return json.Marshal(bv.Value)
}
func (bv *BoolValue) UnmarshalJSON(data []byte) error {
	bv.Provided = true

	if string(data) == "null" {
		return nil
	}

	var val bool
	if err := json.Unmarshal(data, &val); err != nil {
		return err
	}
	bv.Value = &val
	return nil
}
func (bv BoolValue) Equal(obv BoolValue) bool {
	if bv.Value == nil {
		return (obv.Value == nil)
	} else if obv.Value == nil {
		return false
	}
	return (*bv.Value == *obv.Value)
}

func AssertBool(val interface{}) BoolValue {
	bVal, ok := val.(BoolValue)
	if !ok {
		plainVal, ok := val.(**bool)
		if !ok {
			panic("Bad boolean value")
		}
		return BoolValue{
			Value:    *plainVal,
			Provided: true,
		}
	}
	return bVal
}


text:
{{atividade.Nome}}

	  <svg>
	  <use xlink:href="#atividade" />
	  </svg>

{{membro.Nome}}

{{membro.printRegistros()}}

	    <svg class="icon" ng-if="membro.Recurso.Comentarios.length">
	    <use xlink:href="#com-comentarios" />
	    </svg>

	    <svg class="icon" ng-if="!membro.Recurso.Comentarios.length">
	    <use xlink:href="#sem-comentarios" />
	    </svg>

	  <svg>
	  <use xlink:href="#atividade" />
	  </svg>

{{membro.Nome}}

{{membro.Atividade.Nome}} • {{membro.Atividade.Funcao}}

	    <svg class="icon" ng-if="membro.Recurso.Comentarios.length">
	    <use xlink:href="#com-comentarios" />
	    </svg>

	    <svg class="icon" ng-if="!membro.Recurso.Comentarios.length">
	    <use xlink:href="#sem-comentarios" />
	    </svg>

  <button type="button"
	  class="btn btn-cancel hidden"></button>

  <button class="btn btn-ok"
	  ng-click="recursos.openModal()"
	  ng-disabled="buttons.ok.disabled"
	  type="button">Finalizar</button>


text:
#import <UIKit/UIKit.h>

@class ARDVideoCallViewController;
@protocol ARDVideoCallViewControllerDelegate <NSObject>

- (void)viewControllerDidFinish:(ARDVideoCallViewController *)viewController;

@end

@interface ARDVideoCallViewController : UIViewController

@property(nonatomic, weak) id<ARDVideoCallViewControllerDelegate> delegate;

- (instancetype)initForRoom:(NSString *)room
                 isLoopback:(BOOL)isLoopback
                isAudioOnly:(BOOL)isAudioOnly
          shouldMakeAecDump:(BOOL)shouldMakeAecDump
      shouldUseLevelControl:(BOOL)shouldUseLevelControl
                   delegate:(id<ARDVideoCallViewControllerDelegate>)delegate;

@end


text:
(function(){
    'use strict';

    angular
        .module('openracer.events.manager', [
            'ngRoute',
            'mgcrea.ngStrap'
        ])
        .config(Config);

    Config.$inject = [ '$routeProvider' ];
    function Config($routeProvider) {
        $routeProvider
            .when('/events/:eventId/manage', {
                templateUrl: '/app/events/manager/manager.tpl.html',
                controller: 'EventManager',
                controllerAs: 'manager'
            });
    }
})();


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<grid xsi:schemaLocation="http://isis.apache.org/applib/layout/component http://isis.apache.org/applib/layout/component/component.xsd http://isis.apache.org/applib/layout/grid/bootstrap3 http://isis.apache.org/applib/layout/grid/bootstrap3/bootstrap3.xsd" xmlns="http://isis.apache.org/applib/layout/grid/bootstrap3" xmlns:ns2="http://isis.apache.org/applib/layout/component" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <row>
        <col span="12" unreferencedActions="true">
            <ns2:domainObject/>
            <ns2:action id="recentChanges"/>
            <ns2:action id="downloadLayoutXml"/>
            <ns2:action id="downloadJdoMetadata"/>
            <ns2:action id="links"/>
            <ns2:action id="remove"/>
        </col>
    </row>
    <row>
        <col span="4">
            <ns2:fieldSet name="General" id="general" unreferencedProperties="true">
                <ns2:property id="datanucleusVersionLong"/>
                <ns2:property id="versionSequence"/>
                <ns2:property id="financialAccount"/>
                <ns2:property id="fixedAsset"/>
                <ns2:property id="datanucleusId"/>
                <ns2:property id="datanucleusVersionTimestamp"/>
                <ns2:property id="id"/>
                <ns2:property id="applicationTenancy"/>
            </ns2:fieldSet>
        </col>
        <col span="8" unreferencedCollections="true"/>
    </row>
</grid>


text:
hello-design-pattern
====================

Hello world using all 23 kinds of GoF design patterns.

```java
public class Main {

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        //hello=interjection
        //world=object

        System.out.println("We are creational patterns!");

        System.out.println("1. Abstract Factory: ");

        SplitHelloWorldFactory abstractFactory = AbstractFactory.select(AbstractFactory.Type.DesignPattern);
        HelloWorld abstractFactoryHelloWorld = new SplitHelloWorld(abstractFactory.createHelloWorldInterjection(),
                abstractFactory.createHelloWorldObject());
        System.out.println(abstractFactoryHelloWorld.helloWorld());

        System.out.println("2. Builder: ");
        HelloWorld builderHelloWorld = HelloWorldBuilder.builder()
                .interjection("Hello")
                .object("Builder").getHelloWorld();
        System.out.println(builderHelloWorld.helloWorld());

        System.out.println("3. Factory Method: ");
        /**
         * Difference between "abstract factory" and "factory method" is the abstracting point:
         *  1. Abstracting point of abstract factory is factory.
         *  2. Abstracting point of factory method is generated object.
         */
        FactoryMethodHelloWorldFactory factoryMethodHelloWorldFactory = new FactoryMethodHelloWorldFactory();
        HelloWorld factoryMethodHelloWorld = factoryMethodHelloWorldFactory.createHelloWorld();
        System.out.println(factoryMethodHelloWorld.helloWorld());

        System.out.println("4. Prototype: ");
        HelloWorld prototypeHelloWorld = HelloWorldPrototype.PROTOTYPE.clone();
        System.out.println(prototypeHelloWorld.helloWorld());

        System.out.println("5. Singleton: ");
        HelloWorld singletonHelloWorld = HelloWorldSingleton.instance();
        System.out.println(singletonHelloWorld.helloWorld());

        System.out.println("====================================");
        System.out.println("We are structural patterns!");

        System.out.println("6. Adapter: ");
        HelloWorld adapterHelloWorld = new HelloWorldAdapter(new HelloAdapterDesignPattern());
        System.out.println(adapterHelloWorld.helloWorld());

        System.out.println("7. Bridge: ");
        HelloWorld bridgeHelloWorld = new HelloWorldBridge(new DesignPatternWorldImpl());
        //leave bridgeHelloWorld' output to compositeHelloWorld

        System.out.println("8. Composite: ");
        HelloWorld compositeHelloWorld = new CompositeHelloWorld(bridgeHelloWorld, new CompositeHelloWorld.DefaultHelloWorld());
        System.out.println(compositeHelloWorld.helloWorld());

        System.out.println("9. Decorator: ");
        HelloWorldDecorator decoratorHelloWorld = new HelloWorldDecorator(new HelloWorldDecorator.DefaultHelloWorld());
        System.out.println(decoratorHelloWorld.helloDecorator());

        System.out.println("10. Facade: ");
        HelloWorld facadeHelloWorld = HelloWorldFacade.instance().facadeHelloWorld();
        System.out.println(facadeHelloWorld.helloWorld());

        System.out.println("11. Flyweight: ");
        HelloWorld flyWeightHelloWorld = HelloWorldFlyWeightFactory.instance().createHelloWorld("Hello Flyweight!");
        System.out.println(flyWeightHelloWorld.helloWorld());

        System.out.println("12. Proxy: ");
        HelloWorld proxyHelloWorld = new HelloWorldProxy(new HelloWorldProxy.DefaultHelloWorld());
        System.out.println(proxyHelloWorld.helloWorld());

        System.out.println("====================================");
        System.out.println("We are behavioral patterns!");

        System.out.println("13. Chain of Responsibility: ");
        HelloWorldHandler helloWorldChainOfResponsibility = new HelloWorldInterjectionHandler().setNext(new HelloWorldObjectHandler());
        System.out.println(helloWorldChainOfResponsibility.helloWorld());

        System.out.println("14. Command: ");
        Command helloWorldCommand = new HelloWorldPrintCommand();
        helloWorldCommand.execute();

        System.out.println("15. Interpreter: ");
        HelloWorldInterpreter helloWorldInterpreter = new HelloWorldInterpreter();
        helloWorldInterpreter.interpret("println('Hello Interpreter!')");

        System.out.println("16. Iterator: ");
        HelloWorldCharacterIterator helloWorldCharacterIterator = new HelloWorldCharacterIterator("Hello Iterator!".toCharArray());
        while (helloWorldCharacterIterator.hasNext()) {
            System.out.print(helloWorldCharacterIterator.next());
        }
        System.out.println();

        System.out.println("17. Mediator: ");
        HelloWorldInterjection helloWorldInterjection = new HelloWorldInterjection();
        HelloWorldObject helloWorldObject = new HelloWorldObject();
        HelloWorldMediator helloWorldMediator = new HelloWorldMediator(helloWorldInterjection, helloWorldObject);
        helloWorldInterjection.setHelloWorldMediator(helloWorldMediator);
        helloWorldObject.setHelloWorldMediator(helloWorldMediator);
        System.out.println(helloWorldObject.helloWorld());

        System.out.println("18. Memento: ");
        HelloWorldMementoOriginator helloWorldMementoOriginator = new HelloWorldMementoOriginator();
        HelloWorldMementoOriginator.Memento memento = helloWorldMementoOriginator.set("Hello Memento!").saveToMemento();
        helloWorldMementoOriginator.set("Hello Whatever!");
        helloWorldMementoOriginator.restoreFromMemento(memento);
        System.out.println(helloWorldMementoOriginator.helloWorld());

        System.out.println("19. Observer: ");
        Subject subject = new Subject().attach(new HelloWorldObserver());
        subject.notifyObservers();

        System.out.println("20. State: ");
        HelloWorldStateContext helloWorldStateContext = new HelloWorldStateContext();
        HelloWorld stateHelloWorld = helloWorldStateContext.appendWord("Hello").appendWord("State");
        System.out.println(stateHelloWorld.helloWorld());

        System.out.println("21. Strategy: ");
        HelloWorldStrategyContext helloWorldStrategyContext = new HelloWorldStrategyContext(new DesignPatternHelloWorldStrategy());
        System.out.println(helloWorldStrategyContext.helloWorld());

        System.out.println("22. Template Method: ");
        HelloWorld templateMethodHelloWorld = new TemplateMethodHelloWorld();
        System.out.println(templateMethodHelloWorld.helloWorld());

        System.out.println("23. Visitor: ");
        HelloWorldCharacterElements helloWorldCharacterElements = new HelloWorldCharacterElements("Hello Visitor!".toCharArray());
        HelloWorldCharacterVisitor helloWorldCharacterVisitor = new HelloWorldCharacterVisitor();
        helloWorldCharacterElements.accept(helloWorldCharacterVisitor);
        System.out.println(helloWorldCharacterVisitor.helloWorld());

    }
}
```


text:
module Broach
  # Makes a very simple attribute driven model from the class when included.
  module Attributes
    def initialize(attributes)
      @attributes = attributes
    end

    def id; @attributes['id']; end

    def method_missing(method, *arguments, &block)
      if key = method.to_s and @attributes.has_key?(key)
        @attributes[key]
      else
        super
      end
    end
  end
end


text:
<?php

namespace Mickeyhead7\Api\Filters;

class Float implements FilterInterface
{

    /**
     * Sanitize a value
     *
     * @param $value
     * @param array $config
     * @return int
     */
    public function sanitize($value, Array $config = [])
    {
        $value = filter_var($value, FILTER_SANITIZE_NUMBER_FLOAT);

        // Minimum
        if (isset($config['min']) && $value < (int) $config['min']) {
            $value = (int) $config['min'];
        }

        // Maximum
        if (isset($config['max']) && $value > (int) $config['max']) {
            $value = (int) $config['max'];
        }

        return (float) $value;
    }

    /**
     * Validate a value
     *
     * @param $value
     * @param array $config
     * @return bool|mixed
     */
    public function validate($value, Array $config)
    {
        $result = filter_var($value, FILTER_VALIDATE_FLOAT);

        // Minimum
        if (isset($config['min']) && $value < (int) $config['min']) {
            return false;
        }

        // Maximum
        if (isset($config['max']) && $value > (int) $config['max']) {
            return false;
        }

        return $result;
    }

}


text:
var module = angular.module('ToerhApp.services');

module.service('SessionService', function($window) {
	this.isAuthenticated = function() {
		return ($window.sessionStorage.hasOwnProperty('token')) ? true : false;
	};

    this.destroySession = function() {
        delete $window.sessionStorage.token;
        delete $window.sessionStorage.userid;
    };
});


text:
<!DOCTYPE html>
<html>
<body>
    <script src='../resources/reflected-xss-and-xss-protection.js'></script>
    <script>testMixedHeader('unset', 'allow');</script>
</body>
</html>


text:
kpt fn eval --image-pull-policy never --image gcr.io/kpt-fn/render-helm-chart:unstable \
--mount type=bind,src="$(pwd)",dst=/tmp/charts -- \
name=helloworld-chart \
releaseName=test \
valuesFile=/tmp/charts/helloworld-values/values.yaml \
skipTests=true


text:
<!DOCTYPE html>

{{!-- Meta Head --}}
{{ partial template="components/modules/MetaHead/metahead" }}

	{{!-- Body --}}

	{{!-- Off-Screen --}}

		{{ module template="components/modules/Nav" skin="mobile" }}
		{{ module template="components/modules/LanguageSwitch" skin="mobile"}}
		{{ module template="components/modules/Search" skin="mobile"}}

	{{!-- Page --}}

		{{!-- Header --}}

				{{ module template="components/modules/Logo"}}

						{{ module template="components/modules/Search" }}

						{{ module template="components/modules/LanguageSwitch" }}

						{{ placeholder key="nav" }}

		{{!-- Content --}}

			{{!-- Stage --}}
			{{ placeholder key="stage" }}

					{{ placeholder key="main" }}

		{{!-- Footer --}}

				{{ placeholder key="footer" }}

					{{ placeholder key="footer-info" }}

		<button class="e-btn btn-back-top js-btn-back-top"></button>

	{{!-- Meta Foot --}}
	{{ partial template="components/modules/MetaFoot/metafoot" }}


text:
package endpoint

import (
	"github.com/brutella/hc/hap"
	"github.com/brutella/hc/log"

	"io/ioutil"
	"net/http"
	"sync"
)

// Accessories handles the /accessories endpoint and returns all accessories as JSON
//
// This endpoint is not session based and the same for all connections because
// the encryption/decryption is handled by the connection automatically.
type Accessories struct {
	http.Handler

	controller hap.AccessoriesHandler
	mutex      *sync.Mutex
}

// NewAccessories returns a new handler for accessories endpoint
func NewAccessories(c hap.AccessoriesHandler, mutex *sync.Mutex) *Accessories {
	handler := Accessories{
		controller: c,
		mutex:      mutex,
	}

	return &handler
}

func (handler *Accessories) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	log.Debug.Printf("%v GET /accessories", request.RemoteAddr)
	response.Header().Set("Content-Type", hap.HTTPContentTypeHAPJson)

	handler.mutex.Lock()
	res, err := handler.controller.HandleGetAccessories(request.Body)
	handler.mutex.Unlock()

	if err != nil {
		log.Info.Panic(err)
		response.WriteHeader(http.StatusInternalServerError)
	} else {
		// Write the data in chunks of 2048 bytes
		// http.ResponseWriter should do this already, but crashes because of an unkown reason
		wr := hap.NewChunkedWriter(response, 2048)
		b, _ := ioutil.ReadAll(res)
		log.Debug.Println(string(b))
		_, err := wr.Write(b)
		if err != nil {
			log.Info.Panic(err)
		}
	}
}


text:
"""
    Tests the h5py.File object.
"""

from __future__ import absolute_import

import threading
import h5py

from ..common import ut, TestCase

class TestErrorPrinting(TestCase):

    """
        Verify the error printing is squashed in all threads.
    """

    def test_printing(self):
        """ No console messages should be shown from membership tests """
        # Unfortunately we can't have this test assert anything, as
        # HDF5 writes directly to stderr.  But it will show up in the
        # console output.

        import threading

        def test():
            with h5py.File(self.mktemp(), 'w') as newfile:
                try:
                    doesnt_exist = newfile['doesnt_exist'].value
                except KeyError:
                    pass

        th = threading.Thread(target=test)
        th.start()
        th.join()

    def test_attr_printing(self):
        """ No console messages should be shown for non-existing attributes """

        def test():

            with h5py.File(self.mktemp(), 'w') as newfile:
                newfile['newdata'] = [1,2,3]
                try:
                    nonexistent_attr = newfile['newdata'].attrs['nonexistent_attr']
                except KeyError:
                    pass

        th = threading.Thread(target=test)
        th.start()
        th.join()


text:
from sqlalchemy import *
from sqlalchemy.databases import informix
from test.lib import *

class CompileTest(fixtures.TestBase, AssertsCompiledSQL):

    __dialect__ = informix.InformixDialect()

    def test_statements(self):
        meta = MetaData()
        t1 = Table('t1', meta, Column('col1', Integer,
                   primary_key=True), Column('col2', String(50)))
        t2 = Table('t2', meta, Column('col1', Integer,
                   primary_key=True), Column('col2', String(50)),
                   Column('col3', Integer, ForeignKey('t1.col1')))
        self.assert_compile(t1.select(),
                            'SELECT t1.col1, t1.col2 FROM t1')
        self.assert_compile(select([t1, t2]).select_from(t1.join(t2)),
                            'SELECT t1.col1, t1.col2, t2.col1, '
                            't2.col2, t2.col3 FROM t1 JOIN t2 ON '
                            't1.col1 = t2.col3')
        self.assert_compile(t1.update().values({t1.c.col1: t1.c.col1
                            + 1}), 'UPDATE t1 SET col1=(t1.col1 + ?)')


text:
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const experimental_utils_1 = require("@typescript-eslint/experimental-utils");
const util = __importStar(require("../util"));
exports.default = util.createRule({
    name: 'no-namespace',
    meta: {
        type: 'suggestion',
        docs: {
            description: 'Disallow the use of custom TypeScript modules and namespaces',
            category: 'Best Practices',
            recommended: 'error',
        },
        messages: {
            moduleSyntaxIsPreferred: 'ES2015 module syntax is preferred over custom TypeScript modules and namespaces.',
        },
        schema: [
            {
                type: 'object',
                properties: {
                    allowDeclarations: {
                        type: 'boolean',
                    },
                    allowDefinitionFiles: {
                        type: 'boolean',
                    },
                },
                additionalProperties: false,
            },
        ],
    },
    defaultOptions: [
        {
            allowDeclarations: false,
            allowDefinitionFiles: true,
        },
    ],
    create(context, [{ allowDeclarations, allowDefinitionFiles }]) {
        const filename = context.getFilename();
        function isDeclaration(node) {
            var _a;
            return (node.declare === true ||
                (((_a = node.parent.parent) === null || _a === void 0 ? void 0 : _a.type) === experimental_utils_1.AST_NODE_TYPES.TSModuleDeclaration &&
                    isDeclaration(node.parent.parent)));
        }
        return {
            "TSModuleDeclaration[global!=true][id.type='Identifier']"(node) {
                if ((node.parent &&
                    node.parent.type === experimental_utils_1.AST_NODE_TYPES.TSModuleDeclaration) ||
                    (allowDefinitionFiles && util.isDefinitionFile(filename)) ||
                    (allowDeclarations && isDeclaration(node))) {
                    return;
                }
                context.report({
                    node,
                    messageId: 'moduleSyntaxIsPreferred',
                });
            },
        };
    },
});
//# sourceMappingURL=no-namespace.js.map


text:
import 'regenerator-runtime/runtime'
import Vue from 'vue'
import VueMaterial from 'src/material'
import 'jest-localstorage-mock'

Vue.config.productionTip = false
Vue.config.devtools = false
Vue.use(VueMaterial)

Vue.component('transition', {
  render (createElement) {
    const defaultSlot = this.$slots.default

    if (defaultSlot) {
      return defaultSlot[0] && defaultSlot[0]
    }
  }
})

function createAppEl () {
  const app = document.createElement('div')

  app.id = 'app'

  document.body.appendChild(app)
}

createAppEl()

process.on('unhandledRejection', () => {
})