text:
var assert = require('assert'),
    sinon = require('sinon'),
    express = require('express'),
    request = require('supertest'),
    nock   = require('nock'),
    Singleton = require('../lib/honeybadger');

describe('Express Middleware', function () {
  let subject, client_mock, client;
  const error = new Error('Badgers!');

  beforeEach(function() {
    client = Singleton.factory({ apiKey: 'fake api key' });
    subject = client.errorHandler;
    client_mock = sinon.mock(client);
  });

  it('is sane', function(done) {
    const app = express();

    app.get('/user', function(req, res) {
      res.status(200).json({ name: 'john' });
    });

    request(app)
      .get('/user')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200, done);
  });

  it('reports the error to Honeybadger and calls next error handler', function(done) {
    const app = express();
    const expected = sinon.spy();

    app.use(client.requestHandler);

    app.get('/', function(req, res) {
      throw(error);
    });

    app.use(subject);

    app.use(function(err, req, res, next) {
      expected();
      next();
    });

    client_mock.expects('notify').once().withArgs(error);

    request(app)
      .get('/')
      .expect(500, function() {
        client_mock.verify();
        assert(expected.calledOnce);
        done();
    });
  });

  it('reports async errors to Honeybadger and calls next error handler', function(done) {
    const app = express();
    const expected = sinon.spy();

    app.use(client.requestHandler);

    app.get('/', function(req, res) {
      setTimeout(function asyncThrow() {
        throw(error);
      }, 0);
    });

    app.use(subject);

    app.use(function(err, req, res, next) {
      expected();
      next();
    });

    client_mock.expects('notify').once().withArgs(error);

    request(app)
      .get('/')
      .expect(500, function() {
        client_mock.verify();
        assert(expected.calledOnce);
        done();
      });
  });

  it('provides a noop metricsHandler', function(done) {
    const app = express();
    const expected = sinon.spy();

    app.use(client.metricsHandler);
    app.use(function(req, res, next) {
      expected();
      next();
    });

    request(app)
      .get('/')
      .expect(200, function() {
        assert(expected.calledOnce);
        done();
      });
  });
});

describe('Lambda Handler', function () {
  var Honeybadger = require('../lib/honeybadger').factory({ apiKey: 'fake api key' });

  context('with arguments', function() {
    var handlerFunc;

    beforeEach(function(done) {
      handlerFunc = sinon.spy();
      var handler = Honeybadger.lambdaHandler(handlerFunc);
      handler(1, 2, 3);
      process.nextTick(function() {
        done();
      });
    });

    it('calls original handler with arguments', function() {
      assert(handlerFunc.calledWith(1, 2, 3));
    });
  });

  context('async handlers', function() {
    it('reports errors to Honeybadger', function(done) {
      nock.cleanAll();
      const api = nock("https://api.honeybadger.io")
        .post("/v1/notices")
        .reply(201, '{"id":"1a327bf6-e17a-40c1-ad79-404ea1489c7a"}')
      const callback = function(err) {
        api.done();
        done();
      };

      var handler = Honeybadger.lambdaHandler(async function(event) {
        throw new Error("Badgers!");
      });

      handler({}, {}, callback);
    });

    it('reports async errors to Honeybadger', function(done) {
      nock.cleanAll();
      const api = nock("https://api.honeybadger.io")
        .post("/v1/notices")
        .reply(201, '{"id":"1a327bf6-e17a-40c1-ad79-404ea1489c7a"}')
      const callback = function(err) {
        api.done();
        done();
      };

      var handler = Honeybadger.lambdaHandler(async function(event) {
        setTimeout(function() {
          throw new Error("Badgers!");
        }, 0);
      });

      handler({}, {}, callback);
    });
  });

  context('non-async handlers', function() {
    it('reports errors to Honeybadger', function(done) {
      nock.cleanAll();
      const api = nock("https://api.honeybadger.io")
        .post("/v1/notices")
        .reply(201, '{"id":"1a327bf6-e17a-40c1-ad79-404ea1489c7a"}')
      const callback = function(err) {
        api.done();
        done();
      };

      var handler = Honeybadger.lambdaHandler(function(_event, _context, _callback) {
        throw new Error("Badgers!");
      });

      handler({}, {}, callback);
    });

    it('reports async errors to Honeybadger', function(done) {
      nock.cleanAll();
      const api = nock("https://api.honeybadger.io")
        .post("/v1/notices")
        .reply(201, '{"id":"1a327bf6-e17a-40c1-ad79-404ea1489c7a"}')
      const callback = function(err) {
        api.done();
        done();
      };

      var handler = Honeybadger.lambdaHandler(function(_event, _context, _callback) {
        setTimeout(function() {
          throw new Error("Badgers!");
        }, 0);
      });

      handler({}, {}, callback);
    });
  });
});


text:
from nameparser import HumanName
import codecs
import textwrap

authors = []

with codecs.open('authors.csv', 'r', encoding='utf-8') as namefile:
    for line in namefile:
        name, address = line.split(',')
        authors.append((HumanName(name), address))

authors = sorted(authors, key=lambda author: author[0].last)
authors.insert(0, (HumanName("Daniel Standage"), "daniel.standage@gmail.com"))
authors.append((HumanName("C. Titus Brown"), "titus@idyll.org"))

# print(authors)

bibtex = '   author = \"'

for tup in authors:
    name = tup[0]
    name.string_format = "{last}, {first} {middle} and"
    bibtex += str(name) + " "

bibtex = bibtex[:-5] + '"'  # remove last 'and' and close the quote

print('  @article{khmer2015,')
for line in textwrap.wrap(str(bibtex), 77):
    print('  ' + line)

print(
    '''     title = "The khmer software package: enabling efficient nucleotide
  sequence analysis",
     year = "2015",
     month = "08",
     publisher = "F1000",
     url = "https://doi.org/10.12688/f1000research.6924.1"
  }''')

doclist = u':Authors: '

for tup in authors:
    name = tup[0]
    name.string_format = "{first} {middle} {last}"
    doclist += str(name) + ", "

doclist = doclist[:-2]

for line in textwrap.wrap(str(doclist), 71):
    print('        ' + line)

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Oro\Bundle\AttachmentBundle\DependencyInjection;

use Oro\Bundle\AttachmentBundle\Tools\MimeTypesConverter;
use Oro\Bundle\ConfigBundle\DependencyInjection\SettingsBuilder;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

/**
 * Configuration class for OroAttachmentBundle.
 */
class Configuration implements ConfigurationInterface
{
    /**
     * Maximum upload file size default value.
     */
    private const MAX_FILESIZE_MB = 10;

    /**
     * Bytes in one MB. Used to calculate exact bytes in certain MB amount.
     */
    public const BYTES_MULTIPLIER = 1048576;

    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('oro_attachment');
        $rootNode = $treeBuilder->getRootNode();
        $rootNode
            ->children()
                ->booleanNode('debug_images')
                    ->defaultTrue()
                ->end()
                ->integerNode('maxsize')
                    ->min(1)
                    ->defaultValue(self::MAX_FILESIZE_MB)
                ->end()
                ->arrayNode('upload_file_mime_types')
                    ->prototype('scalar')
                    ->end()
                ->end()
                ->arrayNode('upload_image_mime_types')
                    ->prototype('scalar')
                    ->end()
                ->end()
            ->end();

