text:
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using System.Collections;
using System;
using UnityEngine.Networking;

public class MatrixSessionEngine : MonoBehaviour {
    const int BUFFER_SIZE = 1024;

    // Use this for initialization
    void Start()
    {
    }

    //functions for getting REST state
    public void MatrixLogin()
    {
        MatrixSessionInfo.LoginType = "m.login.password";
        StartCoroutine(MatrixREST("_matrix/client/r0/login", "POST", new LoginInfo(), new LoginResponse()));
    }
    //get the server's room directory
    public void MatrixRooms() {
        StartCoroutine(MatrixREST("_matrix/client/r0/publicRooms", "GET", null, new DirectoryResponse()));
    }
    //send a text message to a room
    public void MatrixMessage(string roomid, string msgbody)
    {
        SendEvent msgevent = new SendEvent();
        msgevent.body = new EventBody();
        msgevent.roomId = roomid;
        msgevent.body.body = msgbody;
        msgevent.eventType = "m.room.message";
        msgevent.body.msgtype = "m.text";
        msgevent.txnId = MatrixSessionInfo.txnId;
        StartCoroutine(MatrixREST(string.Format("_matrix/client/r0/rooms/{0}/send/{1}/{2}?access_token={3}", msgevent.roomId.Replace(":", "%3A"), msgevent.eventType, msgevent.txnId, MatrixSessionInfo.AccessToken),
            "PUT", msgevent.body, new SendEventResponse()));
        MatrixSessionInfo.txnId = (Int32.Parse(MatrixSessionInfo.txnId) + 1).ToString();
    }
    public void MatrixJoinRoom(string roomIdOrAlias)
    {
        StartCoroutine(MatrixREST(string.Format("_matrix/client/r0/join/{0}?access_token={1}", WWW.EscapeURL(roomIdOrAlias), MatrixSessionInfo.AccessToken), "POST", null, null));
    }

    //generic handler for any REST endpoint
    IEnumerator MatrixREST(string URL, string method, MatrixJSON data, MatrixResponse response)
    {
        var dataToSend = Encoding.UTF8.GetBytes(JsonUtility.ToJson(data));
        //var postHeader = new Dictionary<string, string>();
        Debug.Log("jsonString: " + JsonUtility.ToJson(data));
        Debug.Log("URL: " + MatrixSessionInfo.HomeServer + URL);
        //POST if you use a postHeader, GET without
        UnityWebRequest request = new UnityWebRequest(MatrixSessionInfo.HomeServer + URL, method); ;
        if (method == "POST" || method == "PUT") {
            if (data != null) {
                request.uploadHandler = (UploadHandler)new UploadHandlerRaw(dataToSend);
            }
            request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
            request.SetRequestHeader("Content-Type", "application/json");
        }
        else if (method == "GET"){
            request = UnityWebRequest.Get(MatrixSessionInfo.HomeServer + URL);
            request.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        }
        yield return request.Send();
        if (request.error != null || request.responseCode == 404)
        {
            Debug.Log("request error: " + request.responseCode);
            if (response != null) {
                response.Error();
            }
        }
        else
        {
            Debug.Log("request success" + request.responseCode);
            Debug.Log("returned data" + request.downloadHandler.text);
            //write the endpoint response, if there is one, into the response object
            if (response != null)
            {
                JsonUtility.FromJsonOverwrite(request.downloadHandler.text, response);
                //The response object will then populate the MatrixSessionInfo static values
                response.Save();
            }
        }
    }
}


text:
#!/usr/bin/env node

var docloud = require('docloud-api');
var program = require('commander');
var fs = require('fs');

/**
 * Reads the config file
 * @returns the config object
 */
function readConfig(){
		var config={};
		if (process.env.HOME) {
			var configFile = process.env.HOME+"/.docloud";
			if (fs.existsSync(configFile)) {
				  config = JSON.parse(fs.readFileSync(process.env.HOME+"/.docloud"));
			}
		}
		return config;
}

/**
 * Writes the config file
 * @param config the config
 */
function writeConfig(config){
   var content = JSON.stringify(config,undefined,2);
   fs.writeFileSync(process.env.HOME+"/.docloud",content);
}

/**
 * Returns the DOcloud client connected to the selected config
 * @returns the client
 */
function connect(){
	try {
		var configs = readConfig();
	    var cname = program.configuration || 'default';
	    var config = configs[cname];

		var client = docloud({
			  url : program.baseurl || config.baseurl,
			  clientId : program.clientid || config.clientid
			});
		if (!client.url){
			console.log("Base URL not defined");
			process.exit(1);
		}
		if (!client.clientId){
			console.log("Client id not defined");
			process.exit(1);
		}
		if (program.verbose)
			console.log("Using config %s with DOcloud URL %s",cname, client.url);
		return client;

	} catch (e) {
		console.log(e);
		process.exit(1);
	}
}

program
 .option('-c, --clientid <clientid>', 'set or override the API key (client id)')
 .option('-u, --baseurl <baseurl>', 'set or override the base URL of DOcloud')
 .option('-g, --configuration <name>', 'select the configuration to use')
 .option('-v, --verbose', 'activate verbose mode')

 // config
program.command('config [name]')
	.description('save configuration defaults in ~/.docloud')
	.action (function(name,options){
		var configs = readConfig();
		var cname = name || 'default';
		configs[cname]= {};
		configs[cname].clientid = program.clientid;
		configs[cname].baseurl = program.baseurl;
		writeConfig(configs);
	});

function collect(val, memo) {
	 if (val) {
	    var p = val.split("=");
	    memo[p[0]]=p[1];
      }
	  return memo;
	}

 // submit
program.command('execute <dir>')
    .alias('exec')
	.description('execute a job by submitting files from a directory')
	.option('-l, --log', 'stream log to stdout as the job is running')
	.option('-p, --param [param]', 'add a prameter', collect,{})
	.action (function(dir,options){

		var files = fs.readdirSync(dir);
		var data = {};
		data.attachments = files.filter(function (f){
			if (f=='solution.json' || f=='solution.xml') return false;
			var index = f.lastIndexOf('.');
			if (index<0) return false;
			var ext = f.substring(index+1);
			var accepted = ["lp", "prm", "sav", "mps", "mod", "dat", "json", "ops","oplproject"]
			return accepted.indexOf(ext)>=0;
		}).map(function(f){
			var att = {};
			att.name = f;
			att.stream = fs.createReadStream(dir+"/"+f);
			return att;
		})
		if (options.log) {
		   data.logstream = process.stdout;
		}
		data.parameters = options.param;
		var client = connect();
		client.execute(data)
		   .on('processed', function(jobid){
			   client.downloadAttachment(jobid,'solution.json',fs.createWriteStream(dir+'/solution.json'))
			         .then(function () {return client.downloadLog(jobid,fs.createWriteStream(dir+'/solution.log'))})
			         .catch(function (error) {process.exit(1)})
		   })
		   .on('interrupted', function(jobid){console.log("Interrupted")})
		   .on('failed', function(jobid){
			     client.getJob(jobid)
		         .then(function (job) {console.log("job failed with message %s",job.failure.message)})
		         .catch(function (error) {process.exit(1)})
			   })
		   .on('error', function(error){process.exit(1)})

	});

function pad(s,l){
	for (var i=s.length; i<l; i++){
		s+=' ';
	}
	return s;
}
function padLeft(s,l){
	var p='';
	for (var i=s.length; i<l; i++){
		p+=' ';
	}
	return p+s;
}
// jobs
program.command('jobs [options...]')
	.description('list the jobs')
	.option('-j, --json', 'returns raw JSON list')
	.action (function(env,options){
		var client = connect();
		client.listJobs()
		  .then(function (list){
			 if (options.json) {
				console.log(list);
			 } else {
				list.forEach(function(job){
					console.log("%s %s %s %s %s",
							pad(job._id,40),
							pad(new Date(job.createdAt).toLocaleDateString(),10),
							pad(new Date(job.createdAt).toLocaleTimeString(),15),
							pad(job.executionStatus,15),
							pad(job.solveStatus?job.solveStatus:"-",35)
							);
				})
				}
		  	 })
		   .catch(function (error) {process.exit(1)})

	});

//list attachments
program.command('attachments <jobid>')
	.description('list the job attachments')
	.alias("atts")
	.option('-j, --json', 'returns raw JSON list')
	.action (function(jobid,options){
		var client = connect();
		client.getJob(jobid)
		  .then(function (job){
			 if (options.json) {
				console.log(job.attachments);
			 } else {
				job.attachments.forEach(function(att){
					console.log("%s %s %s",
							padLeft(''+att.length,15),
							pad(att.type,18),
							att.name
							);
				})
				}
		  	 })
		   .catch(function (error) {console.log(error);process.exit(1)})
	});

//download
program.command('download <jobid> <attid>')
	.description('download a job attachment to stdout')
	.action (function(jobid,attid){
		var client = connect();
		client.downloadAttachment(jobid,attid,process.stdout)
		 .catch(function (error) {console.log(error);process.exit(1)})
	});

//upload
//program.command('upload <jobid> <attid>')
//	.description('upload a job attachment from stdin')
//	.action (function(jobid,attid){
//		var client = connect();
//		client.uploadAttachment(jobid,attid,process.stdin)
//		 .catch(function (error) {console.log(error);process.exit(1)})
//	});

//download
program.command('log <jobid> ')
	.description('download a job log to stdout')
	.action (function(jobid){
		var client = connect();
		client.downloadLog(jobid,process.stdout)
		 .catch(function (error) {console.log(error);process.exit(1)})
	});
//delete
program.command('get <jobid>')
	.description('get a job')
	.option('-j, --json', 'returns raw JSON object')
	.action (function(jobid,options){
		var client = connect();
		client.getJob(jobid).then(function(job){
			if (options.json){
				console.log(job);
			} else {
				console.log("%s %s %s %s %s",
						pad(job._id,40),
						pad(new Date(job.createdAt).toLocaleDateString(),10),
						pad(new Date(job.createdAt).toLocaleTimeString(),15),
						pad(job.executionStatus,15),
						pad(job.solveStatus?job.solveStatus:"-",35)
						);
		    }
		})
		.catch(function (error) {process.exit(1)})
	});

// delete
program.command('delete <jobid>')
    .alias('del')
	.description('delete a job')
	.action (function(jobid,options){
		var client = connect();
		client.deleteJob(jobid)
		.catch(function (error) {process.exit(1)});
	});

// abort
program.command('abort <jobid>')
	.description('abort a job')
	.option('-k, --kill', 'kill a job')
	.action (function(jobid,options){
		var client = connect();
		client.abortJob(jobid,options.kill)
		.catch(function (error) {process.exit(1)});
	});

//delete-all
program.command('delete-all')
	.description('delete all jobs')
	.action (function(env,options){
		var client = connect();
		client.deleteJobs()
		.catch(function (error) {process.exit(1)})
	});

module.exports=program;

redpajama_set_name: RedPajamaGithub


text:
"""The Resource Mapper data model.  All entities and fields are add-only and
are never deleted or overwritten.  To represent modifications to a country's
data, create a new Version under the appropriate Country.  To represent
modifications to a subject's attributes, add a new Report for that Subject.

This project uses the following naming conventions in variables and properties:

    "key":
        An App Engine entity key.

    "name":
        A unique identifier for an entity, used as the entity's key_name.
        Fields ending in "_name" contain the key_names of other entities.

        Names should be C-style identifiers (thus usable as HTML element IDs,
        form element names, and CSS classes) and are usually not displayed in
        the UI directly.  For each name, there should be a corresponding
        Message entity that provides the localized text.

    "title":
        A non-localizable, UI-displayable text label for an entity.
"""

import datetime

from google.appengine.ext import db

MAX_DATE = datetime.datetime(datetime.MAXYEAR, 1, 1)

class Subdomain(db.Model):
    """A separate grouping of Subjects and SubjectTypes.  Top-level entity,
    with no parent.  Key name: unique subdomain name.  In the UI, each
    subdomain appears to be an independent instance of the application.  The
    permitted actions of Accounts and key_names of Subjects and SubjectTypes
    are namespaced by prefixing them with the subdomain name and a colon.  All
    other entities are shared across all subdomains."""
    pass  # No properties for now; only the key_name is significant.

def filter_by_prefix(query, key_name_prefix, root_kind=None):
    """Filters a query for key_names that have the given prefix.  If root_kind
    is specified, filters the query for children of any entities that are of
    that kind with the given prefix; otherwise, the results are assumed to be
    top-level entities of the kind being queried."""
    root_kind = root_kind or query._model_class.__name__
    min_key = db.Key.from_path(root_kind, key_name_prefix)
    max_key = db.Key.from_path(root_kind, key_name_prefix + u'\uffff')
    return query.filter('__key__ >=', min_key).filter('__key__ <=', max_key)

def value_or_none(value):
    """Converts any false value other than 0 or 0.0 to None."""
    if value or value == 0:
        return value
    return None

def get_name(name_or_entity):
    """If given an entity, returns its name (without subdomain); if given a
    string, returns the string itself."""
    if isinstance(name_or_entity, (Subject, SubjectType)):
        return name_or_entity.name
    elif isinstance(name_or_entity, db.Model):
        return name_or_entity.key().name()
    else:
        return name_or_entity

class SubdomainMixin:
    """A mix-in class providing common methods for entities whose key names
    begin with a subdomain and a colon."""
    @classmethod
    def get(cls, subdomain, name):
        """Gets an entity by its subdomain and name.  This method overrides
        the default get() method, which takes a db.Key."""
        return cls.get_by_key_name(subdomain + ':' + name)

    @classmethod
    def all_in_subdomain(cls, subdomain):
        """Gets a query for all entities with the given subdomain."""
        root_kind = getattr(cls, 'ROOT_KIND', None)
        return filter_by_prefix(cls.all(), subdomain + ':', root_kind)

    def get_subdomain(self):
        """Gets the entity's subdomain."""
        return self.key().name().split(':', 1)[0]
    subdomain = property(get_subdomain)

    def get_name(self):
        """Gets the entity's name (without the subdomain)."""
        return self.key().name().split(':', 1)[1]
    name = property(get_name)

class Subject(SubdomainMixin, db.Expando):
    """A thing whose attributes are tracked by this application.  Top-level
    entity, has no parent.  Key name: subdomain + ':' + subject name.
    A subject name is a globally unique ID that starts with a domain name and
    a slash.  In the 'haiti' subdomain, Subjects are health facilities with a
    government or internationally established health facility ID."""
    timestamp = db.DateTimeProperty(auto_now_add=True)  # creation time
    type = db.StringProperty(required=True)  # key_name of a SubjectType,
                                             # without the subdomain prefix
    author = db.UserProperty()  # who created this Subject
    # additional properties for the current value of each attribute
    # (named by Attribute's key_name).  This denormalization is for read speed.
    # Consider an attribute named 'foo'. We will store 6 values here:
    # foo__                    various types, the attribute value
    # foo__observed            datetime, timestamp when the value was valid
    # foo__author              users.User, the user who provided the change
    # foo__author_nickname     string, source of the change
    # foo__author_affiliation  string, affiliation of the source
    # foo__comment             string, a comment about the change
    # These properties will exist with the following invariants:
    # 1. If subject.foo__ is not present, that means attribute "foo" has never
    #    existed on this subject at any point in the past.
    # 2. If subject.foo__ is None, that means some user actually set the
    #    attribute to "(unspecified)".
    # 3. All six fields are always written together at the same time, and are
    #    never removed.  (Hence either all are present or none are present.)

    @staticmethod
    def create(subdomain, subject_type_or_type_name, subject_name, author):
        """Creates a Subject with a given subdomain, type, name, and author."""
        return Subject(key_name='%s:%s' % (subdomain, subject_name),
                       type=get_name(subject_type_or_type_name), author=author)

    @staticmethod
    def generate_name(host, subject_type_or_type_name):
        """Makes a new unique subject_name for an original subject (originally
        created in this repository, not cloned from an external repository)."""
        id = UniqueId.create_id()
        return '%s/%s.%d' % (host, get_name(subject_type_or_type_name), id)

    @staticmethod
    def get_stored_name(attribute_name):
        return '%s__' % attribute_name

    @classmethod
    def delete_complete(cls, subject):
        if subject:
            minimal_subject = MinimalSubject.get_by_subject(subject)
            db.delete([subject, minimal_subject])

    def has_value(self, attribute_name):
        """Returns the value of the Attribute with the given key_name,
           or default if it does not exist."""
        return hasattr(self, '%s__' % attribute_name)

    def get_value(self, attribute_name, default=None):
        """Returns the value of the Attribute with the given key_name,
           or default if it does not exist."""
        return getattr(self, '%s__' % attribute_name, default)

    def get_observed(self, attribute_name, default=None):
        """Returns the timestamp when the Attribute with the given key_name
           was valid, or default if it does not exist."""
        return getattr(self, '%s__observed' % attribute_name, default)

    def get_author(self, attribute_name, default=None):
        """Returns the author of the Attribute value with the given key_name,
           or default if it does not exist."""
        return getattr(self, '%s__author' % attribute_name, default)

    def get_author_nickname(self, attribute_name, default=None):
        """Returns the author nickname of the Attribute value with the given
           key_name, or default if it does not exist."""
        return getattr(self, '%s__author_nickname' % attribute_name, default)

    def get_author_affiliation(self, attribute_name, default=None):
        """Returns the affiliation of the author of the Attribute value
           with the given key_name, or default if it does not exist."""
        return getattr(self, '%s__author_affiliation' % attribute_name, default)

    def get_comment(self, attribute_name, default=None):
        """Returns the author's comment about the Attribute value with the
           given key_name, or default if it does not exist."""
        return getattr(self, '%s__comment' % attribute_name, default)

    def set_attribute(self, name, value, observed, author, author_nickname,
                      author_affiliation, comment):
        """Sets the value for the Attribute with the given key_name."""
        setattr(self, '%s__' % name, value_or_none(value))
        setattr(self, '%s__observed' % name, value_or_none(observed))
        setattr(self, '%s__author' % name, value_or_none(author))
        setattr(self, '%s__author_nickname' % name,
                value_or_none(author_nickname))
        setattr(self, '%s__author_affiliation' % name,
                value_or_none(author_affiliation))
        setattr(self, '%s__comment' % name, value_or_none(comment))

class MinimalSubject(SubdomainMixin, db.Expando):
    """Minimal version of Subject that loads fast from the datastore and
    contains just the information needed to populate the initial list and map.
    Parent: Subject.  Key name: same as its parent Subject.  Wouldn't be
    necessary if we could select columns from the datastore."""
    type = db.StringProperty(required=True)  # key_name of a SubjectType,
                                             # without the subdomain prefix
    # More properties for the current values of ONLY the most critically
    # important attributes of Subject (named by Attribute's key_name).
    # An attribute named foo will be stored as 'foo__' to match Subject.

    ROOT_KIND = 'Subject'  # filter_by_prefix uses this to filter keys properly

    @staticmethod
    def create(subject):
        return MinimalSubject(
            subject, key_name=subject.key().name(), type=subject.type)

    @staticmethod
    def get_by_subject(subject):
        """Gets the MinimalSubject entity for the given Subject."""
        return MinimalSubject.all().ancestor(subject).get()

    @staticmethod
    def get_stored_name(attribute_name):
        return '%s__' % attribute_name

    def has_value(self, attribute_name):
        """Returns the value of the Attribute with the given key_name,
           or default if it does not exist."""
        return hasattr(self, '%s__' % attribute_name)

    def get_value(self, attribute_name, default=None):
        """Returns the value of the Attribute with the given key_name,
           or default if it does not exist."""
        return getattr(self, '%s__' % attribute_name, default)

    def set_attribute(self, name, value):
        """Sets the value for the Attribute with the given key_name."""
        setattr(self, '%s__' % name, value_or_none(value))

class UniqueId(db.Model):
    """This entity is used just to generate unique numeric IDs."""
    @staticmethod
    def create_id():
        """Gets a numeric ID that is guaranteed to be different from any ID
        previously returned by this static method."""
        unique_id = UniqueId()
        unique_id.put()
        return unique_id.key().id()

class SubjectType(SubdomainMixin, db.Model):
    """A type of Subject, e.g. hospital, warehouse, charity, camp.  Top-level
    entity, has no parent.  Key name: subdomain + ':' + type name.  A type name
    is an identifier used as the value of Subject.type."""
    timestamp = db.DateTimeProperty(auto_now_add=True)
    attribute_names = db.StringListProperty()  # key_names of Attribute entities
    minimal_attribute_names = db.StringListProperty()  # key_names of
        # Attribute entities whose values should be copied into MinimalSubject

    @staticmethod
    def create(subdomain, subject_type_name):
        return SubjectType(key_name=subdomain + ':' + subject_type_name)

class Attribute(db.Model):
    """An attribute of a subject, e.g. services available, # of
    patients. Top-level entity, has no parent.  Key name: name of a property
    in a Report, and also the name of the Message providing the
    UI-displayable attribute name."""
    timestamp = db.DateTimeProperty(auto_now_add=True)
    type = db.StringProperty(required=True, choices=[
        'str',     # value is a single-line string (Python unicode)
        'text',    # value is a string, shown as long text (Python unicode)
        'contact', # value is a 3-line string (name, phone, e-mail address)
        'date',    # value is a date (Python datetime with time 00:00:00)
        'int',     # value is an integer (64-bit long)
        'float',   # value is a float (Python float, i.e. double)
        'bool',    # value is a boolean
        'choice',  # value is a string (one of the elements in 'values')
        'multi',   # value is a list of strings (which are elements of 'values')
        'geopt',   # value is a db.GeoPt with latitude and longitude
    ])
    edit_action = db.StringProperty() # What Account action can edit?
    values = db.StringListProperty()  # allowed value names for choice or multi