        SettingsBuilder::append(
            $rootNode,
            [
                'maxsize' => ['value' => self::MAX_FILESIZE_MB],
                'upload_file_mime_types' => ['value' => null],
                'upload_image_mime_types' => ['value' => null]
            ]
        );

        $rootNode
            ->validate()
                ->always(function ($v) {
                    if (null === $v['settings']['upload_file_mime_types']['value']) {
                        $v['settings']['upload_file_mime_types']['value'] = MimeTypesConverter::convertToString(
                            $v['upload_file_mime_types']
                        );
                    }
                    if (null === $v['settings']['upload_image_mime_types']['value']) {
                        $v['settings']['upload_image_mime_types']['value'] = MimeTypesConverter::convertToString(
                            $v['upload_image_mime_types']
                        );
                    }

                    return $v;
                })
            ->end();

        return $treeBuilder;
    }
}


text:
dojo.provide("dojox.form.Uploader");
dojo.experimental("dojox.form.Uploader");
dojo.require("dojox.form.uploader.Base");
dojo.require("dijit.form.Button");

	//
	// TODO:
	//		i18n
	//		label via innerHTML
	//		Doc and or test what can be extended.
	//		Doc custom file events
	//		Use new FileReader() for thumbnails
	//		flashFieldName should default to Flash
	//		get('value'); and set warning
	//

dojo.declare("dojox.form.Uploader", [dojox.form.uploader.Base], {
	//
	// Version: 1.6
	//
	// summary:
	//		A widget that creates a stylable file-input button, with optional multi-file selection,
	//		using only HTML elements. Non-HTML5 browsers have fallback options of Flash or an iframe.
	//
	//	description:
	//		A bare-bones, stylable file-input button, with optional multi-file selection. The list
	//		of files is not displayed, that is for you to handle by connecting to the onChange
	//		event, or use the dojox.form.uploader.FileList.
	//
	//		Uploader without plugins does not have any ability to upload - it is for use in forms
	//		where you handle the upload either by a standard POST or with Ajax using an iFrame. This
	//		class is for convenience of multiple files only. No progress events are available.
	//
	//		If the browser supports a file-input with the "multiple" attribute, that will be used.
	//		If the browser does not support "multiple" (ergo, IE) multiple inputs are used,
	//		one for each selection.
	//
	//
	//	uploadOnSelect: Boolean
	//		If true, uploads imediately after a file has been selected. If false,
	//		waits for upload() to be called.
	uploadOnSelect:false,
	//	tabIndex: Number|String
	//		The tab order in the DOM.
	tabIndex:0,
	//	multiple: Boolean
	//		If true and flash mode, multiple files may be selected from the dialog.
	multiple:false,
	//
	//	label: String
	//		The text used in the button that when clicked, opens a system Browse Dialog.
	label:"Upload...",
	//
	// url: String
	//		The url targeted for upload. An absolute URL is preferred. Relative URLs are
	//		changed to absolute.
	url:"",
	//
	//	name: String
	//		The name attribute needs to end with square brackets: [] as this is the standard way
	//		of handling an attribute "array". This requires a slightly different technique on the
	//		server.
	name:"uploadedfile",
	//
	//	flashFieldName: String
	//		If set, this will be the name of the field of the flash uploaded files that the server
	//		is expecting. If not set, "Flash" is appended to the "name" property.
	flashFieldName:"",
	//
	//	uploadType: String [readonly]
	//		The type of uploader being used. As an alternative to determining the upload type on the
	//		server based on the fieldName, this property could be sent to the server to help
	//		determine what type of parsing should be used.
	uploadType:"form",
	//
	_nameIndex:0,
	widgetsInTemplate:true,
	templateString:'

${label}

',

	postMixInProperties: function(){
		this._inputs = [];
		this._getButtonStyle(this.srcNodeRef);
		this.inherited(arguments);
	},
	postCreate: function(){
		var restore = false;
		var parent = this.domNode.parentNode;
		var position = this._getNodePosition(this.domNode);
		if(!this.btnSize.w || !this.btnSize.h) {
			dojo.body().appendChild(this.domNode);
			this._getButtonStyle(this.domNode);
			restore = true;
		}
		this._setButtonStyle();
		if(restore){
			dojo.place(this.domNode, position.node, position.pos)
		}
		this.inherited(arguments);
	},

	/*************************
	 *	   Public Events	 *
	 *************************/

	onChange: function(/* Array */fileArray){
		//	summary:
		// 		stub to connect
		// 		Fires when files are selected
		// 		Event is an array of last files selected
	},

	onBegin: function(/* Array */dataArray){
		// summary:
		// 		Fires when upload begins
	},

	onProgress: function(/* Object */customEvent){
		// summary:
		// 		Stub to connect
		// 		Fires on upload progress. Event is a normalized object of common properties
		// 		from HTML5 uploaders and the Flash uploader. Will not fire for IFrame.
		// customEvent:
		// 		bytesLoaded: Number
		// 			Amount of bytes uploaded so far of entire payload (all files)
		//		bytesTotal: Number
		//			Amount of bytes of entire payload (all files)
		//		type: String
		//			Type of event (progress or load)
		//		timeStamp: Number
		//			Timestamp of when event occurred
	},

	onComplete: function(/* Object */customEvent){
		// summary:
		// 		stub to connect
		// 		Fires when all files have uploaded
		// 		Event is an array of all files
		this.reset();
	},

	onCancel: function(){
		// summary:
		// 		Stub to connect
		// 		Fires when dialog box has been closed
		//		without a file selection
	},

	onAbort: function(){
		// summary:
		// 		Stub to connect
		// 		Fires when upload in progress was canceled
	},

	onError: function(/* Object or String */evtObject){
		// summary:
		//		Fires on errors
		//
		//FIXME: Unsure of a standard form of error events
	},

	/*************************
	 *	   Public Methods	 *
	 *************************/

	upload: function(/*Object ? */formData){
		// summary:
		// 		When called, begins file upload. Only supported with plugins.
	},

	submit: function(/* form Node ? */form){
		// summary:
		//		If Uploader is in a form, and other data should be sent along with the files, use
		//		this instead of form submit. Only supported with plugins.
	},

	reset: function(){
		// summary
		// 		Resets entire input, clearing all files.
		// 		NOTE:
		// 		Removing individual files is not yet supported, because the HTML5 uploaders can't
		// 		be edited.
		// 		TODO:
		// 		Add this ability by effectively, not uploading them
		//
		this._disconnectButton();
		dojo.forEach(this._inputs, dojo.destroy, dojo);
		this._inputs = [];
		this._nameIndex = 0;
		this._createInput();
	},

	getFileList: function(){
		// summary:
		// 		Returns a list of selected files.
		//
		var fileArray = [];
		if(this.supports("multiple")){
			dojo.forEach(this.inputNode.files, function(f, i){
				fileArray.push({
					index:i,
					name:f.name,
					size:f.size,
					type:f.type
				});
			}, this);
		}else{
			dojo.forEach(this._inputs, function(n, i){
				fileArray.push({
					index:i,
					name:n.value.substring(n.value.lastIndexOf("\\")+1),
					size:0,
					type:n.value.substring(n.value.lastIndexOf(".")+1)
				});
			}, this)

		}
		return fileArray; // Array
	},

	/*********************************************
	 *	   Private Property. Get off my lawn.	 *
	 *********************************************/

	_getValueAttr: function(){
		// summary:
		//		Internal. To get disabled use: uploader.get("disabled");
		return this.getFileList();
	},

	_setValueAttr: function(disabled){
		console.error("Uploader value is read only");
	},

	_getDisabledAttr: function(){
		// summary:
		//		Internal. To get disabled use: uploader.get("disabled");
		return this._disabled;
	},

	_setDisabledAttr: function(disabled){
		// summary:
		//		Internal. To set disabled use: uploader.set("disabled", true);
		if(this._disabled == disabled){ return; }
		this.button.set('disabled', disabled);
		dojo.style(this.inputNode, "display", disabled ? "none" : "block");
	},

	_getNodePosition: function(node){
		if(node.previousSibling){
			return {
				node:node.previousSibling,
				pos:"after"
			}
		}
		return {
			node:node.nextSibling,
			pos:"before"
		}
	},

	_getButtonStyle: function(node){
		if(!node){
			// we don't want this to happen. But if it does, try and display *something*.
			this.btnSize = {
				w:200,
				h:25
			};
		}else{
			this.btnSize = dojo.marginBox(node);
		}
	},

	_setButtonStyle: function(){
		var hasParent = true;
		if(!this.domNode.parentNode || !this.domNode.parentNode.tagName){
			document.body.appendChild(this.domNode);
			hasParent = false;
		}

		dojo.style(this.domNode, {
			width:this.btnSize.w+"px",
			height:(this.btnSize.h+4)+"px",
			overflow:"hidden",
			position:"relative"
		});

		this.inputNodeFontSize = Math.max(2, Math.max(Math.ceil(this.btnSize.w / 60), Math.ceil(this.btnSize.h / 15)));
		this._createInput();

		dojo.style(this.button.domNode, {
			margin:"0px",
			display:"block",
			verticalAlign:"top" // IE fix

		});

		dojo.style(this.button.domNode.firstChild, {
			margin:"0px",
			display:"block"
			//height:this.btnSize.h+"px"
		});

		if(!hasParent){
			document.body.removeChild(this.domNode);
		}
	},

	_createInput: function(){

		if(this._inputs.length){
			dojo.style(this.inputNode, {
				top:"500px"
			});
			this._disconnectButton();
			this._nameIndex++;
		}

		var name;
		if(this.supports("multiple")){
			// FF3.5+, WebKit
			name = this.name+"s[]";
		}else{
			// <=IE8
			name = this.name + (this.multiple ? this._nameIndex : "");
		}
		this.inputNode = dojo.create("input", {type:"file", name:name, className:"dojoxInputNode"}, this.domNode, "first");
		if(this.supports("multiple") && this.multiple){
			dojo.attr(this.inputNode, "multiple", true);
		}
		this._inputs.push(this.inputNode);

		dojo.style(this.inputNode, {
			fontSize:this.inputNodeFontSize+"em"
		});
		var size = dojo.marginBox(this.inputNode);

		dojo.style(this.inputNode, {
			position:"absolute",
			top:"-2px",
			left:"-"+(size.w-this.btnSize.w-2)+"px",
			opacity:0
		});
		this._connectButton();
	},

	_connectButton: function(){
		this._cons = [];
		var cs = dojo.hitch(this, function(nm){
			this._cons.push(dojo.connect(this.inputNode, nm, this, function(evt){
				this.button._cssMouseEvent({type:nm})
			}));
		});
		cs("mouseover");
		cs("mouseout");
		cs("mousedown");
		this._cons.push(dojo.connect(this.inputNode, "change", this, function(evt){
			this.onChange(this.getFileList(evt));
			if(!this.supports("multiple") && this.multiple) this._createInput();
		}));

		this.button.set('tabIndex', -1);
		if(this.tabIndex > -1){
			this.inputNode.tabIndex = this.tabIndex;
			var restoreBorderStyle = dojo.style(this.button.domNode.firstChild, "border");
			this._cons.push(dojo.connect(this.inputNode, "focus", this, function(){
				dojo.style(this.button.domNode.firstChild, "border", "1px dashed #ccc");
			}));
			this._cons.push(dojo.connect(this.inputNode, "blur", this, function(){
				dojo.style(this.button.domNode.firstChild, "border", restoreBorderStyle);
			}));
		}
	},

	_disconnectButton: function(){
		dojo.forEach(this._cons, dojo.disconnect, dojo);
	}
});