class Report(db.Expando):
    """A report on the attributes and resources of a Subject.
    Parent: Subject.  A Report may represent a partial update of the
    attributes of the subject."""
    arrived = db.DateTimeProperty(auto_now_add=True) # date we received report
    source = db.StringProperty() # a URL, the source of the report
    author = db.UserProperty() # author of the report
    observed = db.DateTimeProperty()  # date that report contents were valid
    # additional properties for each Attribute (named by Attribute's key_name)
    # Consider an attribute named 'foo'. We will store 2 values here:
    # foo__          various, the attribute value
    # foo__comment   db.StringProperty, a comment from user making the change
    # These properties will exist with the following invariants:
    # 1. If report.foo__ is not present, that means attribute "foo" should
    # not change its value from the previous report.
    # 2. If report.foo__ is None, that means some user actually set the
    # attribute to "(unspecified)".
    # 3. Both fields are always written together at the same time, and
    # are never removed.  (Hence either all are present or none are present.)

    def get_value(self, attribute_name, default=None):
        """Returns the value of the Attribute with the given key_name,
           or default if it does not exist."""
        return getattr(self, '%s__' % attribute_name, default)

    def get_comment(self, attribute_name, default=None):
        """Returns the author's comment about the Attribute value with the
           given key_name, or default if it does not exist."""
        return getattr(self, '%s__comment' % attribute_name, default)

    def set_attribute(self, name, value, comment):
        """Sets the value for the Attribute with the given key_name."""
        setattr(self, '%s__' % name, value_or_none(value))
        setattr(self, '%s__comment' % name, value_or_none(comment))

class Account(db.Model):
    """User account. Top-level entity, has no parent.  Users without Account
    entities can use the application; for such users, their permissions are
    determined by the special Account object with key_name='default'.  Users
    get their own Account entities when editing a Subject, requesting
    permissions, being granted permissions, or subscribing to alerts."""
    timestamp = db.DateTimeProperty(auto_now_add=True)  # creation time
    description = db.StringProperty()  # full name or description
    email = db.StringProperty()  # e-mail address of the account
    user_id = db.StringProperty()  # users.User.id() of the account
    nickname = db.StringProperty()  # nickname for display in the UI; may
                                    # differ from users.User.nickname()
    affiliation = db.StringProperty()  # company or organization, etc.
    token = db.StringProperty()  # secret token for looking up an Account with
                                 # no e-mail address (so we can have Account
                                 # entities for nonexistent Google Accounts)
    actions = db.StringListProperty()  # actions allowed for this user (items
                                       # have the form subdomain + ':' + verb;
                                       # '*' is a wildcard subdomain or verb)
    requested_actions = db.StringListProperty()  # permissions requested but
                                                 # not yet granted
    locale = db.StringProperty() # user chosen locale
    # default frequency for updates
    default_frequency = db.StringProperty(default='instant')
    # preferred format to receive e-mail in
    email_format = db.StringProperty(choices=['plain', 'html'], default='plain')

    # For explanation of default settings for the next alert times, see
    # mail_alerts.py's send_digests function.
    # next time to send a daily update
    next_daily_alert = db.DateTimeProperty(default=MAX_DATE)
    # next time to send a weekly update to the user
    next_weekly_alert = db.DateTimeProperty(default=MAX_DATE)
    # next time to send a monthly update to the user
    next_monthly_alert = db.DateTimeProperty(default=MAX_DATE)

class Message(db.Expando):
    """Internationalized strings for value identifiers.  Top-level entity,
    has no parent."""
    # Formerly namespace, renamed to work around bug in GAE 1.3.5 (b/2811890);
    # Can change back after 1.3.6, which contains the fix
    ns = db.StringProperty(required=True, choices=[
      'english',  # name is an English string
      'attribute_name',  # name is an Attribute's key_name
      'attribute_value', # name is a value name in a choice or multi attribute
      'subject_type' # name is a SubjectType's key_name (including subdomain)
    ])
    name = db.StringProperty()
    # additional properties for each language (named by locale code)

class Dump(db.Model):
    """A record of the data received from a data source in its native format,
    before it was converted and loaded into the datastore.  Top-level entity,
    has no parent."""
    timestamp = db.DateTimeProperty(auto_now_add=True)
    base = db.SelfReference()  # if present, this dump is a clone of base
    source = db.StringProperty()  # URL identifying the source
    data = db.BlobProperty()  # received raw data

# TODO(kpy): Clean up the inconsistent use of the term "subject_name".
# In Subscription, subject_name is the entire Subject key including the
# subdomain; elsewhere it is just the part after the subdomain.
class Subscription(db.Model):
    """A subscription by a user to receive notification when details for a
    facility change. Top-level entity, has no parent.
    Key name: follows the format subject_name:user_email"""
    user_email = db.StringProperty(required=True) # user to alert
    subject_name = db.StringProperty(required=True) # key_name of subject
    frequency = db.StringProperty(required=True, choices=[
        'instant', # send an alert whenever the facility is updated
        'daily', # send during a daily digest e-mail
        'weekly', # send during a weekly digest e-mail
        'monthly' # send during a monthly digest e-mail on the 1st of the month
    ]) # frequency of updates for this subject

    @staticmethod
    def get(subject_name, user_email):
        """Gets a Subscription entity by its subject_name and e-mail."""
        return Subscription.get_by_key_name(subject_name + ':' + user_email)

    @staticmethod
    def get_by_subject(subject_name):
        """Gets a query for all PendingAlert with the given subject name."""
        return filter_by_prefix(Subscription.all(), subject_name + ':')

class PendingAlert(MinimalSubject):
    """A pending notification for a user; waiting to be sent on a daily/weekly/
    monthly basis, pending the frequency of the particular alert. Top-level
    entity, has no parent.
    Key name: follows the format frequency:user_email:subject_name"""
    user_email = db.StringProperty(required=True) # user to alert
    subject_name = db.StringProperty(required=True) # key_name of subject
    timestamp = db.DateTimeProperty() # creation time of the pending alert
    frequency = db.StringProperty(required=True, choices=[
        'instant', # send an alert whenever the subject is updated
        'daily', # send during a daily digest e-mail
        'weekly', # send during a weekly digest e-mail
        'monthly' # send during a monthly digest e-mail on the 1st of the month
    ]) # frequency of updates for this subject

    @staticmethod
    def get(frequency, user_email, subject_name):
        """Gets a PendingAlert entity by its frequency, e-mail, and
        subject name."""
        return PendingAlert.get_by_key_name(frequency + ':' + user_email +
                                            ':' + subject_name)

    @staticmethod
    def get_by_frequency(frequency, user_email):
        """Gets a query for all PendingAlert with the given frequency and
        associated user e-mail."""
        return filter_by_prefix(PendingAlert.all(), frequency + ':' +
                                user_email + ':')

class MailUpdateText(db.Expando):
    """A map from attribute names and values to alternate values accepted
    in the mail editing system. They are strings that users can type into
    e-mails to refer to attribute names or values. Key name: follows the
    format namespace:name.

    This table should at all times contain the following special cases for
    general-use attribute values: true, false, and none. Accepted values are:
        true: ['Yes', 'y', 'true']
        false: ['No', 'n', 'false']
        none: ['*none']
    by default. In total, the number of entities in the table should be equal
    to the number of attribute entities, plus the unique values across all
    multi and choice attributes, plus the 3 general values defined above."""
    # name is an attribute name or attribute value; see below
    name = db.StringProperty(required=True)
    ns = db.StringProperty(required=True, choices=[
        'attribute_name', # name is an attribute's key_name
        'attribute_value' # name is a value name in a choice or multi attribute
    ])
    # Expando values should be initialized on a per-language basis as a list
    # of accepted input strings for this particular map, in that language.
    # Use the same naming format as in the Message table [en for English,
    # fr for French, etc.]. The first value in each list should match the
    # corresponding Message, to make mail editing behavior resilient to
    # changes in translations. For comparison purposes, each item in the
    # list will be treated as case-insensitive. Spaces should be used in
    # favor of underscores.

    @classmethod
    def get(cls, ns, name):
        """Gets an entity by its namespace and name."""
        key_name = '%s:%s' % (ns, name)
        return cls.get_by_key_name(key_name)

    @classmethod
    def create(cls, ns, name, **kwargs):
        """Creates an entity with the specified namespace and name."""
        key_name = '%s:%s' % (ns, name)
        return cls(key_name=key_name, ns=ns, name=name, **kwargs)

    @classmethod
    def all_in_namespace(cls, ns):
        """Gets a query for all entities with the given namespace."""
        return filter_by_prefix(cls.all(), ns + ':')


text:
@implementation UITableView (PMUtils)

- (void) reloadVisibleRowsWithRowAnimation:(UITableViewRowAnimation)animation
{
	NSArray *visibleRows = [self indexPathsForVisibleRows];
	[self reloadRowsAtIndexPaths:visibleRows withRowAnimation:animation];
}

@end


text:
<?php namespace Cms\api;

use Carbon\Carbon;
use Cms\FunctionalTester;
use Gzero\Cms\Jobs\CreateContent;
use Gzero\Cms\Jobs\DeleteContent;
use Gzero\Core\Models\Language;
use Gzero\Core\Models\User;

class DeletedContentCest {

    public function _before(FunctionalTester $I)
    {
        $I->apiLoginAsAdmin();
    }

    public function shouldGetListOfDeletedContents(FunctionalTester $I)
    {
        $user     = factory(User::class)->create();
        $language = new Language(['code' => 'en']);

        $content = dispatch_now(CreateContent::content('Content Title', $language, $user, ['is_active' => true]));

        $I->sendGET(apiUrl('deleted-contents'));

        $I->seeResponseCodeIs(200);
        $I->seeResponseIsJson();
        $I->assertEmpty($I->grabDataFromResponseByJsonPath('data[*]'));

        dispatch_now(new DeleteContent($content));

        $I->sendGET(apiUrl('deleted-contents'));

        $I->seeResponseCodeIs(200);
        $I->seeResponseIsJson();
        $I->seeResponseJsonMatchesJsonPath('data[*]');
        $I->seeResponseContainsJson(
            [
                'type'         => 'content',
                'translations' => [
                    [
                        'language_code' => 'en',
                        'title'         => 'Content Title',
                        'is_active'     => true,
                    ]
                ]
            ]
        );
    }

    public function shouldBeAbleToFilterListOfDeletedContentsByDeletedAt(FunctionalTester $I)
    {
        $fourDaysAgo = Carbon::now()->subDays(4)->format('Y-m-d');
        $yesterday   = Carbon::yesterday()->format('Y-m-d');
        $today       = Carbon::now()->format('Y-m-d');

        $I->haveContents([
            [
                'deleted_at'   => $today,
                'translations' => [
                    ['language_code' => 'en', 'title' => "Today's deleted content"]
                ]
            ],
            [
                'deleted_at'   => $fourDaysAgo,
                'translations' => [
                    ['language_code' => 'en', 'title' => "Four day's ago deleted content"]
                ]
            ]
        ]);

        $I->sendGET(apiUrl("deleted-contents?deleted_at=$yesterday,$today"));

        $I->seeResponseCodeIs(200);
        $I->seeResponseIsJson();
        $I->seeResponseJsonMatchesJsonPath('data[*]');
        $I->seeResponseContainsJson(
            ['title' => "Today's deleted content"]
        );
        $I->dontSeeResponseContainsJson(
            ['title' => "Four day's ago deleted content"]);

        $I->sendGET(apiUrl("deleted-contents?deleted_at=$fourDaysAgo,$yesterday"));

        $I->seeResponseCodeIs(200);
        $I->seeResponseIsJson();
        $I->seeResponseJsonMatchesJsonPath('data[*]');
        $I->seeResponseContainsJson(
            ['title' => "Four day's ago deleted content"]);
        $I->dontSeeResponseContainsJson(
            ['title' => "Today's deleted content"]
        );
    }

    public function canDeleteOnlySoftDeletedContent(FunctionalTester $I)
    {
        $content = $I->haveContent(
            [
                'type'         => 'content',
                'translations' => [
                    [
                        'language_code' => 'en',
                        'title'         => 'Some Title',
                        'teaser'        => 'Teaser',
                        'body'          => 'Body',

                    ]
                ]
            ]
        );

        $I->sendDELETE(apiUrl('deleted-contents', ['id' => $content->id]));

        $I->seeResponseCodeIs(404);

        dispatch_now(new DeleteContent($content));

        $I->sendDELETE(apiUrl('deleted-contents', ['id' => $content->id]));

        $I->seeResponseCodeIs(204);
    }

    public function canRestoreOnlySoftDeletedContent(FunctionalTester $I)
    {
        $content = $I->haveContent(
            [
                'translations' => [
                    [
                        'language_code' => 'en',
                        'title'         => 'Restored content',
                    ]
                ]
            ]
        );

        $I->sendPOST(apiUrl("deleted-contents/$content->id/restore"));

        $I->seeResponseCodeIs(404);

        dispatch_now(new DeleteContent($content));

        $I->sendPOST(apiUrl("deleted-contents/$content->id/restore"));

        $I->seeResponseCodeIs(200);
        $I->seeResponseIsJson();
        $I->dontSeeResponseJsonMatchesJsonPath('data[*]');
        $I->seeResponseContainsJson(
            ['title' => 'Restored content']);
    }
}


text:
require 'spec_helper'

describe EQ::Job do

  it 'creates a job with payload' do
    job = EQ::Job.new nil, EQ::Job, ['bar', 'foo']
    job.id.should == nil
    job.queue.should == "EQ::Job"
    job.job_class.should == EQ::Job
    job.payload.should == ['bar', 'foo']
  end

  it 'creates a job without payload' do
    job = EQ::Job.new nil, EQ::Job
    job.id.should == nil
    job.queue.should == "EQ::Job"
    job.job_class.should == EQ::Job
    job.payload.should == nil
  end

  it 'performs using queue.perform(*payload)' do
    class MyJob
      def self.perform(*args)
        {result: args}
      end
    end
    my_job_args = [1,2,3]
    job = EQ::Job.new(nil, MyJob, my_job_args)
    job.perform.should == {result: my_job_args}
  end
end


text:
<?php

namespace FDevs\Photatoes\Adapter;

use FDevs\Photatoes\Image;
use FDevs\Photatoes\Gallery;
use FDevs\Photatoes\Manager;

interface AdapterInterface
{
    /**
     * get Photo
     *
     * @param  Image $image
     * @return \FDevs\Photatoes\Image
     */
    public function getImage(Image $image);

    /**
     * put image on server
     *
     * @param  Image $image
     * @return boolean
     */
    public function saveImage(Image $image);

    /**
     * get Gallery
     *
     * @param  Gallery $album
     * @return Gallery
     */
    public function getGallery(Gallery $album);

    /**
     * get Cover
     *
     * @param  Gallery $album
     * @return Gallery
     */
    public function getCover(Gallery $album);

    /**
     * save Gallery
     *
     * @param  Gallery $album
     * @return boolean
     */
    public function saveGallery(Gallery $album);

    /**
     * get Images Gallery
     *
     * @param  Gallery $album
     * @return Gallery
     */
    public function getImagesGallery(Gallery $album);

    /**
     * get Galleries
     *
     * @param  Manager $manager
     * @return Gallery[]
     */
    public function getListGallery(Manager $manager);

    /**
     * get All Tags
     *
     * @return array
     */
    public function getTagList();

    /**
     * get Images By Tag
     *
     * @param string $tag
     * @param Manager $manager
     * @return Image[]
     */
    public function getImagesByTag($tag, Manager $manager);

}


text:
package org.hawkular.apm.api.services;

import java.util.List;

/**
 * This interface enables an application to register a handler for metric
 * information from the publisher.
 *
 * @author gbrown
 */
public interface PublisherMetricHandler<T> {

    /**
     * This method is invoked with the time taken to publish the
     * supplied items.
     *
     * @param tenantId The tenantId
     * @param items The items
     * @param metric The time taken to publish
     */
    void published(String tenantId, List<T> items, long metric);

}


text:
#region License

#endregion
using System.Collections.Generic;
namespace System.Web.Mvc
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
    public abstract class ModelMetadataModifierAttributeBase : Attribute
    {
        public abstract Action<ModelMetadata, ModelMetadataModifierArguments> Modifier { get; }
    }
}


text:
/*	$NetBSD: ls.c,v 1.8 1998/09/13 15:19:13 christos Exp $	*/

/*-
 * Copyright (c) 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
#ifndef lint
__COPYRIGHT("@(#) Copyright (c) 1993\n\
	The Regents of the University of California.  All rights reserved.\n");
#endif /* not lint */

#ifndef lint
#if 0
static char sccsid[] = "@(#)ls.c	8.1 (Berkeley) 6/11/93";
#else
__RCSID("$NetBSD: ls.c,v 1.8 1998/09/13 15:19:13 christos Exp $");
#endif
#endif /* not lint */

#include <sys/param.h>
#include <sys/stat.h>
#include <sys/dirent.h>
#include <ufs/ufs/dir.h>
#include <ufs/ufs/dinode.h>
#include <sys/ttychars.h>
#include <lib/libsa/stand.h>

int main __P((void));
static void ls __P((int));

int
main()
{
	struct stat st;
	int fd;

	for (;;) {
		if ((fd = getfile("ls", 0)) == -1)
			exit();

		if (fstat(fd, &st) == -1) {
			printf("ls: cannot stat\n");
			continue;
		}

		if (!S_ISDIR(st.st_mode)) {
			printf("ls: not a direntory\n");
			continue;
		}
		if (st.st_size == 0) {
			printf("ls: zero length direntory\n");
			continue;
		}
		ls(fd);
	}
}

typedef struct dirent	DP;
static void
ls(fd)
	register int fd;
{
	register int size;
	register char *dp;
	char dirbuf[DIRBLKSIZ];

	printf("\ninode\tname\n");
	while ((size = read(fd, dirbuf, DIRBLKSIZ)) == DIRBLKSIZ)
		for (dp = dirbuf; (dp < (dirbuf + size)) &&
		    (dp + ((DP *)dp)->d_reclen) < (dirbuf + size);
		    dp += ((DP *)dp)->d_reclen) {
			if (((DP *)dp)->d_fileno == 0)
				continue;
			if (((DP *)dp)->d_namlen > MAXNAMLEN+1) {
				printf("Corrupt file name length!  Run fsck soon!\n");
				return;
			}
			printf("%d\t%s\n", ((DP *)dp)->d_fileno,
			    ((DP *)dp)->d_name);
		}
}


text:
output buffering - ob_start
--FILE--
<?php
ob_start();
echo "foo\n";
?>
--EXPECT--
foo


text:
package com.graphhopper.ui;

import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.io.Serializable;

/**
 * @author Peter Karich
 */
public interface MapLayer extends Serializable
{
    void setBounds( Rectangle r );

    Rectangle getBounds();

    void setBuffering( boolean enable );

    void repaint();

    void paint( Graphics2D g );
}


text:
require File.join(File.dirname(__FILE__),'..','..','spec_helper')

describe "<%=class_name%>Controller" do
  include_examples "SpecHelper"
	include Rack::Test::Methods
	include Rhoconnect

  def app
    @app = Rack::URLMap.new Rhoconnect.url_map
  end

  before(:each) do
    setup_test_for <%=class_name%>,'testuser'
    # login user to establish session cookie before each test
    post "/rc/#{Rhoconnect::API_VERSION}/app/login", {"login" => 'testuser', "password" => ''}.to_json, {'CONTENT_TYPE'=>'application/json; charset=UTF-8'}
    last_response.status.should == 200
  end

  it "should process <%=class_name%>Controller GET" do
    pending
  end

  it "should process <%=class_name%>Controller POST" do
    pending
  end
end


text:
import java.io.*;
class a  {
  void f1(int i) {
    try {
      new FileReader("");
    }
    finally {
      <error descr="Unhandled exception: java.lang.ClassNotFoundException">throw new ClassNotFoundException();</error>
    }
  }

  void f2(int i) {
    try {
      <error descr="Unhandled exception: java.io.FileNotFoundException">new FileReader("")</error>;
    }
    finally {
      if (i==4) <error descr="Unhandled exception: java.lang.ClassNotFoundException">throw new ClassNotFoundException();</error>
    }
  }

  void f3(int i) {
    try {
      <error descr="Unhandled exception: java.io.FileNotFoundException">new FileReader("")</error>;
    }
    finally {
      if (i==1) return;
    }
  }

  void f4(int i) {
    try {
      <error descr="Unhandled exception: java.io.FileNotFoundException">new FileReader("")</error>;
    }
    finally {
      if (i==1) <error descr="Unhandled exception: java.io.FileNotFoundException">throw new FileNotFoundException();</error>
    }
  }

  void cf1(int i) {
    try {
      new FileReader("");
    }
    catch (FileNotFoundException e) {
    }
    finally {
      if (1==1) return;
    }
  }

  void cf2(int i) {
    try {
      new FileReader("");
    }
    finally {
      while (1==1) return;
    }
  }
  void foo(OutputStream out, byte[] data) throws IOException {
    out.write(data);
  }

    public void swallow() {
        try {
            throw new Exception("Hello World! I'm Checked Exception and must be declared!");
        } catch (Exception e) {
            throw e;
        } finally {
            return;
        }
    }
    public void spitout() {
        try {
            throw new Exception("Hello World! I'm Checked Exception and must be declared!");
        } catch (Exception e) {
             <error descr="Unhandled exception: java.lang.Exception">throw e;</error>
        } finally {
            //return;
        }
    }

}


text:
package us.ihmc.aci.disServiceProProxy;

import java.util.logging.Level;
import java.util.logging.Logger;
import us.ihmc.aci.dspro2.legacy.LegacyDSProProxy;
import us.ihmc.aci.util.dspro.soi.PeriodicTrackGeneratingTrackHandler;
import us.ihmc.aci.util.dspro.soi.TrackHandler;

import us.ihmc.comm.CommException;

/**
 * DisServiceProProxy version that cancel the received Soi Native Tracks from DSPro
 * and DisService data caches and pushes generated Tracks at every setActualPosition().
 *
 * @author Giacomo Benincasa (gbenincasa@ihmc.us), Enrico Casini (ecasini@ihmc.us)
 */
public class SUDADisServiceProProxy extends DisServiceProProxy
{
    private TrackHandler _trackHandler;

    public SUDADisServiceProProxy ()
    {
        super();
        _trackHandler = null;
    }

    public SUDADisServiceProProxy (short applicationId)
    {
        super(applicationId);
        _trackHandler = null;
    }

    public SUDADisServiceProProxy (short applicationId, String host, int iPort)
    {
        super (applicationId, host, iPort);
        _trackHandler = null;
    }