(function(){
	dojox.form.UploaderOrg = dojox.form.Uploader;
	var extensions = [dojox.form.UploaderOrg];
	dojox.form.addUploaderPlugin = function(plug){
		// summary:
		// 		Handle Uploader plugins. When the dojox.form.addUploaderPlugin() function is called,
		// 		the dojox.form.Uploader is recreated using the new plugin (mixin).
		//
		extensions.push(plug);
		dojo.declare("dojox.form.Uploader", extensions, {});
	}
})();


text:
use log::error;

use crate::interaction::SurfaceInteraction;
use crate::paramset::TextureParams;
use crate::spectrum::Spectrum;
use crate::texture::{Texture, TextureMapping2D, UVMapping2D};
use crate::Transform;

#[derive(Debug)]
pub struct UVTexture {
    mapping: Box<dyn TextureMapping2D>,
}

impl UVTexture {
    pub fn new() -> UVTexture {
        UVTexture {
            mapping: Box::new(UVMapping2D::new(1.0, 1.0, 0.0, 0.0)),
        }
    }

    pub fn create_spectrum(_tex2world: &Transform, tp: &TextureParams<'_>) -> UVTexture {
        let typ = tp.find_string("mapping", "uv");
        let mapping = if typ == "uv" {
            let su = tp.find_float("uscale", 1.0);
            let sv = tp.find_float("vscale", 1.0);
            let du = tp.find_float("udelta", 0.0);
            let dv = tp.find_float("vdelta", 0.0);
            Box::new(UVMapping2D::new(su, sv, du, dv))
        } else if typ == "spherical" {
            unimplemented!()
        } else if typ == "cylindrical" {
            unimplemented!()
        } else if typ == "planar" {
            unimplemented!()
        } else {
            error!("2D texture mapping \"{}\" unknown.", typ);
            Box::new(UVMapping2D::new(1.0, 1.0, 0.0, 0.0))
        };

        UVTexture { mapping }
    }
}

impl Default for UVTexture {
    fn default() -> Self {
        Self::new()
    }
}

impl Texture<Spectrum> for UVTexture {
    fn evaluate(&self, si: &SurfaceInteraction<'_, '_>) -> Spectrum {
        let (st, _dstdx, _dstdy) = self.mapping.map(si);
        Spectrum::rgb(st[0] - st[0].floor(), st[1] - st[1].floor(), 0.0)
    }
}


text:
var displayType = "inline-table";
var name;
var characteristic;
var gender;
var chosenClass;

function setup() {
    document.getElementById("infoCell").style.display = displayType;
    document.getElementById("genderCell").style.display = "none";
    document.getElementById("nameCell").style.display = "none";
    document.getElementById("classCell").style.display = "none";
    document.getElementById("endCell").style.display = "none";
}

function moveToGender() {
    document.getElementById("infoCell").style.display = "none";
    document.getElementById("genderCell").style.display = displayType;
    document.getElementById("nameCell").style.display = "none";
    document.getElementById("classCell").style.display = "none";
    document.getElementById("endCell").style.display = "none";
}

function moveToName_male() {
    gender = "Male";
    document.getElementById("infoCell").style.display = "none";
    document.getElementById("genderCell").style.display = "none";
    document.getElementById("nameCell").style.display = displayType;
    document.getElementById("classCell").style.display = "none";
    document.getElementById("endCell").style.display = "none";
}

function moveToName_female() {
    gender = "Female";
    document.getElementById("infoCell").style.display = "none";
    document.getElementById("genderCell").style.display = "none";
    document.getElementById("nameCell").style.display = displayType;
    document.getElementById("classCell").style.display = "none";
    document.getElementById("endCell").style.display = "none";
}

function moveToClass() {
    name = document.getElementById("name").value;
    characteristic = document.getElementById("characteristic").value;
    document.getElementById("infoCell").style.display = "none";
    document.getElementById("genderCell").style.display = "none";
    document.getElementById("nameCell").style.display = "none";
    document.getElementById("classCell").style.display = displayType;
    document.getElementById("endCell").style.display = "none";
}

function moveToEnd(i) {
    if (i === 0) {
        chosenClass = "Warrior";
    }
    else if (i === 1) {
        chosenClass = "Mage";
    }
    else if (i === 2) {
        chosenClass = "Cleric";
    }
    else if (i === 3) {
        chosenClass = "Thief";
    }
    document.getElementById("infoCell").style.display = "none";
    document.getElementById("genderCell").style.display = "none";
    document.getElementById("nameCell").style.display = "none";
    document.getElementById("classCell").style.display = "none";
    document.getElementById("endCell").style.display = displayType;

    document.getElementById("nameDisplay").innerHTML = "
Name: " + name + " the " + characteristic + "
";
    document.getElementById("genderDisplay").innerHTML = "
Gender: " + gender + "
";
    document.getElementById("classDisplay").innerHTML = "
Class: " + chosenClass + "
";
}

function saveCharacter() {
    Cookies.defaults = {
        path: '/',
    };
    Cookies.set("name",name + " the " + characteristic, { expires: Infinity });
    Cookies.set("gender",gender, { expires: Infinity });
    Cookies.set("class",chosenClass, { expires: Infinity });
    location.href = "../index.html";
}


text:
require.ensure([], function(require) {
require("./109.async.js");
require("./218.async.js");
require("./437.async.js");
require("./874.async.js");
});
module.exports = 875;


text:
<?php

namespace phpManufaktur\Basic\Control\kitFilter;

use Silex\Application;

class BasicFilter
{
    protected $app = null;
    protected static $parameter = null;
    protected static $cms = null;
    protected static $content = null;
    protected static $filter_expression = null;

    public function initClass(Application $app)
    {
        $this->app = $app;

        if (null === (self::$parameter = $app['request']->request->get('parameter', null))) {
            self::$parameter = array();
        }

        if (null === (self::$cms = $app['request']->request->get('cms', null))) {
            throw new \Exception('Missing the CMS information bag!');
        }

        if (null === (self::$content = $app['request']->request->get('content', null))) {
            throw new \Exception('Missing the content for the filter execution.');
        }

        if (null === (self::$filter_expression = $app['request']->request->get('filter_expression', null))) {
            throw new \Exception('Missing the filter expression.');
        }

        if (isset(self::$cms['locale'])) {
            // set the locale from the CMS locale
            $this->app['translator']->setLocale(self::$cms['locale']);
        }
    }

    /**
     * Return the content
     *
     * @return string content
     */
    public function getContent()
    {
        return self::$content;
    }

    /**
     * Set the content
     *
     * @param string $content
     */
    public function setContent($content)
    {
        self::$content = $content;
    }

    /**
     * Remove the filter expression from the content
     *
     */
    protected function removeExpression()
    {
        self::$content = str_replace(self::$filter_expression, '', self::$content);
    }

    /**
     * Get the complete expression
     *
     * @return string expression
     */
    public function getExpression()
    {
        return self::$filter_expression;
    }

    /**
     * Replace $search with $replace in the content.
     *
     * @param string $search
     * @param string $replace
     */
    protected function replace($search, $replace)
    {
        self::$content = str_replace($search, $replace, self::$content);
    }
}


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Agaricus subatratus Batsch, 1786

### Remarks
null


text:
package com.mvp4g.client.annotation;

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

/**
 * This annotation is used on methods to indicate that this method must be used to inject a service.

 *

 * This annotation must be used only in classes that have a Presenter or
 * History annotation.

 *

 * When a service needs to be injected, the framework will search an instance of a service with the
 * same class. If it doesn't found one, it will create one.

 * This means that only one instance of each service class will be created.

 *

 * You can also specify to inject a particular instance of a service thanks to its name with the
 * attribute serviceName.

 *
 * @author plcoirier
 * @deprecated As of release 1.2.0, shoud use GIN injection
 */
@Deprecated
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface InjectService {

  String serviceName() default "";

}


text:
'use strict';

const angular = require('angular');

// require('/components/home/home-controller');
require('./components/nav/nav-controller');
require('./components/landing/landing-controller');
require('./components/router/route-controller');
require('./components/header/header-controller');
require('./components/main/main-controller');
require('./entry-module');


text:
package org.jadira.usertype.dateandtime.threetenbp;

import org.jadira.usertype.dateandtime.threetenbp.columnmapper.StringColumnMonthMapper;
import org.jadira.usertype.spi.shared.AbstractSingleColumnUserType;
import org.threeten.bp.Month;

/**
 * Persist {@link Month} via Hibernate.
 */
public class PersistentMonthAsString extends AbstractSingleColumnUserType<Month, String, StringColumnMonthMapper> {

    private static final long serialVersionUID = 5686457807800307458L;
}


text:
__author__ = 'marko'

#!/usr/local/bin/python
import logging

import cv2

import numpy as np

from scipy import misc
from scipy import ndimage
from sklearn import preprocessing

"""
    TODO: Documentation of the class and methods
"""

logger = logging.getLogger(__name__)