    @Override
    public synchronized boolean setMetadataPossibleValues (String xMLMetadataValues) throws CommException
    {
        return super.setMetadataPossibleValues(xMLMetadataValues);
    }

    @Override
    public int init() throws Exception
    {
        _trackHandler = new PeriodicTrackGeneratingTrackHandler (this);
        int rc = super.init();
        new Thread (_trackHandler).start();
        return rc;
    }

    @Override
    public synchronized boolean setActualPosition (float fLatitude, float fLongitude, float fAltitude,
                                                   String location, String note) throws CommException
    {
        _trackHandler.setActualPosition (getNodeId(), fLatitude, fLongitude, fAltitude, location, note);
        return super.setActualPosition(fLatitude, fLongitude, fAltitude, location, note);
    }
}


text:
<?php

namespace Cdlr\mailBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class CdlrmailBundle extends Bundle
{
}


text:
package org.terasology.web.model;

import java.util.Objects;

/**
 */
public class ServerEntry {

    private String address;
    private String name;
    private String owner;
    private String country;
    private String stateprov;
    private String city;
    private int port;
    private boolean active;

    ServerEntry() {
        // required for marshalling
    }

    public ServerEntry(String address, int port) {
        this.address = address;
        this.port = port;
    }

    public String getName() {
        return name;
    }

    public String getAddress() {
        return address;
    }

    public int getPort() {
        return port;
    }

    public String getOwner() {
        return owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getStateprov() {
        return stateprov;
    }

    public void setStateprov(String stateprov) {
        this.stateprov = stateprov;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

    @Override
    public String toString() {
        return "ServerEntry [name=" + name + ", address=" + address + ", port=" + port + ", owner=" + owner + ", active=" + active + "]";
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, address, port, owner, country, stateprov, city, active);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        ServerEntry other = (ServerEntry) obj;

        return Objects.equals(address, other.address)
            && Objects.equals(port, other.port)
            && Objects.equals(name, other.name)
            && Objects.equals(owner, other.owner)
            && Objects.equals(city, other.city)
            && Objects.equals(stateprov, other.stateprov)
            && Objects.equals(country, other.country)
            && Objects.equals(active, other.active);
    }

}


text:
var Category = require('../models/Category');

module.exports = {

	find: function(params, callback){
		Category.find(params, function(err, category){
			if (err) {
				callback(err, null)
				return
			}
			callback(null, category)
		})
	},

	findById: function(id, callback){
		Category.findById(id, function(err, category){
			if(err){
				callback(err, null)
				return
			}
			callback(null, category)
		})
	},

	create: function(params, callback){
		Category.create(params, function(err, category){
			if (err){
				callback(err, null)
				return
			}
			callback(null, category)
		})
	},

	update: function(id, params, callback){
		Category.findByIdAndUpdate(id, params, {new:true}, function(err, category){
			if (err){
				callback(err, null)
				return
			}
			callback(null, category)
		})
	},

	destroy: function(id, callback){
		Category.findByIdAndRemove(id, function(err){
			if (err){
				callback(err, null)
				return
			}

			callback(null,null)
		})
	}
}


text:
using namespace std;
using namespace Eigen;

namespace fovis
{

#define dump(var) //(cerr<<" "#var<<" =[\n"<< setprecision (12)<<var<<"];"<<endl)
Eigen::ArrayXf InitialHomographyEstimator::flattenMatrix(Eigen::MatrixXf &m)
{
  return Eigen::Map<Eigen::ArrayXf>(m.data(), m.rows() * m.cols());
}

static void
grayToEigen(const uint8_t * grayData, int width, int height, int stride,
    int downsampleFactor, Eigen::MatrixXf* result)
{
  Eigen::MatrixXf& eig_imf = *result;
  if (downsampleFactor > 0) {
    int cols = width >> downsampleFactor;
    int rows = height >> downsampleFactor;
    eig_imf = Eigen::MatrixXf::Zero(rows, cols);
    for (int y = 0; y < height; y++) {
      int ey = y >> downsampleFactor;
      for (int x = 0; x < width; x++) {
        int ex = x >> downsampleFactor;
        eig_imf(ey, ex) += grayData[y * stride + x];
      }
    }
    double pixelFactor = (1 << downsampleFactor);
    eig_imf /= pixelFactor * pixelFactor;
  }
  else {
    eig_imf.resize(height, width);
    const uint8_t* row_start = grayData;
    for(int row=0; row<height; row++) {
      for(int col=0; col<width; col++) {
        eig_imf(row, col) = row_start[col];
      }
      row_start += stride;
    }
  }
}

void InitialHomographyEstimator::setTestImage(const uint8_t * grayData, int width, int height, int stride, int downsampleFactor)
{
  grayToEigen(grayData, width, height, stride, downsampleFactor, &testImage);
}

void InitialHomographyEstimator::setTemplateImage(const uint8_t * grayData, int width, int height, int stride,
    int downsampleFactor)
{
  grayToEigen(grayData, width, height, stride, downsampleFactor, &templateImage);
  template_rows = templateImage.rows();
  template_cols = templateImage.cols();

  //compute template gradients
  Eigen::MatrixXf templateDx, templateDy;
  computeGradient(templateImage, &templateDx, &templateDy);

  templateDxRow = flattenMatrix(templateDx);
  templateDyRow = flattenMatrix(templateDy);

  //setup the utility matrices
  Eigen::MatrixXf x = VectorXf::LinSpaced(template_cols, 0, template_cols - 1).transpose().replicate(template_rows, 1);
  Eigen::MatrixXf y = VectorXf::LinSpaced(template_rows, 0, template_rows - 1).replicate(1, template_cols);
  xx = flattenMatrix(x);
  yy = flattenMatrix(y);

  templatePoints.resize(3, xx.rows());
  templatePoints.row(0) = xx;
  templatePoints.row(1) = yy;
  templatePoints.row(2).setOnes();

  xx += 1;
  yy += 1;

}

double InitialHomographyEstimator::computeError(const Eigen::MatrixXf &error)
{
  return error.norm() / sqrt((double) error.rows() * error.cols());
}

Eigen::Matrix3f InitialHomographyEstimator::track(const Eigen::Matrix3f & initH, int nIters, double * finalRMS)
{

  double minError = INFINITY;
  Eigen::Matrix3f H = initH;
  Eigen::Matrix3f bestH = H;
  int bestIter = 0;
  int lastImproved = 0;
  double lastRMS = INFINITY;

  for (int iter = 0; iter < nIters; iter++) {
    tictoc("track_iter");
    tictoc("warpPoints");
    Eigen::MatrixXf warpedHomogeneousPoints;
    warpedHomogeneousPoints = H * templatePoints;
    tictoc("warpPoints");

    tictoc("constructWarpedImage");
    warpedTestImage = constructWarpedImage(testImage, warpedHomogeneousPoints);
    tictoc("constructWarpedImage");

    errorIm = warpedTestImage - templateImage;
    Eigen::VectorXf errorRow;
    errorRow = flattenMatrix(errorIm);

    double rmsError = computeError(errorRow);

    if (rmsError < minError) {
      minError = rmsError;
      bestH = H;
      bestIter = iter;
    }

    tictoc("computeJacobian");
    tictoc("computeGradient");
    Eigen::MatrixXf warpedTestImageDx, warpedTestImageDy;
    computeGradient(warpedTestImage, &warpedTestImageDx, &warpedTestImageDy);
    tictoc("computeGradient");

    Eigen::ArrayXf warpedTestImageDxRow, warpedTestImageDyRow;
    warpedTestImageDxRow = flattenMatrix(warpedTestImageDx);
    warpedTestImageDyRow = flattenMatrix(warpedTestImageDy);

    Eigen::MatrixXf Jt = computeJacobian(templateDxRow + warpedTestImageDxRow, templateDyRow + warpedTestImageDyRow);
    tictoc("computeJacobian");

    //compute the psuedo-inverse
    tictoc("update");
    tictoc("svd_pinv");
    Eigen::JacobiSVD<MatrixXf> svd(Jt, ComputeThinU | ComputeThinV);
    Eigen::VectorXf sigma = svd.singularValues();
    Eigen::MatrixXf U = svd.matrixU();
    Eigen::MatrixXf V = svd.matrixV();
    int r = 0;
    for (r = 0; r < sigma.rows(); r++) { //singular values are in decreasing order
      if (sigma(r) < 1e-7) //TODO:better way to get the tolerance?
        break;
      else
        sigma(r) = 1.0 / sigma(r);
    }
    Eigen::MatrixXf Jt_plus;
    if (r == 0)
      Jt_plus = Eigen::MatrixXf::Zero(Jt.cols(), Jt.rows());
    else {
      Jt_plus = V.block(0, 0, V.rows(), r) * sigma.head(r).asDiagonal() * U.block(0, 0, U.rows(), r).transpose();
    }
    tictoc("svd_pinv");

    // this doesn't seem to work :-/
    //    tictoc("manual_pinv");
    //    Eigen::Matrix3f JtT_Jt = Jt.transpose() * Jt;
    //    Eigen::MatrixXf Jt_plus = JtT_Jt.inverse() * Jt;
    //    tictoc("manual_pinv");

    Eigen::VectorXf lie_d = -2 * Jt_plus * errorRow;
    tictoc("update");

    tictoc("lieToH");
    H = H * lieToH(lie_d);
    tictoc("lieToH");

    if (rmsError < lastRMS)
      lastImproved = iter;

    tictoc("track_iter");

    //        cout << iter << ") rmsError= " << rmsError << " minError = " << minError << " d.norm() =" << lie_d.norm() << endl;
    //    exit(1);
    if (lie_d.norm() < 1e-6 || (rmsError - minError > 3 && iter - bestIter > 2) || iter - bestIter > 4 || iter
        - lastImproved > 2) {
      //      printf("breaking after %d iters\n", iter);
      break;
    }
    lastRMS = rmsError;

  }
  if (finalRMS != NULL)
    *finalRMS = minError;
  return bestH;

}

void InitialHomographyEstimator::computeGradient(const Eigen::MatrixXf &image, Eigen::MatrixXf *dxp, Eigen::MatrixXf *dyp)
{
  Eigen::MatrixXf & dx = *dxp;
  Eigen::MatrixXf & dy = *dyp;
  dx = Eigen::MatrixXf::Zero(image.rows(), image.cols());
  dy = Eigen::MatrixXf::Zero(image.rows(), image.cols());

  dx.block(0, 1, dx.rows(), dx.cols() - 2) = image.block(0, 2, dx.rows(), dx.cols() - 2) - image.block(0, 0, dx.rows(),
      dx.cols() - 2);
  //handle border

  dy.block(1, 0, dy.rows() - 2, dy.cols()) = image.block(2, 0, dy.rows() - 2, dy.cols()) - image.block(0, 0, dy.rows()
      - 2, dy.cols());
  //normalize
  dx /= 2.0;
  dy /= 2.0;

  //handle borders
  dx.col(0) = image.col(1) - image.col(0);
  dx.col(image.cols() - 1) = image.col(image.cols() - 1) - image.col(image.cols() - 2);
  dy.row(0) = image.row(1) - image.row(0);
  dy.row(image.rows() - 1) = image.row(image.rows() - 1) - image.row(image.rows() - 2);

}

Eigen::MatrixXf InitialHomographyEstimator::computeJacobian(const Eigen::ArrayXf &dx, const Eigen::ArrayXf &dy) const
{
  Eigen::MatrixXf Jt(dx.rows(), 3);
  Jt.col(0) = dx;
  Jt.col(1) = dy;
  Jt.col(2) = dx * yy - dy * xx;
  return Jt;
}

Eigen::Matrix3f InitialHomographyEstimator::lieToH(const Eigen::VectorXf &lie) const
{
  //TODO: support more parameters?
  Eigen::Matrix3f M;
  M << 0, lie(2), lie(0),
      -lie(2), 0, lie(1),
       0, 0, 0;
  return M.exp();
}

Eigen::MatrixXf InitialHomographyEstimator::constructWarpedImage(const Eigen::MatrixXf &srcImage,
    const Eigen::MatrixXf &warpedPoints) const
{
  Eigen::MatrixXf warped = Eigen::MatrixXf(template_rows, template_cols);

  const double defaultValue = 128;
  //Bilinear interpolation
  for (int i = 0; i < warpedPoints.cols(); i++) {
    double val;
    Eigen::Vector2f pt = warpedPoints.col(i).head(2) / warpedPoints(2, i);
    Eigen::Vector2i fipt(floor(pt(0)), floor(pt(1)));
    Eigen::Vector2i cipt(ceil(pt(0)), ceil(pt(1)));
    if (0 <= pt(0) && pt(0) < srcImage.cols() - 1 && 0 <= pt(1) && pt(1) < srcImage.rows() - 1) {
      double x1 = pt(0) - fipt(0);
      double y1 = pt(1) - fipt(1);
      double x2 = 1 - x1;
      double y2 = 1 - y1;
      val = x2 * y2 * srcImage(fipt(1), fipt(0)) + x1 * y2 * srcImage(fipt(1), fipt(0) + 1) + x2 * y1 * srcImage(
          fipt(1) + 1, fipt(0)) + x1 * y1 * srcImage(fipt(1) + 1, fipt(0) + 1);

    }
    else if (0 <= fipt(0) && fipt(0) < srcImage.cols() && 0 <= fipt(1) && fipt(1) < srcImage.rows()) {
      val = srcImage(fipt(1), fipt(0));
    }
    else if (0 <= cipt(0) && cipt(0) < srcImage.cols() && 0 <= cipt(1) && cipt(1) < srcImage.rows()) {
      val = srcImage(cipt(1), cipt(0));
    }
    else
      val = defaultValue; //templateImage(i / template_cols, i % template_cols); //default to the same as template, so error is 0

    warped(i % template_rows, i / template_rows) = val; //Eigen is Column-major
  }
  return warped;
}

}


text:
package commons;
import java.util.*;

/** Heap of ints **/
abstract class Heap {
	/** Current array length **/
	protected int capacity;
	/** Current number of elements in Heap **/
	protected int size;
	/** Array of Heap elements **/
	protected int[] items;