class Preprocess(object):
    # sharpness meter
    def __compute_acutance(self, image_data):
        gray_image = cv2.cvtColor(image_data, cv2.COLOR_BGR2GRAY)
        image_acutance = cv2.Laplacian(gray_image, cv2.CV_64F).var()
        logger.debug('acutance: %.2f', image_acutance)
        return image_acutance

    def __deNoise(self, image_data):
        image_noisy = image_data + 0.4 * image_data.std() * np.random.random(image_data.shape)
        denoised_medium = ndimage.median_filter(image_noisy, 3)

        return denoised_medium

    def __gamma_correction(self, image_data, correction=1.0):
        img = image_data/255.0
        img = cv2.pow(img, correction)
        return np.uint8(img*255)

    def __blurrer_median(self, image_data):
        image_blurred = cv2.medianBlur(image_data, 3)
        return image_blurred

    def __blurrer_gaussian(self, image_data):
        image_blurred = ndimage.gaussian_filter(image_data, sigma=(3, 3, 0), order=0)
        return image_blurred

    def __sharpner(self, image_data):
        blurred_f = ndimage.gaussian_filter(image_data, 3)
        filter_blurred_f = ndimage.gaussian_filter(blurred_f, 1)
        alpha = 30
        image_sharpened = blurred_f + alpha * (blurred_f - filter_blurred_f)

        return image_sharpened

    def __clahe(self, image_data):
        img_lab = cv2.cvtColor(image_data, cv2.COLOR_RGB2LAB)

        clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
        img_lab[:, :, 0] = clahe.apply(img_lab[:, :, 0])
        img_output = cv2.cvtColor(img_lab, cv2.COLOR_LAB2RGB)

        return img_output

    def blur_image(self, image_data, mode='median', apply_clahe=True):
        _sharpness = self.__compute_acutance(image_data)
        logger.debug('acutance %.2f', _sharpness)

        if apply_clahe:
            image_data = self.__clahe(image_data)

        if _sharpness > 100:
            image_data = self.__blurrer_median(image_data) if mode == 'median' else self.__blurrer_gaussian(image_data)
        image_data = self.__gamma_correction(image_data)
        return image_data

    def sharp_image(self, image_data):
        _sharpness = self.__compute_acutance(image_data)
        image_data = self.__clahe(image_data)
        logger.debug('acutance %.2f', _sharpness)
        return image_data


text:
layout: default
id: 2016-08-23-Sharif-Amir
surname: Sharif
name: Amir
university: University of Genoa
date: 23/08/2016
aboutme:
from: Iran
research_topic: Dynamic Security Analysis of Android Mobile Applications
abstract:
advisor: Carbone Roberto
keywords:
website:
img: sharif.jpg
email: asharif<i class="fa fa-at" aria-hidden="true"></i>fbk.eu
alt: Amir Sharif
modal-id: stud125
---


text:
require "formula"

class Mapnik < Formula
  homepage "http://www.mapnik.org/"
  head "https://github.com/mapnik/mapnik.git"
  url "http://mapnik.s3.amazonaws.com/dist/v2.2.0/mapnik-v2.2.0.tar.bz2"
  sha1 "e493ad87ca83471374a3b080f760df4b25f7060d"
  revision 3

  bottle do
    sha1 "7ad87d1b99c5ceb1861b1cbabdb094488886bab4" => :mavericks
    sha1 "cb2d4ab00ae91ff90602db62b01703f105a21362" => :mountain_lion
    sha1 "0bcaf11e97ad59e025e38b428e03adc7195b61e2" => :lion
  end

  stable do
    # can be removed at Mapnik > 2.2.0
    # https://github.com/mapnik/mapnik/issues/1973
    patch :DATA

    # boost 1.56 compatibility
    # concatenated from https://github.com/mapnik/mapnik/issues/2428
    patch do
      url "https://gist.githubusercontent.com/tdsmith/22aeb0bfb9691de91463/raw/3064c193466a041d82e011dc5601312ccadc9e15/mapnik-boost-megadiff.diff"
      sha1 "63939ad5e197c83f7fe09e321484248dfd96d0f3"
    end
  end

  depends_on "pkg-config" => :build
  depends_on "freetype"
  depends_on "libpng"
  depends_on "libtiff"
  depends_on "proj"
  depends_on "icu4c"
  depends_on "jpeg"
  depends_on "boost"
  depends_on "boost-python"
  depends_on "gdal" => :optional
  depends_on "postgresql" => :optional
  depends_on "cairo" => :optional

  depends_on "py2cairo" if build.with? "cairo"

  def install
    icu = Formula["icu4c"].opt_prefix
    boost = Formula["boost"].opt_prefix
    proj = Formula["proj"].opt_prefix
    jpeg = Formula["jpeg"].opt_prefix
    libpng = Formula["libpng"].opt_prefix
    libtiff = Formula["libtiff"].opt_prefix
    freetype = Formula["freetype"].opt_prefix

    # mapnik compiles can take ~1.5 GB per job for some .cpp files
    # so lets be cautious by limiting to CPUS/2
    jobs = ENV.make_jobs.to_i
    jobs /= 2 if jobs > 2

    args = [ "CC=\"#{ENV.cc}\"",
             "CXX=\"#{ENV.cxx}\"",
             "JOBS=#{jobs}",
             "PREFIX=#{prefix}",
             "ICU_INCLUDES=#{icu}/include",
             "ICU_LIBS=#{icu}/lib",
             "PYTHON_PREFIX=#{prefix}",  # Install to Homebrew's site-packages
             "JPEG_INCLUDES=#{jpeg}/include",
             "JPEG_LIBS=#{jpeg}/lib",
             "PNG_INCLUDES=#{libpng}/include",
             "PNG_LIBS=#{libpng}/lib",
             "TIFF_INCLUDES=#{libtiff}/include",
             "TIFF_LIBS=#{libtiff}/lib",
             "BOOST_INCLUDES=#{boost}/include",
             "BOOST_LIBS=#{boost}/lib",
             "PROJ_INCLUDES=#{proj}/include",
             "PROJ_LIBS=#{proj}/lib",
             "FREETYPE_CONFIG=#{freetype}/bin/freetype-config"
           ]

    if build.with? "cairo"
      args << "CAIRO=True" # cairo paths will come from pkg-config
    else
      args << "CAIRO=False"
    end
    args << "GDAL_CONFIG=#{Formula["gdal"].opt_bin}/gdal-config" if build.with? "gdal"
    args << "PG_CONFIG=#{Formula["postgresql"].opt_bin}/pg_config" if build.with? "postgresql"

    system "python", "scons/scons.py", "configure", *args
    system "python", "scons/scons.py", "install"
  end
end

__END__
diff --git a/bindings/python/mapnik_text_placement.cpp b/bindings/python/mapnik_text_placement.cpp
index 0520132..4897c28 100644
--- a/bindings/python/mapnik_text_placement.cpp
+++ b/bindings/python/mapnik_text_placement.cpp
@@ -194,7 +194,11 @@ struct ListNodeWrap: formatting::list_node, wrapper<formatting::list_node>
     ListNodeWrap(object l) : formatting::list_node(), wrapper<formatting::list_node>()
     {
         stl_input_iterator<formatting::node_ptr> begin(l), end;
-        children_.insert(children_.end(), begin, end);
+        while (begin != end)
+        {
+            children_.push_back(*begin);
+            ++begin;
+        }
     }

     /* TODO: Add constructor taking variable number of arguments.


text:
package blip_testing

import (
	"testing"
	"blip/monitor"
	"fmt"
	"time"
)

func initPingMonitor(t *testing.T) *monitor.PingMonitor{
	ping_monitor, err := monitor.NewPingMonitor("localhost", monitor.MIN_ICMP_INTERVAL)
	if err != nil{
		t.Error("Failed to initiate pingMonitor")
	}
	return ping_monitor
}

func TestPingMonitorInterfaceCompliance(t *testing.T){
	defer func(){
		err := recover()
		if err != nil{
			t.Error(fmt.Sprintf("PingMonitor does not complain with Monitor interface. %s", err))
		}
	}()
	var _ monitor.Monitor = (*monitor.PingMonitor)(nil)

}

func TestPingMonitorInitIntervalTooLow(t *testing.T){
	interval_too_low := 9
	ping_monitor, err := monitor.NewPingMonitor("localhost", interval_too_low)
	if err == nil{
		if ping_monitor.Interval() == interval_too_low{
			t.Error("Initiated PingMonitor with interval value below allowed threshold.")
		}
	}
}

func TestPingMonitorSetIntervalTooLow(t *testing.T){
	ping_monitor := initPingMonitor(t)
	err := ping_monitor.SetInterval(9)
	if err ==nil{
		t.Error("Allowed to set PingMonitorInterval below allowed threshold.")
	}
}

func TestPingMonitorInitIntervalDefault(t *testing.T){
	trigger_default := 0
	ping_monitor, err := monitor.NewPingMonitor("localhost", trigger_default)
	if err == nil{
		if ping_monitor.Interval() != monitor.MIN_ICMP_INTERVAL{
			t.Error("Failed to init PingMonitor with default interval value")
		}
	}else{
		t.Error(fmt.Sprintf("Failed to create PingMonitor. %s", err))
	}
}

func TestPingMonitorSetIntervalDefault(t *testing.T){
	ping_monitor := initPingMonitor(t)
	ping_monitor.SetInterval(0)
	if ping_monitor.Interval() != monitor.MIN_ICMP_INTERVAL{
		t.Error("Failed to set PingMonitors default interval value")
	}
}

func TestPingMonitorInitNoHost(t *testing.T){
	no_host := ""
	ping_monitor, err := monitor.NewPingMonitor(no_host, monitor.MIN_ICMP_INTERVAL)
	if err == nil{
		if ping_monitor.Host() == no_host{
			t.Error("Initiated PingMonitor with empty Host.")
		}
	}
}

func TestPingMonitorSetNoHost(t *testing.T){
	ping_monitor := initPingMonitor(t)
	ping_monitor.SetHost("")
	if ping_monitor.Host() == ""{
		t.Error("Allowed to set empty Host")
	}
}

func TestPingMonitorGracefulStop(t *testing.T){
	ping_monitor := initPingMonitor(t)

	go ping_monitor.Run()
	ping_monitor.Terminate()
	time.Sleep(1 * time.Second)
	if ping_monitor.Running(){
		t.Error("Failed to stop PingMonitor routine")
	}

}

// TODO: Test actual Ping


text:
BUILDDIR=lavaburst/core

.PHONY: all clean docs build test install uninstall

all: clean build test

docs:
	cd docs && $(MAKE) html

clean:
	rm $(BUILDDIR)/*.so

build:
	python setup.py build_ext --inplace

test:
	nosetests

install:
	pip install -e .

uninstall:
	pip uninstall lavaburst


text:
<?xml version="1.0" encoding="utf-8"?>
<extension version="1.5" type="plugin" group="system">
	<name>System - Userconsent</name>
	<creationDate>June 2015</creationDate>
	<author>HUBzero</author>
	<authorUrl>hubzero.org</authorUrl>
	<authorEmail>support@hubzero.org</authorEmail>
	<copyright>Copyright 2005-2019 HUBzero Foundation, LLC.</copyright>
	<license>http://opensource.org/licenses/MIT MIT</license>
	<description>PLG_SYSTEM_USERCONSENT_XML_DESCRIPTION</description>
	<files>
		<filename plugin="userconsent">userconsent.php</filename>
	</files>
	<config>
	</config>
</extension>


text:
package com.teamderpy.shouldersurfing;

import net.minecraft.client.settings.KeyBinding;

import org.lwjgl.input.Keyboard;
import org.lwjgl.util.vector.Vector2f;
import cpw.mods.fml.client.registry.ClientRegistry;
//import cpw.mods.fml.client.registry.KeyBindingRegistry;

/**
 * @author      Joshua Powers <jsh.powers@yahoo.com>
 * @version     1.0
 * @since       2012-12-27
 */
public class ShoulderKeybindings {
	/**
	 * Minecraft keybindings for camera functions
	 */
	public static final KeyBinding KEYBIND_ROTATE_CAMERA_LEFT  = new KeyBinding("ShoulderSurfing.key.cameraMoveLeft"   , Keyboard.KEY_J, "ShoulderSurfing.keyCategory");
	public static final KeyBinding KEYBIND_ROTATE_CAMERA_RIGHT = new KeyBinding("ShoulderSurfing.key.cameraMoveRight"  , Keyboard.KEY_L, "ShoulderSurfing.keyCategory");
	public static final KeyBinding KEYBIND_ZOOM_CAMERA_OUT     = new KeyBinding("ShoulderSurfing.key.cameraMoveCloser" , Keyboard.KEY_I, "ShoulderSurfing.keyCategory");
	public static final KeyBinding KEYBIND_ZOOM_CAMERA_IN      = new KeyBinding("ShoulderSurfing.key.cameraMoveFarther", Keyboard.KEY_K, "ShoulderSurfing.keyCategory");

	private static KeyBinding[] keyBindings = {
			KEYBIND_ROTATE_CAMERA_LEFT,
			KEYBIND_ROTATE_CAMERA_RIGHT,
			KEYBIND_ZOOM_CAMERA_OUT,
			KEYBIND_ZOOM_CAMERA_IN};