	public Heap() {
		this.capacity = 10;
		this.size = 0;
		this.items = new int[capacity];
	}

	public int size() {
		return this.size;
	}
	/**
	 * @param parentIndex
	 *            The index of the parent element.
	 * @return The index of the left child.
	 **/
	public int getLeftChildIndex(int parentIndex) {
		return 2 * parentIndex + 1;
	}

	/**
	 * @param parentIndex
	 *            The index of the parent element.
	 * @return The index of the right child.
	 **/
	public int getRightChildIndex(int parentIndex) {
		return 2 * parentIndex + 2;
	}

	/**
	 * @param childIndex
	 *            The index of the child element.
	 * @return The index of the parent element.
	 **/
	public int getParentIndex(int childIndex) {
		return (childIndex - 1) / 2;
	}

	/**
	 * @param index
	 *            The index of the element you are checking.
	 * @return true if the Heap contains enough elements to fill the left child
	 *         index, false otherwise.
	 **/
	public boolean hasLeftChild(int index) {
		return getLeftChildIndex(index) < size;
	}

	/**
	 * @param index
	 *            The index of the element you are checking.
	 * @return true if the Heap contains enough elements to fill the right child
	 *         index, false otherwise.
	 **/
	public boolean hasRightChild(int index) {
		return getRightChildIndex(index) < size;
	}

	/**
	 * @param index
	 *            The index of the element you are checking.
	 * @return true if the calculated parent index exists within array bounds false
	 *         otherwise.
	 **/
	public boolean hasParent(int index) {
		return getParentIndex(index) >= 0;
	}

	/**
	 * @param index
	 *            The index of the element whose child you want.
	 * @return the value in the left child.
	 **/
	public int leftChild(int index) {
		return items[getLeftChildIndex(index)];
	}

	/**
	 * @param index
	 *            The index of the element whose child you want.
	 * @return the value in the right child.
	 **/
	public int rightChild(int index) {
		return items[getRightChildIndex(index)];
	}

	/**
	 * @param index
	 *            The index of the element you are checking.
	 * @return the value in the parent element.
	 **/
	public int parent(int index) {
		return items[getParentIndex(index)];
	}

	/**
	 * @param indexOne
	 *            The first index for the pair of elements being swapped.
	 * @param indexTwo
	 *            The second index for the pair of elements being swapped.
	 **/
	public void swap(int indexOne, int indexTwo) {
		int temp = items[indexOne];
		items[indexOne] = items[indexTwo];
		items[indexTwo] = temp;
	}

	/** Doubles underlying array if capacity is reached. **/
	public void ensureCapacity() {
		if (size == capacity) {
			capacity = capacity << 1;
			items = Arrays.copyOf(items, capacity);
		}
	}

	/**
	 * @throws IllegalStateException
	 *             if Heap is empty.
	 * @return The value at the top of the Heap.
	 **/
	public int peek() {
		isEmpty("peek");

		return items[0];
	}

	/**
	 * @throws IllegalStateException
	 *             if Heap is empty.
	 **/
	public void isEmpty(String methodName) {
		if (size == 0) {
			throw new IllegalStateException("You cannot perform '" + methodName + "' on an empty Heap.");
		}
	}

	/**
	 * Extracts root element from Heap.
	 *
	 * @throws IllegalStateException
	 *             if Heap is empty.
	 **/
	public int poll() {
		// Throws an exception if empty.
		isEmpty("poll");

		// Else, not empty
		int item = items[0];
		items[0] = items[size - 1];
		size--;
		heapifyDown();
		return item;
	}

	/**
	 * @param item
	 *            The value to be inserted into the Heap.
	 **/
	public void add(int item) {
		// Resize underlying array if it's not large enough for insertion
		ensureCapacity();

		// Insert value at the next open location in heap
		items[size] = item;
		size++;

		// Correct order property
		heapifyUp();
	}

	/** Swap values down the Heap. **/
	public abstract void heapifyDown();

	/** Swap values up the Heap. **/
	public abstract void heapifyUp();
}

class MaxHeap extends Heap {

	public void heapifyDown() {
		int index = 0;
		while (hasLeftChild(index)) {
			int smallerChildIndex = getLeftChildIndex(index);

			if (hasRightChild(index) && rightChild(index) > leftChild(index)) {
				smallerChildIndex = getRightChildIndex(index);
			}

			if (items[index] > items[smallerChildIndex]) {
				break;
			} else {
				swap(index, smallerChildIndex);
			}
			index = smallerChildIndex;
		}
	}

	public void heapifyUp() {
		int index = size - 1;

		while (hasParent(index) && parent(index) < items[index]) {
			swap(getParentIndex(index), index);
			index = getParentIndex(index);
		}
	}
}

class MinHeap extends Heap {

	public void heapifyDown() {
		int index = 0;
		while (hasLeftChild(index)) {
			int smallerChildIndex = getLeftChildIndex(index);

			if (hasRightChild(index) && rightChild(index) < leftChild(index)) {
				smallerChildIndex = getRightChildIndex(index);
			}

			if (items[index] < items[smallerChildIndex]) {
				break;
			} else {
				swap(index, smallerChildIndex);
			}
			index = smallerChildIndex;
		}
	}

	public void heapifyUp() {
		int index = size - 1;

		while (hasParent(index) && parent(index) > items[index]) {
			swap(getParentIndex(index), index);
			index = getParentIndex(index);
		}
	}

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		int range = scanner.nextInt();
		scanner.close();

		// Insert random values into heaps:
		Heap minHeap = new MinHeap();
		Heap maxHeap = new MaxHeap();
		System.out.println("Insert Number Sequence:");
		for (int i = 0; i < range; i++) {
			int value = (int) (Math.random() * 100);
			minHeap.add(value);
			maxHeap.add(value);
			System.out.print(+value + " ");
		}

		// Remove values from heaps:
		System.out.println("\n\nPoll Values:\n------------\nMinHeap MaxHeap");
		for (int i = 0; i < range; i++) {
			System.out.format("  %-12d", minHeap.poll());
			System.out.format("%-6d\n", maxHeap.poll());
		}
		try {
			minHeap.peek();
		} catch (IllegalStateException e) {
			System.out.println(e.getMessage());
		}
		try {
			maxHeap.poll();
		} catch (IllegalStateException e) {
			System.out.println(e.getMessage());
		}
	}
}


text:
using System.ComponentModel.DataAnnotations;
using CleanArchitecture.Core.Entities;

namespace CleanArchitecture.Web.ApiModels
{
    // Note: doesn't expose events or behavior
    public class ToDoItemDTO
    {
        public int Id { get; set; }

        [Required]
        public string Title { get; set; }

        public string Description { get; set; }
        public bool IsDone { get; private set; }

        public static ToDoItemDTO FromToDoItem(ToDoItem item)
        {
            return new ToDoItemDTO
            {
                Id = item.Id,
                Title = item.Title,
                Description = item.Description,
                IsDone = item.IsDone
            };
        }
    }
}


text:
module Mysh

  # The mysh help command usage.
  class UsageOption < CommandOption

    # Execute the help command line option. (Punt to error handler with no msg)
    def pre_boot(_args)
      raise MyshUsage
    end

  end

  # Add the usage command line option to the library.
  desc = 'Display mysh usage info and exit.'

  USAGE = UsageOption.new('--help', desc)
  COMMAND_LINE.add_action(USAGE)
  COMMAND_LINE.add_action(UsageOption.new('-h', desc))
  COMMAND_LINE.add_action(UsageOption.new('-?', desc))
end


text:
module RecruiterLint
  module Rules
    class Length < Rule
      name "Length"
      desc "Don't write a small essay, get to the point."

      def run(spec, result)
        if spec.length > 1200
          result.add_warning "Email is too long - get to the point quicker"
          result.add_recruiter_fail_points 1
        elsif spec.length < 30
          result.add_warning "Email is too short - explain more about the position"
          result.add_recruiter_fail_points 1
        end
      end
    end
  end
end


text:
import {Component, Input, enableProdMode, OnInit, OnDestroy} from "@angular/core";
import {Router, ActivatedRoute, Params} from "@angular/router";
import {Speaker} from "./speaker";
import {SpeakerService} from "./speaker.service";

enableProdMode();

@Component({
    selector: 'speakers',
    templateUrl: 'app/speaker/speakers.component.html',
})
export class SpeakersComponent implements OnInit, OnDestroy {