	/**
	 * Registers the ShoulderSurfing keybindings with minecraft.
	 * Should only be called once!
	 *
	 * @return Returns a {@link ShoulderKeyHandler}
	 */
	public static ShoulderKeyHandler registerKeybindings(){
		ShoulderKeyHandler skh = new ShoulderKeyHandler();
		for(KeyBinding keybinding:keyBindings){
		ClientRegistry.registerKeyBinding(keybinding);
		}
		return skh;
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Curso" table="curso">
    <indexes>
      <index name="a_curso_idx" columns="autor"/>
      <index name="n_curso_idx" columns="nombreCurso"/>
    </indexes>
    <id name="idcurso" type="integer" column="idcurso">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="fechainicio" type="datetime" column="fechaInicio" nullable="false"/>
    <field name="fechafin" type="datetime" column="fechaFin" nullable="false"/>
    <field name="duracion" type="string" column="duracion" length="3" nullable="false"/>
    <field name="horainiciomanana" type="time" column="horaInicioManana" nullable="true"/>
    <field name="horafinmanana" type="time" column="horaFinManana" nullable="true"/>
    <field name="horainiciotarde" type="time" column="horaInicioTarde" nullable="true"/>
    <field name="horafintarde" type="time" column="horaFinTarde" nullable="true"/>
    <field name="intensidadhoraria" type="string" column="intensidadHoraria" length="2" nullable="false"/>
    <field name="descripcion" type="text" column="descripcion" nullable="false"/>
    <many-to-one field="nombrecurso" target-entity="Nombrecurso">
      <join-columns>
        <join-column name="nombreCurso" referenced-column-name="idnombreCurso"/>
      </join-columns>
    </many-to-one>
    <many-to-one field="autor" target-entity="Administrador">
      <join-columns>
        <join-column name="autor" referenced-column-name="idadministrador"/>
      </join-columns>
    </many-to-one>
  </entity>
</doctrine-mapping>


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sydowia 17: 198 (1964)

#### Original name
Hysterangium violaceum E. Horak, 1964

### Remarks
null


text:
package com.andkid.fancy.cache.bitmap_recycle;
/**
 * Interface for handling operations on a primitive array type.
 * @param <T> Array type (e.g. byte[], int[])
 */
public interface ArrayAdapterInterface<T> {

  /**
   * TAG for logging.
   */
  String getTag();

  /**
   * Return the length of the given array.
   */
  int getArrayLength(T array);

  /**
   * Allocate and return an array of the specified size.
   */
  T newArray(int length);

  /**
   * Return the size of an element in the array in bytes (e.g. for int return 4).
   */
  int getElementSizeInBytes();
}


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

import numpy as np
import sklearn
from sklearn.kernel_ridge import KernelRidge
from sklearn.manifold import Isomap
from sef_dr.classification import evaluate_svm
from sef_dr.datasets import dataset_loader
from sef_dr.kernel import KernelSEF
from sef_dr.sef_base import mean_data_distance

def outofsample_extensions(method=None, dataset=None):
    np.random.seed(1)
    sklearn.utils.check_random_state(1)
    dataset_path = 'data'
    train_data, train_labels, test_data, test_labels = dataset_loader(dataset_path, dataset, seed=1)
    # Learn a new space using Isomap
    isomap = Isomap(n_components=10, n_neighbors=20)
    train_data_isomap = np.float32(isomap.fit_transform(train_data))
    sigma = mean_data_distance(np.float32(train_data))

    if method == 'kernel-regression':
        # Use kernel regression to provide baseline out-of-sample extensions
        proj = KernelRidge(kernel='rbf', gamma=(1.0 / sigma ** 2))
        proj.fit(np.float64(train_data), np.float64(train_data_isomap))
        acc = evaluate_svm(proj.predict(train_data), train_labels,
                           proj.predict(test_data), test_labels)
    elif method == 'cK-ISOMAP-10d' or method == 'cK-ISOMAP-20d':
        # Use the SEF to provide out-of-sample extensions
        if method == 'cK-ISOMAP-10d':
            dims = 10
        else:
            dims = 20
        proj = KernelSEF(train_data, train_data.shape[1], output_dimensionality=dims)
        proj.cuda()
        loss = proj.fit(data=train_data, target_data=train_data_isomap, target='copy',
                        epochs=100, batch_size=256, verbose=True, learning_rate=0.00001,  regularizer_weight=0.001)
        acc = evaluate_svm(proj.transform(train_data), train_labels,
                           proj.transform(test_data), test_labels)

    print("Method: ", method, " Test accuracy: ", 100 * acc, " %")

if __name__ == '__main__':

    for dataset in ['15scene', 'corel', 'mnist', 'yale', 'kth', '20ng']:
        print("Evaluating dataset: ", dataset)

        print("Evaluating baseline kernel-regression (10d) for providing out-of-sample extensions...")
        outofsample_extensions('kernel-regression', dataset=dataset)

        print("Evaluating kernel SEF (10d) for providing out-of-sample extensions...")
        outofsample_extensions('cK-ISOMAP-10d', dataset=dataset)

        print("Evaluating kernel SEF (20d) for providing out-of-sample extensions...")
        outofsample_extensions('cK-ISOMAP-20d', dataset=dataset)


text:
% Name              : Kamna Yadav
% A Number          : A02048769
% File name         : OptimizedDemo.m
% File description  : Demo file for the optimized algorithm

clear;

% Set path for the testdata
pathPos = 'D:\Assignments\ComputerVision\Project\Deliverables\Code\Images\Genki\Pos';
pathNeg = 'D:\Assignments\ComputerVision\Project\Deliverables\Code\Images\Genki\Neg';
pathTest = 'D:\Assignments\ComputerVision\Project\Deliverables\Code\Images\Genki\Test';

% Extract HOG feature data after pre-processing training images
disp('Positive training');
tic
[featurePos, classPos] = detectOptimizedFeatures(pathPos, 1);
toc;

disp('Negative training');
tic
[featureNeg, classNeg] = detectOptimizedFeatures(pathNeg, 2);
toc;

% Concatenate the Positive and Negative test set data
ftotal = vertcat(featurePos, featureNeg);
ctotal = vertcat(classPos, classNeg);

% Create the classification model for the training data
disp('SVM training');
tic
SVMModel = fitcsvm(ftotal,ctotal);
toc;

% Extract HOG feature data after pre-processing testing images
disp('Testing');
tic
[featureTest, classTest] = detectOptimizedFeatures(pathTest, 3);
toc;

% Predict class labels for testing data
disp('Prediction');
tic
label = predict(SVMModel, featureTest);
toc;


text: exports.where = __dirname;


text:
ActiveRecord::Schema.define(:version => 20110814191338) do

  create_table "authentications", :force => true do |t|
    t.integer  "user_id"
    t.string   "provider"
    t.string   "uid"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "users", :force => true do |t|
    t.string   "email",                                 :default => "", :null => false
    t.string   "encrypted_password",     :limit => 128, :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",                         :default => 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users", ["email"], :name => "index_users_on_email", :unique => true
  add_index "users", ["reset_password_token"], :name => "index_users_on_reset_password_token", :unique => true

end


text:
#pragma once

#include <functional>
#include <memory>
#include <vector>

#include <ABI44_0_0React/ABI44_0_0renderer/core/ShadowNode.h>

namespace ABI44_0_0facebook {
namespace ABI44_0_0React {

/*
 * This is an implementation detail, do not use it directly.
 * A type-erased version of `Element<>`.
 * `ElementFragment` carries all information that is stored inside `Element<>`
 * in some generalized, type-erased manner.
 */
class ElementFragment final {
 public:
  using Shared = std::shared_ptr<ElementFragment>;
  using List = std::vector<ElementFragment>;
  using ListOfShared = std::vector<Shared>;
  using ReferenceCallback =
      std::function<void(ShadowNode::Unshared const &shadowNode)>;
  using FinalizeCallback = std::function<void(ShadowNode &shadowNode)>;
  using StateCallback = std::function<StateData::Shared()>;

  /*
   * ComponentDescriptor part (describes the type)
   */
  ComponentHandle componentHandle;
  ComponentName componentName;

  /*
   * ShadowNodeFamily part (describes the family)
   */
  Tag tag;
  SurfaceId surfaceId;

  /*
   * ShadowNode part (describes the instance)
   */
  Props::Shared props;
  List children;

  /*
   * Other
   */
  ReferenceCallback referenceCallback;
  FinalizeCallback finalizeCallback;
  StateCallback stateCallback;
};

} // namespace ABI44_0_0React
} // namespace ABI44_0_0facebook


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="@dimen/height_block_base"
  android:background="?panel"
  android:gravity="center_vertical"
  android:orientation="horizontal">
  <TextView
    android:id="@+id/tv__text"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:layout_marginLeft="@dimen/margin_half"
    android:gravity="center_vertical"
    android:singleLine="true"
    android:ellipsize="end"
    android:textAppearance="@style/MwmTextAppearance.Body2"
    tools:text="Maps: 10 (1024 MB)"/>

  <Button
    android:id="@+id/btn__action"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/margin_base"
    android:paddingRight="@dimen/margin_base"
    style="@style/MwmWidget.Button"
    android:textAppearance="@style/MwmTextAppearance.Button"
    android:textColor="?colorAccent"
    tools:text="@string/downloader_update_all_button"/>
</LinearLayout>


text:
'use strict';

/**
 * @ngdoc function
 * @name tripzcalcApp.controller:AboutCtrl
 * @description
 * # AboutCtrl
 * Controller of the tripzcalcApp
 */
angular.module('tripzcalcApp')
  .controller('AboutCtrl', function ($scope) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });


text:
namespace Nancy.Validation
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// A description of a validation rule.
    /// </summary>
    public class ModelValidationRule
    {
        private readonly Func<string, string> errorMessageFormatter;

        /// <summary>
        /// Initializes a new instance of the <see cref="ModelValidationRule"/> class.
        /// </summary>
        /// <param name="ruleType">Type of the rule.</param>
        /// <param name="errorMessageFormatter">The error message formatter.</param>
        public ModelValidationRule(string ruleType, Func<string, string> errorMessageFormatter)
        {
            if (ruleType == null)
            {
                throw new ArgumentNullException("ruleType");
            }

            if (errorMessageFormatter == null)
            {
                throw new ArgumentNullException("errorMessageFormatter");
            }

            this.RuleType = ruleType;
            this.errorMessageFormatter = errorMessageFormatter;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ModelValidationRule"/> class.
        /// </summary>
        /// <param name="ruleType">Type of the rule.</param>
        /// <param name="errorMessageFormatter">The error message formatter.</param>
        /// <param name="memberNames">Name of the member.</param>
        public ModelValidationRule(string ruleType, Func<string, string> errorMessageFormatter, IEnumerable<string> memberNames)
            : this(ruleType, errorMessageFormatter)
        {
            this.MemberNames = memberNames;
        }

        /// <summary>
        /// Gets the names of the members this rule validates.
        /// </summary>
        /// <value>An <see cref="IEnumerable{T}"/> that contains the name of the member.</value>
        public IEnumerable<string> MemberNames { get; private set; }

        /// <summary>
        /// Gets the type of the rule.
        /// </summary>
        /// <value>The type of the rule.</value>
        public string RuleType { get; private set; }

        /// <summary>
        /// Gets the error message that this rule will provide upon error.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns>The error message.</returns>
        public string GetErrorMessage(string name)
        {
            return errorMessageFormatter(name);
        }
    }
}


text:
'use strict';

define(['app'], function (app) {
    app.controller('FrontendUserCtrl', ['$scope', '$state', 'Environment', 'resourceService', 'collectionService',
        function ($scope, $state, Environment, resourceService, collectionService) {

            var itemService = new resourceService('frontenduser');

            $scope.collectionTitle = 'Frontend Users';
            $scope.pageLimit = 20;
            $scope.pageNumber = 1;
            $scope.columns = [
                {name: 'id', enableColumnMenu: false, width: '100'},
                {name: 'username', enableColumnMenu: false},
                {name: 'email', enableColumnMenu: false},
                {
                    name: 'action',
                    enableSorting: false,
                    enableFiltering: false,
                    enableColumnMenu: false,
                    width: '100',
                    cellTemplate: collectionService.actionTemplate()
                }
            ];
            $scope.gridOptions = collectionService.gridOptions($scope);

            // === Item Actions ===
            $scope.editDetails = function (id) {
                $state.transitionTo('frontendUserEdit', {locale: Environment.currentLocale(), id: id});
            };
            $scope.newItem = function () {
                $state.transitionTo('frontendUserNew', {locale: Environment.currentLocale()});
            }

            // === Load collection from remote ===
            $scope.loadCollection = function (pageNumber) {
                collectionService.loadCollection($scope, itemService, pageNumber);
            }
            $scope.loadCollection();

        }]);
});


text:
coder-dojo-resources
====================

a collection of resources that aspiring coders can use!


text:
package com.tr.rp.varstore;

public class FreeVarNameProvider {

	// Global counter to generate unique variable names
	private volatile static long rwCounter = 0;

	/**
	 * Returns a unique variable name based on the original variable name.
	 * This uses an internal static counter, whose value is included in the
	 * variable name, to avoid collisions. It is guaranteed that this method
	 * never returns the same name (except possibly in case of counter
	 * overflow, which ¯should not occur in practice). All names returned
	 * start with "$".
	 *
	 * @param original Original variable name
	 * @return A unique variable name based on original
	 */
	public static String getFreeVariable(String original) {
		return "$" + (rwCounter++) + "_" + original;
	}
}


text:
module CourseAssets::Jobs
class ContentDepositorChangeEventJob
  include Rails.application.routes.url_helpers
  include ActionView::Helpers
  include ActionView::Helpers::DateHelper
  include Hydra::AccessControlsEnforcement
  include SufiaHelper

  def queue_name
    :proxy_deposit
  end

  attr_accessor :pid, :login, :reset

  # @param [String] pid identifier of the file to be transfered
  # @param [String] login the user key of the user the file is being transfered to.
  # @param [Boolean] reset (false) should the access controls be reset. This means revoking edit access from the depositor
  def initialize(pid, login, reset=false)
    self.pid = pid
    self.login = login
    self.reset = reset
  end

  def run
    file = GenericFile.find(pid)
    file.proxy_depositor = file.depositor
    file.rightsMetadata.clear_permissions! if reset
    # TODO: Determine whether this should retain or reset permissions
    file.apply_depositor_metadata(login)
    file.save!

    action = "User #{link_to_profile file.proxy_depositor} has transferred #{link_to file.title.first, Sufia::Engine.routes.url_helpers.generic_file_path(file.noid)} to User #{link_to_profile login}"
    timestamp = Time.now.to_i
    depositor = User.find_by_user_key(file.depositor)
    proxy_depositor = User.find_by_user_key(file.proxy_depositor)
    # Create the event
    event = proxy_depositor.create_event(action, timestamp)
    # Log the event to the GF's stream
    file.log_event(event)

    #log the event to the depositor
    log_depositor_event(event, depositor, file)

    #log the event to the proxy_depositor
    log_depositor_event(event, proxy_depositor, file)

  end
  def log_depositor_event(event, depositor, gf)
    # Log the event to the depositor's profile stream
    depositor.log_profile_event(event)
    # Fan out the event to all followers who have access
    depositor.followers.select { |user| user.can? :read, gf }.each do |follower|
      follower.log_event(event)
    end

  end
end
end