    title = 'Speakers';
    speakers: Speaker[];
    @Input() selectedSpeaker: Speaker;
    search: string;

    constructor(private router: Router, private route: ActivatedRoute, private speakerService: SpeakerService) {
    }

    ngOnInit(): void {
        let _self = this;

        this.speakerService.init(function () {
            _self.getSpeakers();

            _self.route.params.forEach((params: Params) => {
                _self.onSelectId(params['id']);
            });
        });
    }

    ngOnDestroy(): void {

    }

    getSpeakers(): void {
        this.speakerService.getSpeakers().then(speakers => this.speakers = speakers).catch(SpeakersComponent.handleError);
    }

    onSelectId(any: any): void {
        this.speakerService.getSpeakersById([any as string]).then(speaker => this.onSelect(speaker[0]));
    }

    onSelect(speaker: Speaker): void {

        if (undefined != speaker && null != speaker) {
            this.selectedSpeaker = speaker;
        }
    }

    onSearch(search: string): void {
        this.search = search;
    }

    private static handleError(error: any): Promise<any> {
        console.error('An error occurred', error); // TODO - Display safe error
        return Promise.reject(error.message || error);
    }
}


text:
package com.outworkers.phantom.builder.query.execution

import scala.concurrent.ExecutionContext

/**
  * A special mini monad implementation that allows us not to have to rely on Cats being
  * part of our dependencies as it's really heavy to use for this simple reason.
  * Cats also requires binding a future monad for Scala futures against a known [[ExecutionContext]],
  * which unfortunately interferes with one of the core features in phantom, giving users the ability
  * to supply their own execution context whenever they want.
  *
  * In our implementation, we go against the grain and include the implicit [[ExecutionContext]] as part
  * of the standard method signature for map and flatMap, and this is only because we want to keep enabling users
  * to supply their own context. Certain implementations of Futures will downright ignore this implicit parameter,
  * but it's there for the implementations of Future and Promise that need it, specifically Scala Standard Lib
  * [[scala.concurrent.Future]] and [[scala.concurrent.Promise]].
  *
  * Cats is a much better library in any conceivable way, and while we are not trying to reinvent category theory,
  * it's too heavy of a dependency to add for the sake of a single simple typeclass.
  *
  * @tparam F The type of the Future implementation for which we implement map and flatMap.
  */
trait FutureMonad[F[_]] {

  def pure[A](source: A): F[A]

  def map[A, B](source: F[A])(f: A => B)(
    implicit ctx: ExecutionContext
  ): F[B]

  def flatMap[A, B](source: F[A])(fn: A => F[B])(
    implicit ctx: ExecutionContext
  ): F[B]
}

object FutureMonadOps {
  implicit class Ops[F[_], A](val source: F[A])(implicit monad: FutureMonad[F]) {
    def map[B](f: A => B)(
      implicit ctx: ExecutionContext
    ): F[B] = monad.map(source)(f)

    def flatMap[B](fn: A => F[B])(
      implicit ctx: ExecutionContext
    ): F[B]= monad.flatMap(source)(fn)
  }
}


text:
<?php

/**
 * Get a service by its name
 *
 * _Example:_
 *
 * $forms = mc4wp('forms');
 * $api = mc4wp('api');
 *
 * When no service parameter is given, the entire container will be returned.
 *
 * @param string $service (optional)
 * @throws Exception when service is not found
 * @return object
 */
function mc4wp( $service = null ) {
	static $mc4wp;

	if( ! $mc4wp ) {
		$mc4wp = new MC4WP_Container();
	}

	if( $service ) {
		return $mc4wp->get( $service );
	}

	return $mc4wp;
}

/**
 * Gets the MailChimp for WP options from the database
 * Uses default values to prevent undefined index notices.
 *
 * @since 1.0
 * @access public
 * @staticvar array $options
 * @return array
 */
function mc4wp_get_options() {
	static $options;

	if( ! $options ) {
		$defaults = require MC4WP_PLUGIN_DIR . 'config/default-settings.php';
		$options = (array) get_option( 'mc4wp', array() );
		$options = array_merge( $defaults, $options );
	}

	/**
	 * Filters the MailChimp for WordPress settings (general).
	 *
	 * @param array $options
	 */
	return apply_filters( 'mc4wp_settings', $options );
}

/**
 * Gets the MailChimp for WP API class and injects it with the API key
 *
 * @staticvar $instance
 *
 * @since 1.0
 * @access public
 *
 * @return MC4WP_API
 */
function mc4wp_get_api() {
	$opts = mc4wp_get_options();
	$instance = new MC4WP_API( $opts['api_key'] );
	return $instance;
}

/**
 * Creates a new instance of the Debug Log
 *
 * @return MC4WP_Debug_Log
 */
function mc4wp_get_debug_log() {

	// get default log file location
	$upload_dir = wp_upload_dir();
	$file = trailingslashit( $upload_dir['basedir'] ) . 'mc4wp-debug.log';

	/**
	 * Filters the log file to write to.
	 *
	 * @param string $file The log file location. Default: /wp-content/uploads/mc4wp-debug.log
	 */
	$file = apply_filters( 'mc4wp_debug_log_file', $file );

	/**
	 * Filters the minimum level to log messages.
	 *
	 * @see MC4WP_Debug_Log
	 *
	 * @param string|int $level The minimum level of messages which should be logged.
	 */
	$level = apply_filters( 'mc4wp_debug_log_level', 'warning' );

	return new MC4WP_Debug_Log( $file, $level );
}

/**
 * Retrieves the URL of the current WordPress page
 *
 * @access public
 * @since 2.0
 *
 * @return  string  The current URL (escaped)
 */
function mc4wp_get_current_url() {

	global $wp;

	// get requested url from global $wp object
	$site_request_uri = $wp->request;

	// fix for IIS servers using index.php in the URL
	if( false !== stripos( $_SERVER['REQUEST_URI'], '/index.php/' . $site_request_uri ) ) {
		$site_request_uri = 'index.php/' . $site_request_uri;
	}

	// concatenate request url to home url
	$url = home_url( $site_request_uri );
	$url = trailingslashit( $url );

	return esc_url( $url );
}

/**
 * Sanitizes all values in a mixed variable.
 *
 * @access public
 *
 * @param mixed $value
 *
 * @return mixed
 */
function mc4wp_sanitize_deep( $value ) {

	if ( is_scalar( $value ) ) {
		$value = sanitize_text_field( $value );
	} elseif( is_array( $value ) ) {
		$value = array_map( 'mc4wp_sanitize_deep', $value );
	} elseif ( is_object($value) ) {
		$vars = get_object_vars( $value );
		foreach ( $vars as $key => $data ) {
			$value->{$key} = mc4wp_sanitize_deep( $data );
		}
	}

	return $value;
}

/**
 * Guesses merge vars based on given data & current request.
 *
 * @since 3.0
 * @access public
 *
 * @param array $merge_vars
 *
 * @return array
 */
function mc4wp_guess_merge_vars( $merge_vars = array() ) {

	// maybe guess first and last name
	if ( isset( $merge_vars['NAME'] ) ) {
		if( ! isset( $merge_vars['FNAME'] ) && ! isset( $merge_vars['LNAME'] ) ) {
			$strpos = strpos( $merge_vars['NAME'], ' ' );
			if ( $strpos !== false ) {
				$merge_vars['FNAME'] = trim( substr( $merge_vars['NAME'], 0, $strpos ) );
				$merge_vars['LNAME'] = trim( substr( $merge_vars['NAME'], $strpos ) );
			} else {
				$merge_vars['FNAME'] = $merge_vars['NAME'];
			}
		}
	}

	// set ip address
	if( empty( $merge_vars['OPTIN_IP'] ) ) {
		$optin_ip = mc4wp('request')->get_client_ip();

		if( ! empty( $optin_ip ) ) {
			$merge_vars['OPTIN_IP'] = $optin_ip;
		}
	}

	/**
	 * Filters merge vars which are sent to MailChimp
	 *
	 * @param array $merge_vars
	 */
	$merge_vars = (array) apply_filters( 'mc4wp_merge_vars', $merge_vars );

	return $merge_vars;
}

/**
 * Gets the "email type" for new subscribers.
 *
 * Possible return values are either "html" or "text"
 *
 * @access public
 * @since 3.0
 *
 * @return string
 */
function mc4wp_get_email_type() {

	$email_type = 'html';

	/**
	 * Filters the email type preference for this new subscriber.
	 *
	 * @param string $email_type
	 */
	$email_type = apply_filters( 'mc4wp_email_type', $email_type );

	return $email_type;
}

/**
 *
 * @ignore
 * @return bool
 */
function __mc4wp_use_sslverify() {

	// Disable for all transports other than CURL
	if( ! function_exists( 'curl_version' ) ) {
		return false;
	}

	$curl = curl_version();

	// Disable if OpenSSL is not installed
	if( empty( $curl['ssl_version'] ) ) {
		return false;
	}

	// Disable if on WP 4.4, see https://core.trac.wordpress.org/ticket/34935
	if( $GLOBALS['wp_version'] === '4.4' ) {
		return false;
	}

	return true;
}

/**
 * This will replace the first half of a string with "*" characters.
 *
 * @param string $string
 * @return string
 */
function mc4wp_obfuscate_string( $string ) {

	$length = strlen( $string );
	$obfuscated_length = ceil( $length / 2 );

	$string = str_repeat( '*', $obfuscated_length ) . substr( $string, $obfuscated_length );
	return $string;
}


text:
<!DOCTYPE html>

  {% if success %}

Thanks! successfully logged in to {{ service }}.

  {% else %}

Ouch! login to {{ service }} failed.

  {% endif %}


text:
layout: post
title: "Format 1"
excerpt: "About This Site"
categories: aboutthissite
comments: false
share: true
---

# What the hell is going on out there?

I love a good quote from Vince Lombardi.

Anyway, to answer St. Lombardi; I pretty much need a creative outlet to let my inner-bloviator run rampant.

So without further ado, here is a quick description of each page:

## Global

My thoughts and takes on things that relate to all things around this great big blue marble I like to call 'Earth'. Updated bi-weekly.

## National

My State of the Union done every week. Warning: this page may inspire a lot of ire. Reader beware! Updated bi-weekly.

## Local

Interesting things happening in Seattle. Updated bi-weekly.

## Personal

Inner thoughts and stories that others may relate to. Updated bi-weekly.

## Sports

My true expertise lies in this arena. I'll try to limit my know-it-all qualities to make it more readable. Eh, no I won't. Updated bi-weekly.

## Pop Culture

Pretty much me telling you what to watch, listen to, etc. Wow, I sound like my mom. Updated bi-weekly.

## Beer

In all honestly, this section will be the most informative. My friend Josh and I try as many as 10 new beers a week and rate them. Hopefully this may inspire a more in depth blog than just a simple page on a personal website, but for now this will do. Again, beer lovers who live in Seattle can get something out of this section. Updated weekly.

## Top 10s

A little flavor of my tastes in a myriad of subjects.

## About Me

My bio

## Plans

So the plan is to update these sections bi-weekly (twice a week). Monday will be Global/Personal, Tuesday will be National/Sports, Wednesday will be Local/Pop Culture, Thursday will be Global/National/Local, Friday will be Personal/Sports/Pop Culture. Weekend will be the Beer. Let's see how long this lasts.


text:
import os
import sys

sys.path.insert(0, os.path.abspath("../cxroots"))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    "nbsphinx",
    "sphinx.ext.autodoc",
    "sphinx.ext.doctest",
    "sphinx.ext.todo",
    "sphinx.ext.coverage",
    "sphinx.ext.mathjax",
    "sphinx.ext.viewcode",
    "sphinx.ext.githubpages",
    "sphinx.ext.napoleon",
    "sphinx.ext.autosectionlabel",
    "sphinx.ext.intersphinx",
    "sphinxcontrib.programoutput",
    "sphinxcontrib.bibtex",
    "sphinx_github_changelog",
    "matplotlib.sphinxext.plot_directive",
    "IPython.sphinxext.ipython_directive",
    "IPython.sphinxext.ipython_console_highlighting",
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# The suffix(es) of source filenames.
source_suffix = [".rst"]

# The master toctree document.
master_doc = "index"

# General information about the project.
project = "cxroots"
copyright = "2017, Robert Parini"
author = "Robert Parini"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
with open("../cxroots/version.py") as f:
    exec(f.read())
version = __version__
# The full version, including alpha/beta/rc tags.
release = version

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = "en"

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "**.ipynb_checkpoints"]

pygments_style = "sphinx"
autosectionlabel_prefix_document = True
bibtex_bibfiles = ["refs.bib"]

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_rtd_theme"

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ['_static']

# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = "cxrootsdoc"

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    # 'papersize': 'letterpaper',
    # The font size ('10pt', '11pt' or '12pt').
    #
    # 'pointsize': '10pt',
    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',
    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (master_doc, "cxroots.tex", "cxroots Documentation", "Robert Parini", "manual"),
]

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [(master_doc, "cxroots", "cxroots Documentation", [author], 1)]

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (
        master_doc,
        "cxroots",
        "cxroots Documentation",
        author,
        "cxroots",
        "One line description of project.",
        "Miscellaneous",
    ),
]

intersphinx_mapping = {
    "numpy": ("http://docs.scipy.org/doc/numpy/", None),
    "matplotlib": ("http://matplotlib.org", None),
    "scipy": ("http://docs.scipy.org/doc/scipy/reference", None),
    "numdifftools": (
        "http://numdifftools.readthedocs.io/en/latest",
        None,
    ),  # XXX: Not working
}


text:
cd $TRAVIS_BUILD_DIR
npm run-script build


text:
package org.apache.ambari.funtest.server.api.service;

import org.apache.ambari.funtest.server.AmbariHttpWebRequest;
import org.apache.ambari.funtest.server.ConnectionParams;

/**
 * Deletes the specified service from the specified cluster.
 */
public class DeleteServiceWebRequest extends AmbariHttpWebRequest {
    private String clusterName;
    private String serviceName;
    private static String pathFormat = "/api/v1/clusters/%s/services/%s";

    /**
     * Deletes a service from a cluster.
     *
     * @param params - Ambari server connection information
     * @param clusterName - Cluster from where the service is to be deleted.
     * @param serviceName - Service to be deleted.
     */
    public DeleteServiceWebRequest(ConnectionParams params, String clusterName, String serviceName) {
        super(params);
        this.clusterName = clusterName;
        this.serviceName = serviceName;
    }

    public String getClusterName() {
        return this.clusterName;
    }

    public String getHostName() {
        return this.serviceName;
    }

    @Override
    public String getHttpMethod() {
        return "DELETE";
    }

    /**
     * Get REST API path fragment for construction full URI.
     *
     * @return - REST API path
     */
    @Override
    protected String getApiPath() {
        return String.format(pathFormat, clusterName, serviceName);
    }
}


text: angular.module('player', []);


text:
namespace Services
{
    using System.Linq;

    using Data.Contracts;

    using Models.Content;

    using Contracts;

    public class CommentService : BaseService<Comment>, ICommentService
    {
        public CommentService(IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {
        }

        public IQueryable<Comment> GetLatestCommentsForAPost(int postId, int count, int page = 1)
        {
            return this.GetDataWithPaging(this.GetLatestCommentsForAPost(postId), count, page);
        }

        public IQueryable<Comment> GetLatestCommentsForAPost(int postId)
        {
            return this.DataSet.Where(comment => comment.PostId == postId).OrderByDescending(comment => comment.CreatedOn);
        }

        public IQueryable<Comment> GetLatestComments(int count, int page = 1)
        {
            return this.GetDataWithPaging(this.DataSet.OrderByDescending(comment => comment.CreatedOn), count, page);
        }
    }
}


text:
package org.fakekoji.core;

import org.fakekoji.core.ProjectMapping;
import org.fakekoji.core.ProjectMappingExceptions;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

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

import static org.junit.Assert.assertEquals;

public class ProjectMappingTest {

    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    private static final List<String> products = Arrays.asList(
            "java-X-openjdk",
            "java-openjdk",
            "java-10-openjdk",
            "java-9-openjdk",
            "java-1.8.0-openjdk",
            "java-1.7.0-openjdk"
    );

    private static final List<String> projects = Arrays.asList(
            "java-10-openjdk",
            "java-1.7.0-openjdk",
            "java-1.7.0-openjdk-forest",
            "java-1.7.0-openjdk-forest-26",
            "java-1.8.0-openjdk",
            "java-1.8.0-openjdk-aarch64",
            "java-1.8.0-openjdk-aarch64-shenandoah",
            "java-1.8.0-openjdk-dev",
            "java-1.8.0-openjdk-shenandoah",
            "java-9-openjdk",
            "java-9-openjdk-dev",
            "java-9-openjdk-shenandoah",
            "java-9-openjdk-updates",
            "java-X-openjdk"
    );

    private static final List<String> nvras = Arrays.asList(
            "java-X-openjdk-jdk.11.4-50.upstream.src.tarxz",
            "java-10-openjdk-jdk.10.46-0.static.x86_64.tarxz",
            "java-1.8.0-openjdk-aarch64.jdk8u152.b16-6.aarch64.static.x86_64.tarxz",
            "java-1.8.0-openjdk-aarch64.shenandoah.jdk8u141.b16.shenandoah.merge.2017.07.27.02-0.aarch64.shenandoah.static.x86_64.tarxz",
            "java-1.7.0-openjdk-icedtea.2.7.0pre10-3.forest.static.x86_64.tarxz",
            "java-1.7.0-openjdk-icedtea.2.6.12-134.forest.26.static.x86_64.tarxz",
            "java-openjdk-10.0.0.46-8.fc27.x86_64.rpm",
            "java-9-openjdk-jdk.9.181-794.shenandoah.static.fastdebug.aarch64.tarxz",
            "java-10-openjdk-jdk.10.46-0.static.fastdebug.i686.tarxz",
            "java-X-openjdk-jdk.11.2-52.static.fastdebug.x86_64.tarxz",
            "java-9-openjdk-9.0.1.11-2.el7.x86_64.rpm",
            "java-9-openjdk-jdk.9.165-31.shenandoah.static.x86_64.tarxz",
            "java-1.8.0-openjdk-jdk8u162.b01-2.static.fastdebug.i686.tarxz",
            "java-1.7.0-openjdk-jdk7u161.b01-0.static.fastdebug.i686.tarxz",
            "java-X-openjdk-jdk.12.13-69.static.x86_64.tarxz"
    );

    @Test
    public void getProjectOfNvraTest() throws ProjectMappingExceptions.ProjectMappingException {
        final List<String> expectedProjects = Arrays.asList(
                "java-X-openjdk",
                "java-10-openjdk",
                "java-1.8.0-openjdk-aarch64",
                "java-1.8.0-openjdk-aarch64-shenandoah",
                "java-1.7.0-openjdk-forest",
                "java-1.7.0-openjdk-forest-26",
                "java-10-openjdk",
                "java-9-openjdk-shenandoah",
                "java-10-openjdk",
                "java-X-openjdk",
                "java-9-openjdk",
                "java-9-openjdk-shenandoah",
                "java-1.8.0-openjdk",
                "java-1.7.0-openjdk",
                "java-X-openjdk"
        );

        ProjectMapping projectMapping = createProjectMapping();
        List<String> actualProjects = new ArrayList<>();
        for (String nvra : nvras) {
            actualProjects.add(projectMapping.getProjectOfNvra(nvra, projects));
        }
        actualProjects.sort(String::compareTo);
        expectedProjects.sort(String::compareTo);
        assertEquals("The actual list of projects doesn\'t match the expected", expectedProjects, actualProjects);
    }

    @Test
    public void getProductOfNvraTest() throws ProjectMappingExceptions.ProjectMappingException {
        final List<String> expectedProducts = Arrays.asList(
                "java-X-openjdk",
                "java-10-openjdk",
                "java-1.8.0-openjdk",
                "java-1.8.0-openjdk",
                "java-1.7.0-openjdk",
                "java-1.7.0-openjdk",
                "java-openjdk",
                "java-9-openjdk",
                "java-10-openjdk",
                "java-X-openjdk",
                "java-9-openjdk",
                "java-9-openjdk",
                "java-1.8.0-openjdk",
                "java-1.7.0-openjdk",
                "java-X-openjdk"
        );

        ProjectMapping projectMapping = createProjectMapping();
        List<String> actualProducts = new ArrayList<>();
        for (String nvra : nvras) {
            actualProducts.add(projectMapping.getProductOfNvra(nvra, products));
        }
        actualProducts.sort(String::compareTo);
        expectedProducts.sort(String::compareTo);
        assertEquals("The actual list of products doesn\'t match the expected", expectedProducts, actualProducts);

        expectedException.expect(ProjectMappingExceptions.ProductOfNvraNotFoundException.class);
        projectMapping.getProductOfNvra("wrong nvra", products);
    }

    @Test
    public void getProductOfProjectTest() throws ProjectMappingExceptions.ProjectMappingException {
        final List<String> expectedProductsOfProjects = Arrays.asList(
                "java-10-openjdk",
                "java-1.7.0-openjdk",
                "java-1.7.0-openjdk",
                "java-1.7.0-openjdk",
                "java-1.8.0-openjdk",
                "java-1.8.0-openjdk",
                "java-1.8.0-openjdk",
                "java-1.8.0-openjdk",
                "java-1.8.0-openjdk",
                "java-9-openjdk",
                "java-9-openjdk",
                "java-9-openjdk",
                "java-9-openjdk",
                "java-X-openjdk"
        );

        ProjectMapping projectMapping = createProjectMapping();
        List<String> actualProducts = new ArrayList<>();
        for (String project : projects) {
            actualProducts.add(projectMapping.getProductOfProject(project, products, projects));
        }
        actualProducts.sort(String::compareTo);
        expectedProductsOfProjects.sort(String::compareTo);
        assertEquals("The actual list of products doesn\'t match the expected", expectedProductsOfProjects, actualProducts);

        expectedException.expect(ProjectMappingExceptions.ProjectNotFoundException.class);
        projectMapping.getProductOfProject("wrong project", products, projects);
    }

    private ProjectMapping createProjectMapping() {
        return new ProjectMapping(null) {
            @Override
            public List<String> getAllProducts() {
                return products;
            }

            @Override
            public List<String> getAllProjects() {
                return projects;
            }
        };
    }
}