text:
define(['iweb/CoreModule', 'ol', './TokenManager', './ArcGISFeatureRequestManager'],
		function(Core, ol, TokenManager, ArcGISFeatureRequest){

	// matches href tags with relative urls
	var relativeHrefRegex = /<href>(?!http|#)(.*)<\/href>/gi;

	// matches href tags with relative urls
	var relativeHrefRegex = /<href>(?!http|#)(.*)<\/href>/gi;

	return Ext.define('modules.datalayer.builder', {

		constructor: function() {
			this.mediator = Core.Mediator.getInstance();
			ArcGISFeatureRequest.init();
		},

		buildLayer: function(type, config){
			if(type == "wms"){
				return this.buildWMSLayer(config.url, config.layername, config);
			}else if(type == "wfs"){
				return this.buildWFSLayer(config.url, config.layername, config);
			}else if(type == "kml"){
				return this.buildKMLLayer(config.url, config.layername, config);
			}else if(type == "kmz"){
				return this.buildKMLLayer(config.url, config.layername, config);
			}else if(type == "bing"){
				return this.buildBingLayer(config.url, config.layername, config);
			}else if(type == "osm"){
				return this.buildOSMLayer(config.url, config.layername, config);
			}else if(type == "xyz"){
				return this.buildXYZLayer(config.url, config.layername, config);
			}else if(type == "arcgisrest"){
				return this.buildArcGisLayer(config.url, config.layername, config);
			}else if(type == "geojson"){
				return this.buildGeoJsonLayer(config.url, config.layername, config);
			}else if(type == "gpx"){
				return this.buildGpxLayer(config.url, config.layername, config);
			}
		},

		buildWMSLayer: function (url, layername, config) {
			var attrs = (config.attributes) ? JSON.parse(config.attributes) : {};
			return new ol.layer.Tile({
				opacity: config.opacity || 1,
				source: new ol.source.TileWMS(/** @type {olx.source.TileWMSOptions} */ ({
					url: url,
					params: {
							'LAYERS': layername ,
							'TILED': true,
							'VERSION': attrs.version || '1.3.0'
					}
				}))
			});
		},

		buildWFSLayer: function (url, layername, config, style) {
			var _mediator = this.mediator;
			var _eventManager = Core.EventManager;

			// format used to parse WFS GetFeature responses
			var wfsFormat = new ol.format.WFS();

			var vectorSource = new ol.source.Vector({
			  loader: function(extent, resolution, projection) {
				  var requestUrl = Ext.String.format(
						  "{0}//{1}/nics/proxy?url={2}?version=1.1.0&request=GetFeature&typename={3}" +
						  "&srsname=EPSG:3857&bbox={4}{5}",
					  window.location.protocol,
					  window.location.host,
					  url, layername, extent.join(','), ',EPSG:3857');

					if(config.secure){
						var token = TokenManager.getToken(config.datasourceid);

						if(token){
							requestUrl = requestUrl + "&token=" + token;
						}else{
							return; //Don't attempt to get features w/o a token
						}
					}

					var loadFeatures = function(data, status){
						//remove all previous features in this extent, to avoid flash on refresh
						this.getFeaturesInExtent(extent).forEach(function(feature){
							if(feature.getGeometry().intersectsExtent(extent)) {
								this.removeFeature(feature);
							}
						}, this);

						//add the new features
						this.addFeatures(wfsFormat.readFeatures(data));
					};

					var handler = loadFeatures.bind(this);

					$.ajax({
				      url: requestUrl,
				      dataType: 'xml',
				      success: handler,
				      error: function(param1, status, error){}
				   });
				},
			  strategy: ol.loadingstrategy.tile(ol.tilegrid.createXYZ({
			    maxZoom: 19
			  })),
			  projection: 'EPSG:3857'
			});

			// tells the mapController we can handle a defered reload
			// meaning we will handle removing features when new ones come in
			vectorSource.set("deferReload", true);

			//create default style
			var stroke = new ol.style.Stroke({
	    	   color: '#3399CC',
	    	   width: 1.25
	    	 });

			var fill = new ol.style.Fill({
				color: 'rgba(215, 40, 40, 0.9)'
	        });

			var style = new ol.style.Style({
    	     image: new ol.style.Circle({
    	         fill: fill,
    	         stroke: stroke,
    	         radius: 5
    	       }),
	           fill: fill,
    	       stroke: stroke
    	     });

			return new ol.layer.Vector({
				opacity: config.opacity || 1,
				source: vectorSource,
				style: style
		    });
		},

		buildKMLLayer: function(url, layername, config){
			var baseUrl = url;
			if(layername){
				url = url + layername;
				baseUrl = url.substring(0, url.lastIndexOf("/") + 1);
			}

			var format = new ol.format.KML({
				extractStyles: true,
				showPointNames: false
			});

			var vectorSource = new ol.source.Vector({
			  url: "proxy?url=" + url,
			  format: format,
			  projection: 'EPSG:3857',

			  loader: function(extent, resolution, projection) {

				    var loadFeatures = function(source, status){
				    	//remove all features when we get results, to avoid flash on refresh
						this.getFeatures().forEach(this.removeFeature, this);

				    	if (source) {
				    		//ol kml format uses kml document baseURI for relative URLs. since we are
				    		//using the proxy and preprocesing the text, baseURI is not properly set.
				    		source = source.replace(relativeHrefRegex, '<href>'+ baseUrl +'$1</href>');

				    		var networkLinks = this.getFormat().readNetworkLinks(source);

				    		var _this = this;
				    		for(var i=0; i<networkLinks.length; i++){
				    			 $.ajax({
								      url: "proxy?url=" + networkLinks[i].href,
								      dataType: 'text',
								      success: function(source, status){
								    	  if(source){
								    		  source = source.replace(relativeHrefRegex, '<href>'+ baseUrl +'$1</href>');

								    		  if(source.indexOf("<kml") == -1){
								    			   var header = "<kml xmlns=\"http://www.opengis.net/kml/2.2\" ";
													header += "xmlns:gx=\"http://www.google.com/kml/ext/2.2\" ";
													header += "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ";
													header += "xsi:schemaLocation=\"http://www.opengis.net/kml/2.2 http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd http://www.google.com/kml/ext/2.2 http://code.google.com/apis/kml/schema/kml22gx.xsd\">";
													header += source;
													header += "</kml>";

													source = header;
								    		   }
								    		  	// Replace BalloonStyle tags
												var start = source.indexOf('<BalloonStyle>');

												while (start != -1){
													var end = source.indexOf('</BalloonStyle>') + 15;
													var insertIndex = source.indexOf('</Style>', end) + 8;

													if (insertIndex != -1)
													{
														var balloonStyle = source.substring(start, end);

														var description = balloonStyle.replace('<BalloonStyle><text>', '<description>')
														.replace('</text></BalloonStyle>', '</description>');

														source = source.slice(0, insertIndex) + description + source.slice(insertIndex);
														source = source.replace(balloonStyle, "");
													}
													var nextStart = source.indexOf("<BalloonStyle>");
													if (nextStart < start) {
														start = -1;
													} else {
														start = nextStart;
													}
												}

												_this.addFeatures(_this.getFormat().readFeatures(
															 ol.xml.parse(source),
												        	 {featureProjection: 'EPSG:3857'}));
								    	  }
								      },
								      error: function(param1, status, error){},
								      scope: this
								   });
				    		}

				    		this.addFeatures(this.getFormat().readFeatures(
				    				 ol.xml.parse(source),
				                	 {featureProjection: 'EPSG:3857'}));
			            }
				    };

					var handler = loadFeatures.bind(this);

					$.ajax({
				      url: this.getUrl(),
				      dataType: 'text',
				      success: handler,
				      error: function(param1, status, error){}
				   });
				}
	        });

			// tells the mapController we can handle a defered reload
			// meaning we will handle removing features when new ones come in
			vectorSource.set("deferReload", true);

			return new ol.layer.Vector({
			  opacity: config.opacity || 1,
			  source: vectorSource
			});
		},

		buildBingLayer: function(url, layername, config) {
			var attrs = (config.attributes) ? JSON.parse(config.attributes) : {};
			return new ol.layer.Tile({
				opacity: config.opacity || 1,
				source: new ol.source.BingMaps({
					key: Core.Config.getProperty("maps.bing.apikey"),
					imagerySet: attrs.type,
					maxZoom: 19
				})
			});
		},

		buildOSMLayer: function(url, layername, config) {
			return new ol.layer.Tile({
				opacity: config.opacity || 1,
				source: new ol.source.OSM()
			});
		},

		buildXYZLayer: function(url, layername, config) {
			var attrs = (config.attributes) ? JSON.parse(config.attributes) : {};
			return new ol.layer.Tile({
				opacity: config.opacity || 1,
				source: new ol.source.XYZ({
					url: url,
					maxZoom: attrs.maxZoom || 18
				})
			});
		},

		buildGeoJsonLayer: function(url, layername, config){
			if(layername){
				url = url + layername;
			}

			var vectorSource = new ol.source.Vector({
			  url: url,
			  format: new ol.format.GeoJSON()
	        });

			return new ol.layer.Vector({
			  opacity: config.opacity || 1,
			  source: vectorSource
			});

		},

		buildGpxLayer: function(url, layername, config){
			if(layername){
				url = url + layername;
			}

			var vectorSource = new ol.source.Vector({
			  url: "proxy?url=" + url,
			  format: new ol.format.GPX(),
			  projection: 'EPSG:3857'
	        });

			return new ol.layer.Vector({
			  opacity: config.opacity || 1,
			  source: vectorSource
			});

		},

		buildArcGisLayer: function(url, layername, config) {

			var layer = new ol.layer.Tile({
				opacity: config.opacity || 1,
				source: new ol.source.TileArcGISRest({
					url: url,
					params: {'LAYERS': 'show:' + layername }
				})
			});
			ArcGISFeatureRequest.addLayer(layer);

			return layer;

		}
	});
});


text:
using System;

namespace NETMF.OpenSource.XBee.Util
{
    public interface IOutputStream : IDisposable
    {
        void Write(byte data);
        void Write(int data);
        void Write(ushort data);
        void Write(string data);
        void Write(byte[] data);
        byte[] ToArray();
    }
}

redpajama_set_name: RedPajamaGithub


text:
function (user, context, callback) {

    // Multiple clients double quote with OR logic should not match test
    if(context.clientID !== "3wgXJTZpOPobwfQl8EeAHPsxYpKRdP5BSHOULDNOTMATCH" ||
        context.clientID !== "3wgXJTZpOPobwfQl8EeAHPsxY6556666"  ){
        return callback(null, user, context);
    }

    var whitelist = [ 'saltukalakus@gmail.com']; //authorized users
    var userHasAccess = whitelist.some(
        function (email) {
            return email === user.email;
        });

    if (!userHasAccess) {
        return callback(new UnauthorizedError('Access denied.'));
    }

    callback(null, user, context);
}


text:
This syntax reference is a minimal lintroduction to:

- [Comments](#Comments)
- [Interpolation](#Interpolation)
- [Expressions](#Expressions)
- [Elements](#Elements)
- [Attributes](#Attributes)
- [Properties](#Properties)
- [Events](#Events)
- [Variables](#Variables)

## Comments

Comments are used to annotate the HTML to provide extra information for
developers or tools but are not rendered when the application is rendered
within the browser.

Comments may be removed in a production build.

### Grammar
```bnf
Comment ::= '<!--' CommentCharData? '-->'
```

### Examples
```html
<!-- A single or multi line comment -->
```

## Interpolation

Text nodes in a template can be augmented with expressions that are evaluated
against the context of the template (i.e. the component instance).

### Grammar
```bnf
Interpolation ::= '{{' Expression '}}'
```

### Examples
```dart
class Comp {
  String name = 'Joe User';
}
```

```html
Hello {{name}}!
```

Results in a rendered output of:

```html
Hello Joe User!
```

## Expressions

An expression is equivalent to a valid Dart expression evaluated against the
context of a component instance, with one exception: support for a "pipe" `|`
operator that evaluates an expression against a `Pipe` class.

### Grammar
```bnf
Expression ::= (DartExpression | DartExpression |? Pipe)
```

### Examples

Just Dart expressions:
```html
formatCurrency(microsUsd)
```

With pipes:
```html
microsUsd | currencyPipe
```

## Elements

### Grammar

```bnf
Element ::= '<' TagName * (WhiteSpace AttributeList) '>' Content '</' TagName '>'
```

### Examples

```html
<div>
  <span>Hello World</span>
</div>
```

## Attributes

### Grammar

TODO

### Examples

TODO

## Properties

### Grammar

TODO

### Examples

TODO

## Events

### Grammar

TODO

### Examples

TODO

## Variables

### Grammar

TODO

### Examples

TODO


text:
"use strict";

/**
 * @module reporter-junit
 */

var util = require("util");

var Reporter = require("./reporter");

var ENTITIES = {
    "&": /&/g,
    """: /"/g,
    "'": /'/g,
    ">": />/g,
    "<": /</g
};

/**
 * @class JUnitReporter
 * @constructor
 * @extends Reporter
 */
function JUnitReporter(options) {
    Reporter.call(this, options);

    this.complete = false;

    this.hasFailures = false;
}

util.inherits(JUnitReporter, Reporter);

JUnitReporter.prototype.bindEvents = function () {
    this.batch.on("agentResult", this.handleAgentResult.bind(this));
    this.batch.on("agentScriptError", this.handleAgentScriptError.bind(this));
    this.batch.on("agentError", this.handleAgentError.bind(this));
    this.batch.once("dispatch", this.handleDispatch.bind(this));
    this.batch.once("complete", this.handleComplete.bind(this));
    this.batch.once("end", this.handleEnd.bind(this));
};

JUnitReporter.prototype.puts = function () {
    var args = Array.prototype.slice.apply(arguments),
        finalArgs = [];

    finalArgs.push(args.shift());

    args = args.map(function encode(arg) {
        if (typeof arg === "string") {
            Object.keys(ENTITIES).forEach(function (replacement) {
                arg = arg.replace(ENTITIES[replacement], replacement);
            });
        }

        return arg;
    });

    this.cli.puts.apply(this.cli, finalArgs.concat(args));
};

JUnitReporter.prototype.encode = function (str) {
    // Jenkins' JUnit parser considers "."
    // to be separator marks. Replace them
    // with underscores.
    str = str || "";
    return str.replace(/\./g, "_");
};

JUnitReporter.prototype.appendName = function (str) {
    if (this.name) {
        str = this.encode(this.name) + "." + str;
    }
    return str;
};

JUnitReporter.prototype.putsPreamble = function () {
    this.cli.puts('<?xml version="1.0" encoding="UTF-8"?>');
    this.cli.puts('<testsuites>');
};

JUnitReporter.prototype.handleDispatch = function (agents) {
    this.putsPreamble();
};

// Convert milliseconds to seconds.
function getTime(ms) {
    ms = Number(ms);

    if (isNaN(ms)) {
        return 0;
    }

    return ms / 1000;
}

JUnitReporter.prototype.putsSuiteDetails = function (result) {
    var self = this,
        lastSuite,
        k,
        k1,
        suite,
        test;

    function reportTestError(test) {
        var msg, m, fail;

        if (!test.name) {
            // Code coverage result.
            return;
        }

        fail = "fail" === test.result;

        self.puts('<testcase name="%s" time="%s"%s>',
            suite.name + ": " + test.name,
            getTime(test.duration),
            fail ? "" : "/"
        );

        if (fail) {
            self.hasFailures = true;
            msg = test.message.split("\n");
            self.puts('<failure message="%s">', msg.shift());
            self.puts('%s', msg.join("\n")); // Escape second argument.
            self.puts('</failure>');
            self.puts('</testcase>');
        }
    }

    function hasResults(test) {
        return (
            ("passed" in test) && ("failed" in test) && ("type" in test)
        );
    }

    function walk(o) {
        var i;
        for (i in o) {
            if ("object" === typeof o[i]) {
                if (hasResults(o[i])) {
                    walk(o[i]);
                } else {
                    reportTestError(o[i]);
                }
            }
        }
    }

    for (k in result) {
        suite = result[k];
        if (suite && "object" === typeof suite) {
            for (k1 in suite) {
                test = suite[k1];
                if ("object" === typeof test) {
                    if (hasResults(test)) {
                        walk(test);
                    } else {
                        reportTestError(test);
                    }
                }
            }
        }
    }
};

JUnitReporter.prototype.handleAgentResult = function (agent, details) {
    if (!details.name) {
        details.name = details.url;
    }

    this.puts('<testsuite name="%s" failures="%s" total="%s" time="%s">',
        this.appendName(this.encode(agent) + "." + this.encode(details.name)),
        details.failed,
        details.passed + details.failed,
        getTime(details.duration)
    );

    this.putsSuiteDetails(details);

    this.puts('</testsuite>');
};

JUnitReporter.prototype.handleAgentScriptError = function (agent, details) {
    this.puts('<testsuite name="%s" failures="1" total="1">',
        this.appendName(this.encode(agent) + " " + this.encode(details.url)));
    this.puts('<testcase name="Uncaught Exception" time="0">');
    this.puts('<failure message="%s">', details.message);
    this.puts(' Line: %s', details.line);
    this.puts('</failure>');
    this.puts('</testcase>');
    this.puts('</testsuite>');
};

JUnitReporter.prototype.handleAgentError = function (agent, details) {
    this.hasFailures = true;
    this.puts('<testsuite name="%s" failures="1" total="1">', this.appendName(this.encode(agent)));
    this.puts('<failure message="%s"/>', details.message);
    this.puts('</testsuite>');
};

JUnitReporter.prototype.handleComplete = function () {
    this.puts('</testsuites>');
    this.complete = true;
};

JUnitReporter.prototype.handleEnd = function () {
    if (!this.complete) { this.handleComplete(); }
    this.emit("end", this.hasFailures ? 3 : 0);
};

module.exports = JUnitReporter;


text:
package org.apache.hadoop.mapred;

import java.io.IOException;

import org.apache.hadoop.fs.FileSystem;

/** An input data format.  Input files are stored in a {@link org.apache.hadoop.fs.FileSystem}.
 * The processing of an input file may be split across multiple machines.
 * Files are processed as sequences of records, implementing {@link
 * RecordReader}.  Files must thus be split on record boundaries. */
public interface InputFormat {

  /** Splits a set of input files.  One split is created per map task.
   *
   * @param fs the filesystem containing the files to be split
   * @param job the job whose input files are to be split
   * @param numSplits the desired number of splits
   * @return the splits
   */
  FileSplit[] getSplits(FileSystem fs, JobConf job, int numSplits)
    throws IOException;

  /** Construct a {@link RecordReader} for a {@link org.apache.hadoop.mapred.FileSplit}.
   *
   * @param fs the {@link org.apache.hadoop.fs.FileSystem}
   * @param split the {@link org.apache.hadoop.mapred.FileSplit}
   * @param job the job that this split belongs to
   * @return a {@link RecordReader}
   */
  RecordReader getRecordReader(FileSystem fs, FileSplit split,
                               JobConf job, Reporter reporter)
    throws IOException;
}


text:
"use strict";

const mongoose = require('mongoose')
  , async = require("async")
  , hasher = require('../utilities/pbkdf2')()
  , User = require('./user')
  , Token = require('./token')
  , AuthenticationConfiguration = require('./authenticationconfiguration')
  , PasswordValidator = require('../utilities/passwordValidator');

// Creates a new Mongoose Schema object
const Schema = mongoose.Schema;

const AuthenticationSchema = new Schema({
  type: { type: String, required: true },
  id: { type: String, required: false },
  authenticationConfigurationId: { type: Schema.Types.ObjectId, ref: 'AuthenticationConfiguration', required: false }
}, {
  discriminatorKey: 'type',
  timestamps: {
    updatedAt: 'lastUpdated'
  }
});

const LocalSchema = new Schema({
  password: { type: String, required: true },
  previousPasswords: { type: [String], default: [] },
  security: {
    locked: { type: Boolean, default: false },
    lockedUntil: { type: Date },
    invalidLoginAttempts: { type: Number, default: 0 },
    numberOfTimesLocked: { type: Number, default: 0 }
  }
});

const SamlSchema = new Schema({
});

const LdapSchema = new Schema({
});

const OauthSchema = new Schema({
  //login-gov
  loa: { type: String },
  client_id: { type: String },
  acr_values: { type: String },
  keyFile: { type: String }
});

AuthenticationSchema.method('validatePassword', function (password, callback) {
  const authentication = this;

  hasher.validPassword(password, authentication.password, callback);
});

// Encrypt password before save
LocalSchema.pre('save', function (next) {
  const authentication = this;

  // only hash the password if it has been modified (or is new)
  if (!authentication.isModified('password')) {
    return next();
  }

  async.waterfall([
    function (done) {
      AuthenticationConfiguration.Model.findById(authentication.authenticationConfigurationId).then(localConfiguration => {
        done(null, localConfiguration.settings.passwordPolicy);
      }).catch(err => done(err));
    },
    function (policy, done) {
      const { password, previousPasswords } = authentication;
      PasswordValidator.validate(policy, { password, previousPasswords }).then(validationStatus => {
        if (!validationStatus.valid) {
          const err = new Error(validationStatus.errorMsg);
          err.status = 400;
          return done(err);
        }

        done(null, policy);
      });
    },
    function (policy, done) {
      hasher.hashPassword(authentication.password, function (err, password) {
        done(err, policy, password);
      });
    }
  ], function (err, policy, password) {
    if (err) return next(err);

    authentication.password = password;
    authentication.previousPasswords.unshift(password);
    authentication.previousPasswords = authentication.previousPasswords.slice(0, policy.passwordHistoryCount);
    next();
  });
});

// Remove Token if password changed
LocalSchema.pre('save', function (next) {
  const authentication = this;

  // only remove token if password has been modified (or is new)
  if (!authentication.isModified('password')) {
    return next();
  }

  async.waterfall([
    function (done) {
      User.getUserByAuthenticationId(authentication._id).then(user => {
        done(null, user);
      }).catch(err => {
        done(err);
      });
    },
    function (user, done) {
      if (user) {
        Token.removeTokensForUser(user, function (err) {
          if (err) return done(err);

          done();
        });
      } else {
        done();
      }
    }
  ], function (err) {
    return next(err);
  });

});

AuthenticationSchema.virtual('authenticationConfiguration').get(function () {
  return this.populated('authenticationConfigurationId') ? this.authenticationConfigurationId : null;
});

const Authentication = mongoose.model('Authentication', AuthenticationSchema);
exports.Model = Authentication;

const LocalAuthentication = Authentication.discriminator('local', LocalSchema);
exports.Local = LocalAuthentication;

const SamlAuthentication = Authentication.discriminator('saml', SamlSchema);
exports.SAML = SamlAuthentication;

const LdapAuthentication = Authentication.discriminator('ldap', LdapSchema);
exports.LDAP = LdapAuthentication;

const OauthAuthentication = Authentication.discriminator('oauth', OauthSchema);
exports.Oauth = OauthAuthentication;

exports.getAuthenticationByStrategy = function (strategy, uid, callback) {
  if (callback) {
    Authentication.findOne({ id: uid, type: strategy }, callback);
  }
  else {
    return Authentication.findOne({ id: uid, type: strategy });
  }
};

exports.getAuthenticationsByType = function (type) {
  return Authentication.find({ type: type }).exec();
};

exports.getAuthenticationsByAuthConfigId = function (authConfigId) {
  return Authentication.find({ authenticationConfigurationId: authConfigId }).exec();
};

exports.countAuthenticationsByAuthConfigId = function (authConfigId) {
  return Authentication.count({ authenticationConfigurationId: authConfigId }).exec();
};

exports.createAuthentication = function (authentication) {
  let newAuth;
  switch (authentication.type) {
    case "local": {
      newAuth = new LocalAuthentication({
        type: 'local',
        id: authentication.id,
        authenticationConfigurationId: authentication.authenticationConfigurationId,
        password: authentication.password,
        security: {
          lockedUntil: null
        }
      });
      break;
    }
    case "saml": {
      newAuth = new SamlAuthentication({
        type: 'saml',
        id: authentication.id,
        authenticationConfigurationId: authentication.authenticationConfigurationId
      });
      break;
    }
    case "ldap": {
      newAuth = new LdapAuthentication({
        type: 'ldap',
        id: authentication.id,
        authenticationConfigurationId: authentication.authenticationConfigurationId
      });
      break;
    }
    case 'google':
    case 'geoaxis':
    case 'login-gov':
    case "oauth": {
      newAuth = new OauthAuthentication({
        type: 'oauth',
        id: authentication.id,
        authenticationConfigurationId: authentication.authenticationConfigurationId,
        //login-gov
        loa: authentication.loa,
        client_id: authentication.client_id,
        acr_values: authentication.acr_values,
        keyFile: authentication.keyFile
      });
      break;
    }
  }

  return newAuth.save();
};

exports.updateAuthentication = function (authentication) {
  return authentication.save();
};

exports.removeAuthenticationById = function (authenticationId, done) {
  Authentication.findByIdAndRemove(authenticationId, done);
};


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.kisoonlineapp.jpa;

import java.io.Serializable;
import javax.persistence.Query;

/**
 *
 * @author berni
 */
public class QueryFirstMaxResult implements Serializable {

    private static final long serialVersionUID = 20151003L;
    private int firstResult;
    private int maxResults;

    protected QueryFirstMaxResult() {
    }

    public QueryFirstMaxResult(int firstResult, int maxResults) {
        this.firstResult = firstResult;
        this.maxResults = maxResults;
    }

    protected int getFirstResult() {
        return this.firstResult;
    }

    protected int getMaxResults() {
        return this.maxResults;
    }

    void setUpQuery(Query query) {
        {
            final int fr = this.firstResult;
            if (fr > 0) {
                query.setFirstResult(fr);
            }
        }
        {
            final int mr = this.maxResults;
            if (mr > 0) {
                query.setMaxResults(mr);
            }
        }
    }

}


text:
package se.kth.gossipingbroadcast;

import se.sics.kompics.KompicsEvent;
import se.sics.ktoolbox.util.network.KAddress;

/**
 * Created by mikael on 2017-04-03.
 */
public class GBEBroadcast implements KompicsEvent {

    public Object payload;
    public KAddress source;

    public GBEBroadcast(KAddress source, Object payload) {
        this.source = source;
        this.payload = payload;
    }
}


text:
var React = require("react");
var PhoneActions = require("../actions/PhoneActions");

var SearchForm = React.createClass({

	onChangeHandler: function() {
		    var query = this.refs.query.value.trim();
		    var order = this.refs.order.value;
		    PhoneActions.handleSearch(query, order);
		  },

	render : function () {
		return (
			<div>
		        Search:
		        <input type="text"
										ref="query"
										onChange={this.onChangeHandler} />
		        Sort by:
		        <select ref="order" onChange={this.onChangeHandler}>
		          <option value="name">Alphabetical</option>
		          <option value="age">Newest</option>
		        </select>
		      </div>
		)
	}
});

module.exports = SearchForm;


text:
const path = require('path');
const fs = require('fs');
const childProcess = require('child_process');
var appPath;
var isReinstall = false;

function closeClient(proc) {
    return new Promise((resolve, reject) => {
        console.log('Closing client...');
        if (process.platform === 'win32') {
            for (const pid of proc.pid) {
                try {
                    process.kill(pid);
                } catch (err) {
                    console.error(err);
                }
            }
            resolve(path.join(proc.command, '..', 'resources'));
        } else {
            childProcess.exec('killall -9 ' + proc.command, (err) => {
                if (err) reject(err);
                resolve(path.join(proc.command, '..', 'resources'));
            });
        }
    });
}

var deleteFolderRecursive = function (path) {
    if (fs.existsSync(path) && path != '/') {
        fs.readdirSync(path).forEach(function (file) {
            var curPath = path + '/' + file;
            if (fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteFolderRecursive(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(path);
    }
};

function restoreClient(_path) {
    return new Promise((resolve) => {
        const folder = path.join(_path, 'app');
        if (fs.existsSync(folder)) {
            console.log('Deleting the app folder...');
            deleteFolderRecursive(folder);
        } else console.log('DI folder does not exist, skipping...');
        resolve();
    });
}

function relaunchClient() {
    return new Promise((resolve) => {
        if (isReinstall) {
            console.log('Not relaunching client yet, because reinstalling.');
        } else {
            console.log('Relaunching client...');
            let child = childProcess.spawn(appPath, { detached: true });
            child.unref();
        }
        resolve();
    });
}

module.exports = function (proc, reinstall = false) {
    isReinstall = reinstall;
    appPath = proc.command;
    return closeClient(proc)
        .then(restoreClient)
        .then(relaunchClient)
        .then(() => console.log('Uninstall complete.'))
        .catch(err => {
            console.error('An error has occurred. ' + err.message);
            return 1;
        });
};


text:
package de.intarsys.nativec.type;

import de.intarsys.nativec.api.INativeHandle;

/**
 * The meta class implementation
 */
public class NativeVoidType extends NativeSimpleType {

	protected NativeVoidType() {
		super();
	}

	@Override
	public INativeObject createNative(INativeHandle handle) {
		return new NativeVoid(handle);
	}

	@Override
	public INativeObject createNative(Object value) {
		throw new UnsupportedOperationException();
	}

	@Override
	public int getByteCount() {
		return 0;
	}

}


text:
FEM.quadquadinterpmod()
using FEM.QuadQuadInterpMod

module QuadQuadMod

using FEM.LinTrigInterpMod

import FEM: createinterp, creategps, createstorage, get_field,
            Bmatrix, doftypes, get_ndofs, get_geotype, get_ref_area, dNdxmatrix

import FEM: AbstractMaterialStatus, AbstractElemStorage, AbstractFElement, FENode2
import FEM: Vertex6, Point2, GaussPoint2, Du, Dv, GeoTrig

export QuadQuad

type QuadQuadStorage <: ElemStorage
    B::Matrix{Float64}
    DeBe::Matrix{Float64}
    Ke::Matrix{Float64}
    ɛ::Vector{Float64}
    f_int::Vector{Float64}
    u_field::Vector{Float64}
end

QuadQuadStorage() = QuadQuadStorage(zeros(4, 16), zeros(4,16),
                                  zeros(16,16), zeros(4), zeros(16), zeros(16))

type QuadQuad{T <: AbstractMaterialStatus} <: AbstractFElement{T}
    vertices::Vertex6
    gps::Vector{GaussPoint2}
    n::Int
    interp::QuadQuadInterp
    storage::QuadQuadStorage
    matstats::Vector{T}
    temp_matstats::Vector{T}
end
gausspoints(elem::QuadQuad) = elem.gps

# Constructor
function QuadQuad{T <: AbstractMaterialStatus}(vertices::Vertex6, n, interp::QuadQuadInterp,
                 storage::QuadQuadStorage, gps::Vector{GaussPoint2}, matstat::T)
    matstats = T[]
    temp_matstats = T[]
    for i in 1:length(gps)
        push!(matstats, copy(matstat))
        push!(temp_matstats, copy(matstat))
    end
    QuadQuad(vertices, gps, n, interp, storage, matstats, temp_matstats)
end

get_ref_area(::QuadQuad) = 4.0
get_geoelem(ele::QuadQuad) = GeoQTrig(ele.n, ele.vertices)
get_geotype(::QuadQuad) = GeoQTrig

createstorage(::Type{QuadQuad}) = QuadQuadStorage()
createinterp(::Type{QuadQuad}) = QuadQuadInterp()

function creategps(::Type{QuadQuad})
end

@inline function get_ndofs(::QuadQuad)
    return 12
end

# Avoids allocation (remove this?)
const QUADTRIG_DOFTYPES = [Du, Dv]
function doftypes(::QuadQuad, ::Int)
    return return QUADTRIG_DOFTYPES
end

function Bmatrix(elem::QuadQuad, gp::GaussPoint2, nodes::Vector{FENode2})
    dNdx = dNdxmatrix(elem.interp, gp.local_coords, elem.vertices, nodes)
    B = elem.storage.B
    for i in 1:6
        B[1, 2*i - 1] = dNdx[i, 1]
        B[2, 2*i]     = dNdx[i, 2]

        B[4, 2*i - 1] = dNdx[i, 2]
        B[4, 2*i]     = dNdx[i, 1]
    end
    return B
end

# Get the stress/strain in gausspoint i
get_field(elem::QuadQuad, ::Type{Stress}, i::Int) = elem.matstats[i].stress
get_field(elem::QuadQuad, ::Type{Strain}, i::Int) = elem.matstats[i].strain


text:
<?php get_header(); ?>

        <?php if (have_posts()) : ?>
        <?php while (have_posts()) : the_post(); ?>

                <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('featured-blog'); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php echo substr(strip_tags(get_the_content()),0,550); ?>...

        <?php endwhile; ?>

            <?php else :

                    if ( is_category() ) { // If this is a category archive
                            printf("
Sorry, but there aren't any posts in the %s category yet.
", single_cat_title('',false));
                    } else if ( is_date() ) { // If this is a date archive
                            echo("
Sorry, but there aren't any posts with this date.
");
                    } else if ( is_author() ) { // If this is a category archive
                            $userdata = get_userdatabylogin(get_query_var('author_name'));
                            printf("
Sorry, but there aren't any posts by %s yet.
", $userdata->display_name);
                    } else {
                            echo("
No posts found.
");
                    }
                    get_search_form();

            endif;
    ?>

            <?php if(get_previous_posts_link()) { ?>
<?php previous_posts_link('« Previous') ?>
<?php } ?>
            <?php if(get_next_posts_link()) { ?>
<?php next_posts_link('Next »') ?>
<?php } ?>

        <?php wp_reset_query(); ?>

    <?php get_sidebar(); ?>

<?php get_footer(); ?>


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

import org.flowable.bpmn.model.BpmnModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VariableListenerUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(VariableListenerUtil.class);

    public static boolean hasVariableListenerEventDefinitions(String processDefinitionId) {
        BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(processDefinitionId);
        return bpmnModel.hasVariableListeners();
    }
}


text:
"""
Module-wide constants.

"""

### IMPORTS

from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()

__all__ = [
	'DEF_SLEEP',
	'DEF_UPLOAD_CHUNK_SZ',
	'DEF_DOWNLOAD_CHUNK_SZ',
	'SCHEMA_FLD_ORDER',
]

### CONSTANTS & DEFINES

DEF_SLEEP = 1

DEF_UPLOAD_CHUNK_SZ = 100

DEF_DOWNLOAD_CHUNK_SZ = 1000

DEF_SMART_CHUNK_SZ = 1000000

SCHEMA_FLD_ORDER = [
	'field_name',
	'form_name',
	'section_header',
	'field_type',
	'field_label',
	'select_choices_or_calculations',
	'field_note',
	'text_validation_type_or_show_slider_number',
	'text_validation_min',
	'text_validation_max',
	'identifier',
	'branching_logic',
	'required_field',
	'custom_alignment',
	'question_number',
	'matrix_group_name',
	'matrix_ranking',
]

### END ###


text:
CWeapon* CAI_Stalker::GetCurrentWeapon() const {
    return (smart_cast<CWeapon*>(inventory().ActiveItem()));
}

u32 CAI_Stalker::GetWeaponAmmo() const {
    if (!GetCurrentWeapon())
        return (0);
    return (GetCurrentWeapon()->GetSuitableAmmoTotal(true));
}

// CInventoryItem *CAI_Stalker::GetCurrentEquipment() const
//{
//    return inventory().ItemFromSlot(OUTFIT_SLOT);
//}

CInventoryItem* CAI_Stalker::GetMedikit() const {
#pragma todo("Dima to Dima : Return correct medikit")
    return (0);
}

CInventoryItem* CAI_Stalker::GetFood() const {
#pragma todo("Dima to Dima : Return correct food")
    return (0);
}

void CAI_Stalker::ResetScriptData(void* P) { inherited::ResetScriptData(P); }

bool CAI_Stalker::bfAssignMovement(CScriptEntityAction* tpEntityAction) {
    if (!inherited::bfAssignMovement(tpEntityAction))
        return (false);

    CScriptMovementAction& l_tMovementAction = tpEntityAction->m_tMovementAction;
    CScriptWatchAction& l_tWatchAction = tpEntityAction->m_tWatchAction;
    CScriptAnimationAction& l_tAnimationAction = tpEntityAction->m_tAnimationAction;
    CScriptObjectAction& l_tObjectAction = tpEntityAction->m_tObjectAction;

    CObjectHandler::set_goal(l_tObjectAction.m_tGoalType);

    movement().set_path_type(movement().path_type());
    movement().set_detail_path_type(l_tMovementAction.m_tPathType);
    movement().set_body_state(l_tMovementAction.m_tBodyState);
    movement().set_movement_type(l_tMovementAction.m_tMovementType);
    movement().set_mental_state(l_tAnimationAction.m_tMentalState);
    sight().setup(l_tWatchAction.m_tWatchType, &l_tWatchAction.m_tWatchVector);
    movement().update(Device.dwTimeDelta);
    sight().update();

    return (true);
}

bool CAI_Stalker::bfAssignWatch(CScriptEntityAction* tpEntityAction) {
    if (!inherited::bfAssignWatch(tpEntityAction))
        return (false);

    CScriptWatchAction& l_tWatchAction = tpEntityAction->m_tWatchAction;

    //	float			&yaw = movement().m_head.target.yaw, &pitch =
    //movement().m_head.target.pitch;

    switch (l_tWatchAction.m_tGoalType) {
    case CScriptWatchAction::eGoalTypeObject: {
        if (!xr_strlen(l_tWatchAction.m_bone_to_watch))
            l_tWatchAction.m_tpObjectToWatch->Center(l_tWatchAction.m_tWatchVector);
        else {
            CBoneInstance& l_tBoneInstance =
                smart_cast<IKinematics*>(l_tWatchAction.m_tpObjectToWatch->Visual())
                    ->LL_GetBoneInstance(
                        smart_cast<IKinematics*>(l_tWatchAction.m_tpObjectToWatch->Visual())
                            // TODO: [imdex] remove shared_str
                            ->LL_BoneID(*l_tWatchAction.m_bone_to_watch));
            Fmatrix l_tMatrix;

            l_tMatrix = l_tBoneInstance.mTransform;
            l_tMatrix.mulA_43(l_tWatchAction.m_tpObjectToWatch->XFORM());

            l_tWatchAction.m_tWatchVector = l_tMatrix.c;
        }
        sight().setup(l_tWatchAction.m_tWatchType, &l_tWatchAction.m_tWatchVector);
        break;
    }
    case CScriptWatchAction::eGoalTypeDirection: {
        sight().setup(l_tWatchAction.m_tWatchType, &l_tWatchAction.m_tWatchVector);
        break;
    }
    case CScriptWatchAction::eGoalTypeWatchType: {
        break;
    }
    case CScriptWatchAction::eGoalTypeCurrent: {
        l_tWatchAction.m_tWatchType = SightManager::eSightTypeCurrentDirection;
        l_tWatchAction.m_bCompleted = true;
        return (false);
    }
    default:
        NODEFAULT;
    }

    if ((CScriptWatchAction::eGoalTypeWatchType != l_tWatchAction.m_tGoalType) &&
        (angle_difference(movement().m_head.target.yaw, movement().m_head.current.yaw) < EPS_L) &&
        (angle_difference(movement().m_head.target.pitch, movement().m_head.current.pitch) < EPS_L))
        l_tWatchAction.m_bCompleted = true;
    else
        l_tWatchAction.m_bCompleted = false;

    return (!l_tWatchAction.m_bCompleted);
}

bool CAI_Stalker::bfAssignObject(CScriptEntityAction* tpEntityAction) {
    CScriptObjectAction& l_tObjectAction = tpEntityAction->m_tObjectAction;
    CInventoryItem* l_tpInventoryItem = smart_cast<CInventoryItem*>(l_tObjectAction.m_tpObject);

    if (!inherited::bfAssignObject(tpEntityAction) || !l_tObjectAction.m_tpObject ||
        !l_tpInventoryItem) {
        if (!inventory().ActiveItem()) {
            CObjectHandler::set_goal(eObjectActionIdle);
        } else {
            CObjectHandler::set_goal(eObjectActionIdle, inventory().ActiveItem());
        }

        return ((l_tObjectAction.m_bCompleted = (CObjectHandler::goal_reached())) == false);
    }

    if (!l_tpInventoryItem->object().H_Parent())
        return (true);

    CWeapon* l_tpWeapon = smart_cast<CWeapon*>(inventory().ActiveItem());
    CWeaponMagazined* l_tpWeaponMagazined = smart_cast<CWeaponMagazined*>(inventory().ActiveItem());

    if (l_tpWeaponMagazined)
        l_tpWeaponMagazined->SetQueueSize(l_tObjectAction.m_dwQueueSize);

    switch (l_tObjectAction.m_tGoalType) {
    case eObjectActionIdle: {
        if (!l_tpWeapon)
            return ((l_tObjectAction.m_bCompleted = true) == false);
        CObjectHandler::set_goal(eObjectActionIdle, l_tpInventoryItem);
        //			inventory().Action	(kWPN_FIRE,	CMD_STOP);
        return ((l_tObjectAction.m_bCompleted = (CObjectHandler::goal_reached())) == false);
        break;
    }
    case eObjectActionFire1: {
        CObjectHandler::set_goal(eObjectActionFire1, l_tpInventoryItem);
        //			if (!l_tpWeapon)
        //				return	((l_tObjectAction.m_bCompleted = true) == false);
        if (inventory().ActiveItem() && l_tpWeapon) {
            if (l_tpWeapon->GetAmmoElapsed()) {
                //					if (l_tpWeapon->GetAmmoMagSize() > 1)
                //						l_tpWeaponMagazined->SetQueueSize(l_tObjectAction.m_dwQueueSize);
                //					else
                //						l_tpWeaponMagazined->SetQueueSize(1);
                //					inventory().Action(kWPN_FIRE,	CMD_START);
            } else {
                //					inventory().Action(kWPN_FIRE,	CMD_STOP);
                if (l_tpWeapon->GetSuitableAmmoTotal()) {
                    //						CObjectHandler::set_goal
                    //(eObjectActionFire1,l_tObjectAction.m_tpObject);
                    //						inventory().Action(kWPN_RELOAD,
                    //CMD_START);
                } else
                    l_tObjectAction.m_bCompleted = true;
            }
        }
        break;
    }
    case eObjectActionFire2: {
        CObjectHandler::set_goal(eObjectActionFire2, l_tpInventoryItem);
        //			if (!l_tpWeapon)
        //				return	((l_tObjectAction.m_bCompleted = true) == false);
        if (inventory().ActiveItem()) {
            if (l_tpWeapon->GetAmmoElapsed()) {
                //					if (l_tpWeapon->GetAmmoMagSize() > 1)
                //						l_tpWeaponMagazined->SetQueueSize(l_tObjectAction.m_dwQueueSize);
                //					else
                //						l_tpWeaponMagazined->SetQueueSize(1);
                //					inventory().Action(kWPN_FIRE,	CMD_START);
            } else {
                //					inventory().Action(kWPN_FIRE,	CMD_STOP);
                if (l_tpWeapon->GetSuitableAmmoTotal()) {
                    //						CObjectHandler::set_goal
                    //(eObjectActionFire1,l_tObjectAction.m_tpObject);
                    //						inventory().Action(kWPN_RELOAD,
                    //CMD_START);
                } else
                    l_tObjectAction.m_bCompleted = true;
            }
        }
        break;
    }
    case eObjectActionReload2:
    case eObjectActionReload1: {
        if (!l_tpWeapon)
            return ((l_tObjectAction.m_bCompleted = true) == false);
        CObjectHandler::set_goal(eObjectActionReload1, l_tpInventoryItem);
        if (inventory().ActiveItem()->object().ID() == l_tObjectAction.m_tpObject->ID()) {
            //				inventory().Action(kWPN_FIRE,	CMD_STOP);
            if (CWeapon::eReload != l_tpWeapon->GetState()) {
                //					inventory().Action(kWPN_RELOAD,	CMD_START);
            } else
                l_tObjectAction.m_bCompleted = true;
        } else
            ai().script_engine().script_log(
                ScriptStorage::eLuaMessageTypeError,
                "cannot reload active item because it is not selected!");

        //			if (inventory().ActiveItem()) {
        //				inventory().Action(kWPN_FIRE,	CMD_STOP);
        //				if (CWeapon::eReload != l_tpWeapon->STATE)
        //					inventory().Action(kWPN_RELOAD,	CMD_START);
        //				else
        //					l_tObjectAction.m_bCompleted = true;
        //			}
        //			else
        //				ai().script_engine().script_log(ScriptStorage::eLuaMessageTypeError,"cannot
        //reload active item because it is not selected!");
        break;
    }
    case eObjectActionActivate: {
        CTorch* torch = smart_cast<CTorch*>(l_tObjectAction.m_tpObject);
        if (torch) {
            torch->Switch(true);
            break;
        }
        CObjectHandler::set_goal(eObjectActionIdle, l_tpInventoryItem);
        //				inventory().Slot(l_tpInventoryItem);
        //				inventory().Activate(l_tpInventoryItem->GetSlot());
        //			if (inventory().ActiveItem() && (inventory().ActiveItem()->ID() ==
        //l_tpInventoryItem->ID())) 				if (l_tpWeapon && (CWeapon::eIdle ==
        //l_tpWeapon->STATE)) 				l_tObjectAction.m_bCompleted = true;
        return ((l_tObjectAction.m_bCompleted = (CObjectHandler::goal_reached())) == false);

        break;
    }
    case eObjectActionDeactivate: {
        CTorch* torch = smart_cast<CTorch*>(l_tObjectAction.m_tpObject);
        if (torch) {
            torch->Switch(false);
            break;
        }
        //				inventory().Activate(u32(-1));
        CObjectHandler::set_goal(eObjectActionIdle);
        return ((l_tObjectAction.m_bCompleted = (CObjectHandler::goal_reached())) == false);
        break;
    }
    case eObjectActionUse: {
        CObjectHandler::set_goal(eObjectActionUse);
        return ((l_tObjectAction.m_bCompleted = (CObjectHandler::goal_reached())) == false);
        break;
    }
    case eObjectActionTake: {
        if (inventory().GetItemFromInventory(*l_tObjectAction.m_tpObject->cName())) {
            ai().script_engine().script_log(ScriptStorage::eLuaMessageTypeError,
                                            "item is already in the inventory!");
            return ((l_tObjectAction.m_bCompleted = true) == false);
        }
        feel_touch_new(l_tObjectAction.m_tpObject);
        l_tObjectAction.m_bCompleted = true;
        break;
    }
    case eObjectActionDrop: {
        if (!inventory().GetItemFromInventory(*l_tObjectAction.m_tpObject->cName())) {
            ai().script_engine().script_log(ScriptStorage::eLuaMessageTypeError,
                                            "item is not in the inventory!");
            return ((l_tObjectAction.m_bCompleted = true) == false);
        }
        DropItemSendMessage(l_tObjectAction.m_tpObject);
        break;
    }
    default:
        NODEFAULT;
    }

    return (true);
}

bool CAI_Stalker::bfAssignAnimation(CScriptEntityAction* tpEntityAction) {
    if (!inherited::bfAssignAnimation(tpEntityAction))
        return (false);

    if (xr_strlen(tpEntityAction->m_tAnimationAction.m_caAnimationToPlay)) {
#ifdef _DEBUG
//		Msg				("%6d Assigning animation :
//%s",Device.dwTimeGlobal,*tpEntityAction->m_tAnimationAction.m_caAnimationToPlay);
#endif
        animation().torso().reset();
        animation().legs().reset();
    }

    return (true);
}


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

module Sunspot
  module SessionProxy
    #
    # This class implements a session proxy that creates a different Session
    # object for each thread. Any multithreaded application should use this
    # proxy.
    #
    class ThreadLocalSessionProxy < AbstractSessionProxy
      FINALIZER = Proc.new do |object_id|
        Thread.current[:"sunspot_session_#{object_id}"] = nil
      end

      # The configuration with which the thread-local sessions are initialized.
      attr_reader :config
      @@next_id = 0

      delegate :batch, :commit, :commit_if_delete_dirty, :commit_if_dirty, :delete_dirty?, :dirty?, :index, :index!, :new_search, :optimize, :remove, :remove!, :remove_all, :remove_all!, :remove_by_id, :remove_by_id!, :search, :more_like_this, :new_more_like_this, :to => :session

      #
      # Optionally pass an existing Sunspot::Configuration object. If none is
      # passed, a default configuration is used; it can then be modified using
      # the #config attribute.
      #
      def initialize(config = Sunspot::Configuration.new)
        @config = config
        ObjectSpace.define_finalizer(self, FINALIZER)
      end

      def session #:nodoc:
        Thread.current[:"sunspot_session_#{object_id}"] ||= Session.new(config)
      end
    end
  end
end


text:
$(function () {

	var menu = $('#menu').detach(),
		map, markers = [];

	$('body').on('click', 'nav li > a', function(e) {
		if(!$(this).hasClass('link')) {
			$(this).parent('li').siblings().find('.opened').removeClass('opened');
			$(this).addClass('opened').siblings('ul, div, form').addClass('opened');
			google.maps.event.trigger(map, 'resize');
			map.setCenter(new google.maps.LatLng(50.086094, 14.421270));
			e.preventDefault();
		}
	});

	$('table a').on('click', function(e) {

		var that = $(this);

		if(!$(this).hasClass('no-detail')) {

			$('table').find('.opened-td').removeClass('opened-td');
			$(this).closest('td').addClass('opened-td');

			var row = $(this).closest('tr').nextAll('.opener').first().find('td');

			menu.appendTo(row);
			google.maps.event.trigger(map, 'resize');

			var target = $($(this).attr('href'));

			$('#menu').find('.opened').removeClass('opened');

			target
				.addClass('opened')
				.siblings('a').addClass('opened')
				.closest('.person-detail').addClass('opened')
				.siblings('a').addClass('opened')
				.closest('.sub-1').addClass('opened')
				.siblings('a').addClass('opened');

			$('html, body').animate({scrollTop: that.offset().top - 66}, 0);

			e.preventDefault();
		}
	});

	menu.find('.person-lessons > li > a').on('click', function() {
		var l = $(this).next('.lesson-details');
		if (l.attr('id')) {
			$('table').find('a[href=#' + l.attr('id') + ']').click();
		}
	});

   	$('.menu-link').on('click', function() {
		$('table').find('.opened-td').removeClass('opened-td');

		var row = $('table tr.opener:first').find('td');

		menu.appendTo(row);
		google.maps.event.trigger(map, 'resize');

		var target = $($(this).attr('href'));

		$('#menu').find('.opened').removeClass('opened');

		target
			.addClass('opened')
			.siblings('form').addClass('opened')
			.siblings('a').addClass('opened')
			.closest('.person-detail').addClass('opened')
			.siblings('a').addClass('opened')
			.closest('.sub-1').addClass('opened')
			.siblings('a').addClass('opened');

		$('html, body').animate({scrollTop: menu.offset().top}, 500);
	});

	$('table td').each(function() {
    	if($(this).find('a').length && !$(this).find('a').hasClass('no-detail')) {
    		$(this).addClass('has-detail');
    	}
    });

    $('body').on('click', '#menu > .closer', function() {
    	$('#menu').remove();
    	$('table').find('.opened-td').removeClass('opened-td');
    });

    fixeddate();

    function fixeddate() {
    	var dates = $('.dates'),
	    	headposition = dates.offset().top;

	    $(window).scroll(function() {

	    	var scrolltop = $(window).scrollTop()

	    	if(scrolltop > headposition) {
	    		dates.addClass('fixed');
	    	} else {
	    		if(dates.hasClass('fixed')) {
	    			dates.removeClass('fixed');
	    		}
	    	}

	    });

    }

   	var handleRegister = function(e) {
		e.preventDefault();

		var $form = $(this);

		var values = {};
		$.each( $form.serializeArray(), function(i, field) {
			values[field.name] = field.value;
		});
		values['fos_user_registration_form[username]'] = $('#fos_user_registration_form_email').val();

		$.ajax({
			type        : $form.attr('method'),
			url         : $form.attr('action'),
			data        : values,
			success     : function(data) {
				var $data = $(data);
				if ($data.prop('tagName') === 'FORM') {
					$form.replaceWith($data);
					$data.on('submit', handleRegister);
				} else {
					$form.after($data);
					$data.show();
					$data.children('ul').show();
				}
			}
		});

	}

	menu.find('.fos_user_registration_register').on('submit', handleRegister);

	var handleProfile = function(e) {
		e.preventDefault();

		var $form = $(this);

		var values = {};
		$.each( $form.serializeArray(), function(i, field) {
			values[field.name] = field.value;
		});
		values['fos_user_profile_form[username]'] = $('#fos_user_profile_form_email').val();

		$.ajax({
			type        : $form.attr('method'),
			url         : $form.attr('action'),
			data        : values,
			success     : function(data) {
				var parent = $form.parent();
				parent.html(data);
				parent.find('.fos_user_profile_edit').on('submit', handleProfile);
				parent.find('.ajax-link').on('click', handleAjaxLinks);
			}
		});

	}

	menu.find('.fos_user_profile_edit').on('submit', handleProfile);

	var handleAjaxLinks = function(e) {
		e.preventDefault();
		var that = $(this);

		$.ajax({
			url: $(this).attr('href'),
			type: 'GET',
			success: function (data) {
				$(that.data('target')).html(data);
				$(that.data('target')).find('.ajax-link').on('click', handleAjaxLinks);
				$(that.data('target')).find('.fos_user_profile_edit').on('submit', handleProfile);
			}
		})
	};

	$('.ajax-link').on('click', handleAjaxLinks);

	function initialize() {
		var mapOptions = {
			center: new google.maps.LatLng(50.086094, 14.421270),
			zoom: 15
		};
		map = new google.maps.Map(menu.find('#map').get(0), mapOptions);

		markers.push(new google.maps.Marker({
			position: new google.maps.LatLng(50.0884285, 14.4225103),
			map: map,
			title:"Maitrea - Dům osobního rozvoje"
		}));
		markers.push(new google.maps.Marker({
			position: new google.maps.LatLng(50.0873831, 14.4173879),
			map: map,
			title:"Municipal Library of Prague"
		}));
		markers.push(new google.maps.Marker({
			position: new google.maps.LatLng(50.0840201, 14.4279772),
			map: map,
			title:"fusion hotel prague"
		}));
		markers.push(new google.maps.Marker({
			position: new google.maps.LatLng(50.08409210000001, 14.4145105),
			map: map,
			title:"Lehka Hlava"
		}));
		markers.push(new google.maps.Marker({
			position: new google.maps.LatLng(50.0883149, 14.4162797),
			map: map,
			title:"Mistral"
		}));
		markers.push(new google.maps.Marker({
			position: new google.maps.LatLng(50.086915, 14.4254801),
			map: map,
			title:"Grand Café Orient"
		}));
		markers.push(new google.maps.Marker({
			position: new google.maps.LatLng(50.086094, 14.421270),
			map: map,
			title:"Čili Bar"
		}));
		markers.push(new google.maps.Marker({
			position: new google.maps.LatLng(50.0839548, 14.4143128),
			map: map,
			title:"Hemingway Bar"
		}));

		menu.find('p[data-marker]').each(function() {
			var i = parseInt($(this).data('marker'));

			google.maps.event.addListener(markers[i], 'mouseover', function() {
				this.setAnimation(google.maps.Animation.BOUNCE);
				$('p[data-marker=' + i + ']').css('background-color', '#ffdbe5');
			});
			google.maps.event.addListener(markers[i], 'mouseout', function() {
				this.setAnimation(null);
				$('p[data-marker=' + i + ']').css('background-color', '');
			});

			$(this).mouseenter(function() {
				markers[i].setAnimation(google.maps.Animation.BOUNCE);
				$('p[data-marker=' + i + ']').css('background-color', '#ffdbe5');
			}).mouseleave(function() {
				markers[i].setAnimation(null);
				$('p[data-marker=' + i + ']').css('background-color', '');
			});
		});
	}
	google.maps.event.addDomListener(window, 'load', initialize);
});


text:
from .licenses import Licenses
from .login import Login


text:
package ua.com.fielden.platform.entity;

import static java.lang.String.format;
import static ua.com.fielden.platform.entity.NoKey.NO_KEY;

import ua.com.fielden.platform.entity.annotation.IsProperty;
import ua.com.fielden.platform.entity.annotation.KeyType;
import ua.com.fielden.platform.entity.annotation.MapTo;
import ua.com.fielden.platform.entity.annotation.Observable;
import ua.com.fielden.platform.entity.annotation.Title;

/**
 * An abstract entity that is used as a common super type for generic entities {@link EntityEditAction} and {@link EntityNewAction}.
 *
 * @author TG Team
 *
 */
@KeyType(NoKey.class)
public abstract class AbstractEntityManipulationAction extends AbstractFunctionalEntityWithCentreContext<NoKey> {

    @IsProperty
    @MapTo
    @Title("Entity Type")
    private String entityType;

    private Class<? extends AbstractEntity<?>> entityTypeAsClass;

    @IsProperty
    @MapTo
    @Title("Import URI")
    private String importUri;

    @IsProperty
    @MapTo
    @Title("Element Name")
    private String elementName;

    protected AbstractEntityManipulationAction() {
        setKey(NO_KEY);
    }

    @Observable
    public AbstractEntityManipulationAction setElementName(final String elementName) {
        this.elementName = elementName;
        return this;
    }

    public String getElementName() {
        return elementName;
    }

    @Observable
    protected AbstractEntityManipulationAction setImportUri(final String importUri) {
        this.importUri = importUri;
        return this;
    }

    public String getImportUri() {
        return importUri;
    }

    public AbstractEntityManipulationAction setEntityTypeForEntityMaster(final Class<? extends AbstractEntity<?>> entityTypeAsClass) {
        this.entityTypeAsClass = entityTypeAsClass;
        setEntityType(entityTypeAsClass.getName());
        setImportUri(format("/master_ui/%s", getEntityType()));
        setElementName(format("tg-%s-master", this.entityTypeAsClass.getSimpleName()));
        return this;
    }

    public Class<? extends AbstractEntity<?>> getEntityTypeAsClass() {
        return entityTypeAsClass;
    }

    @Observable
    protected AbstractEntityManipulationAction setEntityType(final String entityType) {
        this.entityType = entityType;
        return this;
    }

    public String getEntityType() {
        return entityType;
    }
}


text:
Note: if your project is a child component, then bin/lib folder could be linked to the parent directories
      and you can use variable directory of parent layer instead. In some cases you're forced to do it.

## Local pre-compiled project (simple)
e.g., application or game without sources

- bin
- lib
- data
- conf
- var

## Local interpreted project (simple)
e.g., python apps, nodejs/php console apps etc.

- bin
- lib
- src
- data
- conf
- var

## Local interpreted modular project (complex)
e.g., python apps, nodejs/php console apps etc.

- apps
- bin
- lib
- src
- modules
- deps
- data
- conf
- var

## Network modular project (complex)
e.g., websites, web services, server applications, LAN utilities

- srv (often called public/ under web projects)
- apps
- bin
- lib
- src
- modules
- deps
- data
- conf
- var

## Operating system or container

 - bin
 - lib
 - conf
 - data
 - var
 - srv
 - apps
 - modules
 - deps
 - env
     - sys
        - boot
        - mnt
        - [...]
     - users


text:
#include "anim.hpp"
#include "dialog_scene.hpp"
#include "play_scene.hpp"
#include "welcome_scene.hpp"

#include "blurb.inl"
#include "strings.inl"

#include "game-text-input/gametextinput.h"

// from samples/common/include
#include "Versions.h"

#include <string>
#include <android/window.h>

#define TITLE_POS center, 0.15f
#define TITLE_FONT_SCALE 1.0f
#define TITLE_COLOR 0.0f, 1.0f, 0.0f

#define NAME_EDIT_POS center, 0.85f
#define NAME_EDIT_FONT_SCALE .7f
#define NAME_EDIT_COLOR 1.0f, 1.0f, 0.0f
#define NAME_EDIT_SIZE 1.0f, 0.2f

// button defaults:
#define BUTTON_COLOR 0.0f, 1.0f, 0.0f
#define BUTTON_SIZE 0.2f, 0.2f
#define BUTTON_FONT_SCALE 0.5f

// button geometry
#define BUTTON_PLAY_POS center, 0.5f
#define BUTTON_PLAY_SIZE 0.4f, 0.4f
#define BUTTON_PLAY_FONT_SCALE 1.0f

// size of all side buttons (story, about)
#define BUTTON_SIDEBUTTON_WIDTH (center - 0.4f)
#define BUTTON_SIDEBUTTON_HEIGHT 0.2f
#define BUTTON_SIDEBUTTON_SIZE BUTTON_SIDEBUTTON_WIDTH, BUTTON_SIDEBUTTON_HEIGHT

// position of each side button (the buttons on the sides of the PLAY button)
#define BUTTON_STORY_POS 0.1f + 0.5f * BUTTON_SIDEBUTTON_WIDTH, 0.5f
#define BUTTON_MEMORY_POS 0.1f + 0.5f * BUTTON_SIDEBUTTON_WIDTH, 0.25f
#define BUTTON_ABOUT_POS center + 0.3f + 0.5f * BUTTON_SIDEBUTTON_WIDTH, 0.5f
#define BUTTON_TEST_POS center + 0.3f + 0.5f * BUTTON_SIDEBUTTON_WIDTH, 0.75f
#define BUTTON_QUIT_POS center + 0.3f + 0.5f * BUTTON_SIDEBUTTON_WIDTH, 0.25f
#define INITIAL_NAME "noname"

static std::string sNameEdit(S_NAME_EDIT);

OwnedGameTextInputState::OwnedGameTextInputState(const std::string &initial_string) : owned_string(
        initial_string) {
    inner.text_UTF8 = owned_string.data();
    inner.text_length = owned_string.length();
    inner.selection.start = 0;
    inner.selection.end = owned_string.length();
    inner.composingRegion.start = -1;
    inner.composingRegion.end = -1;
}

OwnedGameTextInputState &OwnedGameTextInputState::operator=(const GameTextInputState &rhs) {
    inner = rhs;
    owned_string = std::string(rhs.text_UTF8, rhs.text_length);
    inner.text_UTF8 = owned_string.data();
    return *this;
}

WelcomeScene::WelcomeScene() : mTextInputState(INITIAL_NAME) {
}

WelcomeScene::~WelcomeScene() {
}

void WelcomeScene::RenderBackground() {
    RenderBackgroundAnimation(mShapeRenderer);
}

static std::string sAboutStartText;

void WelcomeScene::InitAboutText(JNIEnv* env, jobject context) {
    std::stringstream aboutStream;
    aboutStream << BLURB_ABOUT;
    std::string versionName;
    agdk_samples_util::GetAppVersionInfo(env, context, nullptr, &versionName);
    aboutStream << "\nApp Version: " << versionName;
    aboutStream << "\nTarget SDK Version: "
                << android_get_application_target_sdk_version();
    aboutStream << "\nDevice OS Version: " << android_get_device_api_level();
    sAboutStartText = aboutStream.str();
}

std::string WelcomeScene::AboutMessage() {
    std::stringstream aboutStream;
    aboutStream << sAboutStartText;
    // Add window insets to help debugging
    aboutStream << "\n[Debug Insets (left, right, top, bottom)]\n";
    auto activity = NativeEngine::GetInstance()->GetAndroidApp()->activity;
    ARect insets;
    GameActivity_getWindowInsets(activity, GAMECOMMON_INSETS_TYPE_SYSTEM_BARS, &insets);
    aboutStream << "System bars: (" << insets.left << ", " << insets.right << ", " << insets.top
                << ", " << insets.bottom << ")\n";
    GameActivity_getWindowInsets(activity, GAMECOMMON_INSETS_TYPE_DISPLAY_CUTOUT, &insets);
    aboutStream << "Cutout: (" << insets.left << ", " << insets.right << ", " << insets.top
                << ", " << insets.bottom << ")\n";
    GameActivity_getWindowInsets(activity, GAMECOMMON_INSETS_TYPE_WATERFALL, &insets);
    aboutStream << "Waterfall: (" << insets.left << ", " << insets.right << ", "
                << insets.top << ", " << insets.bottom << ")";
    return aboutStream.str();
}

void WelcomeScene::OnButtonClicked(int id) {
    SceneManager *mgr = SceneManager::GetInstance();

    if (id == mPlayButtonId) {
        DataLoaderStateMachine *dataStateMachine =
                NativeEngine::GetInstance()->GetDataStateMachine();
        mgr->RequestNewScene(new PlayScene(dataStateMachine->getLevelLoaded()));
    } else if (id == mStoryButtonId) {
        mgr->RequestNewScene((new DialogScene())->SetText(BLURB_STORY)->SetSingleButton(S_OK,
                DialogScene::ACTION_RETURN));
    } else if (id == mAboutButtonId) {
        std::string aboutText = AboutMessage();
        mgr->RequestNewScene((new DialogScene())->SetText(aboutText.c_str())->SetSingleButton(S_OK,
                DialogScene::ACTION_RETURN));
    } else if (id == mNameEdit->GetId()) {
        auto activity = NativeEngine::GetInstance()->GetAndroidApp()->activity;
        // NB: the UI is resized when the IME is shown and OnCreateWidgets is called again.
        sNameEdit = mTextInputState.inner.text_UTF8;
        mNameEdit->SetText(sNameEdit.c_str());
        GameActivity_setTextInputState(activity, &mTextInputState.inner);
        GameActivity_showSoftInput(NativeEngine::GetInstance()->GetAndroidApp()->activity, 0);
    } else if (id == mTestButtonId) {
        auto activity = NativeEngine::GetInstance()->GetAndroidApp()->activity;
        GameActivity_setWindowFlags(activity,
                                    AWINDOW_FLAG_KEEP_SCREEN_ON | AWINDOW_FLAG_TURN_SCREEN_ON |
                                    AWINDOW_FLAG_FULLSCREEN |
                                    AWINDOW_FLAG_SHOW_WHEN_LOCKED,
                                    0);
    } else if (id == mQuitButtonId) {
        auto activity = NativeEngine::GetInstance()->GetAndroidApp()->activity;
        GameActivity_finish(activity);
    } else if (id == mMemoryButtonId) {
        NativeEngine::GetInstance()->GetMemoryConsumer()->SetActive(true);
    }
}

void WelcomeScene::OnTextInput() {
    auto activity = NativeEngine::GetInstance()->GetAndroidApp()->activity;
    GameActivity_getTextInputState(activity, [](void *context, const GameTextInputState *state) {
        auto thiz = static_cast<WelcomeScene *>(context);
        thiz->mTextInputState = *state;
        sNameEdit = thiz->mTextInputState.owned_string;
    }, this);
    __android_log_print(ANDROID_LOG_DEBUG, "WelcomeScene", "Got game text %s", sNameEdit.c_str());
    mNameEdit->SetText(sNameEdit.c_str());
    ARect insets;
    GameTextInput_getImeInsets(GameActivity_getTextInput(activity), &insets);
    __android_log_print(ANDROID_LOG_DEBUG,
                        "WelcomeScene", "IME insets: left=%d right=%d top=%d bottom=%d",
                        insets.left, insets.right, insets.top, insets.bottom);
}

void WelcomeScene::DoFrame() {
    // update widget states based on signed-in status
    UpdateWidgetStates();

    // if the sign in or cloud save process is in progress, show a wait screen. Otherwise, not:
    SetWaitScreen(false);

    // draw the UI
    UiScene::DoFrame();
}

void WelcomeScene::UpdateWidgetStates() {
    // Build navigation
    AddNav(mPlayButtonId, UI_DIR_LEFT, mStoryButtonId);
    AddNav(mPlayButtonId, UI_DIR_RIGHT, mAboutButtonId);

    AddNav(mStoryButtonId, UI_DIR_RIGHT, mMemoryButtonId);
    AddNav(mMemoryButtonId, UI_DIR_RIGHT, mPlayButtonId);

    AddNav(mAboutButtonId, UI_DIR_LEFT, mPlayButtonId);

}

void WelcomeScene::OnStartGraphics() {
    UiScene::OnStartGraphics();
}

void WelcomeScene::OnCreateWidgets() {

    // create widgets
    float maxX = SceneManager::GetInstance()->GetScreenAspect();
    float center = 0.5f * maxX;

    // create the static title
    NewWidget()->SetText(S_TITLE)->SetCenter(TITLE_POS)->SetTextColor(TITLE_COLOR)
            ->SetFontScale(TITLE_FONT_SCALE)->SetTransition(UiWidget::TRANS_FROM_BOTTOM);

    // create the "play" button
    mPlayButtonId = NewWidget()->SetText(S_PLAY)->SetTextColor(BUTTON_COLOR)
            ->SetCenter(BUTTON_PLAY_POS)->SetSize(BUTTON_PLAY_SIZE)
            ->SetFontScale(BUTTON_PLAY_FONT_SCALE)->SetIsButton(true)
            ->SetTransition(UiWidget::TRANS_SCALE)->GetId();

    // story button
    mStoryButtonId = NewWidget()->SetTextColor(BUTTON_COLOR)->SetText(S_STORY)
            ->SetCenter(BUTTON_STORY_POS)->SetSize(BUTTON_SIDEBUTTON_SIZE)
            ->SetFontScale(BUTTON_FONT_SCALE)->SetIsButton(true)
            ->SetTransition(UiWidget::TRANS_FROM_RIGHT)->GetId();

    // memory button
    mMemoryButtonId = NewWidget()->SetTextColor(BUTTON_COLOR)->SetText(S_MEMORY)
            ->SetCenter(BUTTON_MEMORY_POS)->SetSize(BUTTON_SIDEBUTTON_SIZE)
            ->SetFontScale(BUTTON_FONT_SCALE)->SetIsButton(true)
            ->SetTransition(UiWidget::TRANS_FROM_RIGHT)->GetId();

    // about button
    mAboutButtonId = NewWidget()->SetTextColor(BUTTON_COLOR)->SetText(S_ABOUT)
            ->SetCenter(BUTTON_ABOUT_POS)->SetSize(BUTTON_SIDEBUTTON_SIZE)
            ->SetFontScale(BUTTON_FONT_SCALE)->SetIsButton(true)
            ->SetTransition(UiWidget::TRANS_FROM_RIGHT)->GetId();

    // create editable name field
    mNameEdit = NewWidget()->SetText(sNameEdit.c_str())->SetCenter(NAME_EDIT_POS)->SetTextColor(
                    NAME_EDIT_COLOR)
            ->SetFontScale(NAME_EDIT_FONT_SCALE)->SetTransition(UiWidget::TRANS_FROM_TOP)
            ->SetSize(NAME_EDIT_SIZE)->SetIsButton(true);

    // test button
    mTestButtonId = NewWidget()->SetTextColor(BUTTON_COLOR)->SetText(S_TEST)
            ->SetCenter(BUTTON_TEST_POS)->SetSize(BUTTON_SIDEBUTTON_SIZE)
            ->SetFontScale(BUTTON_FONT_SCALE)->SetIsButton(true)
            ->SetTransition(UiWidget::TRANS_FROM_TOP)->GetId();

    // quit button
    mQuitButtonId = NewWidget()->SetTextColor(BUTTON_COLOR)->SetText(S_QUIT)
            ->SetCenter(BUTTON_QUIT_POS)->SetSize(BUTTON_SIDEBUTTON_SIZE)
            ->SetFontScale(BUTTON_FONT_SCALE)->SetIsButton(true)
            ->SetTransition(UiWidget::TRANS_FROM_BOTTOM)->GetId();

    // "Play" button is the default button
    SetDefaultButton(mPlayButtonId);

    // enable/disable widgets as appropriate to signed in state
    UpdateWidgetStates();
}

void WelcomeScene::OnKillGraphics() {
    UiScene::OnKillGraphics();
}


text:
package sg.ncl.service.team.exceptions;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
import sg.ncl.common.exception.base.NotFoundException;

/**
 * Created by Desmond / Te Ye
 */
@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Team not found")
public class TeamNotFoundException extends NotFoundException {
    public TeamNotFoundException(final String message) {
        super(message);
    }
}


text:
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands;
using Microsoft.eShopOnContainers.Services.Ordering.API.Application.Queries;
using Microsoft.eShopOnContainers.Services.Ordering.API.Infrastructure.Services;
using Ordering.API.Application.Commands;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Microsoft.eShopOnContainers.Services.Ordering.API.Controllers
{
    [Route("api/v1/[controller]")]
    [Authorize]
    public class OrdersController : Controller
    {
        private readonly IMediator _mediator;
        private readonly IOrderQueries _orderQueries;
        private readonly IIdentityService _identityService;

        public OrdersController(IMediator mediator, IOrderQueries orderQueries, IIdentityService identityService)
        {

            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
            _orderQueries = orderQueries ?? throw new ArgumentNullException(nameof(orderQueries));
            _identityService = identityService ?? throw new ArgumentNullException(nameof(identityService));
        }

        [Route("cancel")]
        [HttpPut]
        public async Task<IActionResult> CancelOrder([FromBody]CancelOrderCommand command, [FromHeader(Name = "x-requestid")] string requestId)
        {
            bool commandResult = false;
            if (Guid.TryParse(requestId, out Guid guid) && guid != Guid.Empty)
            {
                var requestCancelOrder = new IdentifiedCommand<CancelOrderCommand, bool>(command, guid);
                commandResult = await _mediator.Send(requestCancelOrder);
            }

            return commandResult ? (IActionResult)Ok() : (IActionResult)BadRequest();

        }

        [Route("ship")]
        [HttpPut]
        public async Task<IActionResult> ShipOrder([FromBody]ShipOrderCommand command, [FromHeader(Name = "x-requestid")] string requestId)
        {
            bool commandResult = false;
            if (Guid.TryParse(requestId, out Guid guid) && guid != Guid.Empty)
            {
                var requestShipOrder = new IdentifiedCommand<ShipOrderCommand, bool>(command, guid);
                commandResult = await _mediator.Send(requestShipOrder);
            }

            return commandResult ? (IActionResult)Ok() : (IActionResult)BadRequest();

        }

        [Route("{orderId:int}")]
        [HttpGet]
        public async Task<IActionResult> GetOrder(int orderId)
        {
            try
            {
                var order = await _orderQueries
                    .GetOrderAsync(orderId);

                return Ok(order);
            }
            catch (KeyNotFoundException)
            {
                return NotFound();
            }
        }

        [Route("")]
        [HttpGet]
        public async Task<IActionResult> GetOrders()
        {
            var orderTask = _orderQueries.GetOrdersAsync();

            var orders = await orderTask;

            return Ok(orders);
        }

        [Route("cardtypes")]
        [HttpGet]
        public async Task<IActionResult> GetCardTypes()
        {
            var cardTypes = await _orderQueries
                .GetCardTypesAsync();

            return Ok(cardTypes);
        }
    }
}


text:
package com.coolshow.app;

import com.coolshow.app.utils.MyActivityCollector;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;

public class BaseActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		Log.d("BaseActivity", getClass().getSimpleName());
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		MyActivityCollector.addActivity(this);
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		MyActivityCollector.removeActivity(this);
	}

}


text:
var FormImageCrop = function () {

    var demo1 = function() {
        $('#demo1').Jcrop();
    }

    var demo2 = function() {
        var jcrop_api;

        $('#demo2').Jcrop({
          onChange:   showCoords,
          onSelect:   showCoords,
          onRelease:  clearCoords
        },function(){
          jcrop_api = this;
        });

        $('#coords').on('change','input',function(e){
          var x1 = $('#x1').val(),
              x2 = $('#x2').val(),
              y1 = $('#y1').val(),
              y2 = $('#y2').val();
          jcrop_api.setSelect([x1,y1,x2,y2]);
        });

        // Simple event handler, called from onChange and onSelect
        // event handlers, as per the Jcrop invocation above
        function showCoords(c)
        {
            $('#x1').val(c.x);
            $('#y1').val(c.y);
            $('#x2').val(c.x2);
            $('#y2').val(c.y2);
            $('#w').val(c.w);
            $('#h').val(c.h);
        };

        function clearCoords()
        {
            $('#coords input').val('');
        };
    }

    var demo3 = function() {
        // Create variables (in this scope) to hold the API and image size
        var jcrop_api,
            boundx,
            boundy,
            // Grab some information about the preview pane
            $preview = $('#preview-pane'),
            $pcnt = $('#preview-pane .preview-container'),
            $pimg = $('#preview-pane .preview-container img'),

            xsize = $pcnt.width(),
            ysize = $pcnt.height();

            console.log('init',[xsize,ysize]);

        $('#demo3').Jcrop({
          onChange: updatePreview,
          onSelect: updatePreview,
          aspectRatio: xsize / ysize
        },function(){
          // Use the API to get the real image size
          var bounds = this.getBounds();
          boundx = bounds[0];
          boundy = bounds[1];
          // Store the API in the jcrop_api variable
          jcrop_api = this;
          // Move the preview into the jcrop container for css positioning
          $preview.appendTo(jcrop_api.ui.holder);
        });

        function updatePreview(c)
        {
          if (parseInt(c.w) > 0)
          {
            var rx = xsize / c.w;
            var ry = ysize / c.h;

            $pimg.css({
              width: Math.round(rx * boundx) + 'px',
              height: Math.round(ry * boundy) + 'px',
              marginLeft: '-' + Math.round(rx * c.x) + 'px',
              marginTop: '-' + Math.round(ry * c.y) + 'px'
            });
          }
        };
    }

    var demo4 = function() {
        var jcrop_api;

        $('#demo4').Jcrop({
          bgFade:     true,
          bgOpacity: .2,
          setSelect: [ 60, 70, 540, 330 ]
        },function(){
          jcrop_api = this;
        });

        $('#fadetog').change(function(){
          jcrop_api.setOptions({
            bgFade: this.checked
          });
        }).attr('checked', true);
        App.updateUniform('#fadetog');

        $('#shadetog').change(function(){
          if (this.checked) $('#shadetxt').slideDown();
            else $('#shadetxt').slideUp();
          jcrop_api.setOptions({
            shade: this.checked
          });
        }).attr('checked', false);

        // Define page sections
        var sections = {
          bgc_buttons: 'Change bgColor',
          bgo_buttons: 'Change bgOpacity',
          anim_buttons: 'Animate Selection'
        };
        // Define animation buttons
        var ac = {
          anim1: [217,122,382,284],
          anim2: [20,20,580,380],
          anim3: [24,24,176,376],
          anim4: [347,165,550,355],
          anim5: [136,55,472,183]
        };
        // Define bgOpacity buttons
        var bgo = {
          Low: .2,
          Mid: .5,
          High: .8,
          Full: 1
        };
        // Define bgColor buttons
        var bgc = {
          R: '#900',
          B: '#4BB6F0',
          Y: '#F0B207',
          G: '#46B81C',
          W: 'white',
          K: 'black'
        };
        // Create fieldset targets for buttons
        for(i in sections)
          insertSection(i,sections[i]);

        function create_btn(c) {
          var $o = $('<button />').addClass('btn small');
          if (c) $o.append(c);
          return $o;
        }

        var a_count = 1;
        // Create animation buttons
        for(i in ac) {
          $('#anim_buttons .btn-group')
            .append(
              create_btn(a_count++).click(animHandler(ac[i])),
              ' '
            );
        }

        $('#anim_buttons .btn-group').append(
          create_btn('Bye!').click(function(e){
            $(e.target).addClass('active');
            jcrop_api.animateTo(
              [300,200,300,200],
              function(){
                this.release();
                $(e.target).closest('.btn-group').find('.active').removeClass('active');
              }
            );
            return false;
          })
        );

        // Create bgOpacity buttons
        for(i in bgo) {
          $('#bgo_buttons .btn-group').append(
            create_btn(i).click(setoptHandler('bgOpacity',bgo[i])),
            ' '
          );
        }
        // Create bgColor buttons
        for(i in bgc) {
          $('#bgc_buttons .btn-group').append(
            create_btn(i).css({
              background: bgc[i],
              color: ((i == 'K') || (i == 'R'))?'white':'black'
            }).click(setoptHandler('bgColor',bgc[i])), ' '
          );
        }
        // Function to insert named sections into interface
        function insertSection(k,v) {
          $('#interface').prepend(
            $('<fieldset></fieldset>').attr('id',k).append(
              $('

').append(v),
              '

'
            )
          );
        };
        // Handler for option-setting buttons
        function setoptHandler(k,v) {
          return function(e) {
            $(e.target).closest('.btn-group').find('.active').removeClass('active');
            $(e.target).addClass('active');
            var opt = { };
            opt[k] = v;
            jcrop_api.setOptions(opt);
            return false;
          };
        };
        // Handler for animation buttons
        function animHandler(v) {
          return function(e) {
            $(e.target).addClass('active');
            jcrop_api.animateTo(v,function(){
              $(e.target).closest('.btn-group').find('.active').removeClass('active');
            });
            return false;
          };
        };

        $('#bgo_buttons .btn:first,#bgc_buttons .btn:last').addClass('active');
        $('#interface').show();
    }

    var demo5 = function() {
        // The variable jcrop_api will hold a reference to the
        // Jcrop API once Jcrop is instantiated.
        var jcrop_api;

        // In this example, since Jcrop may be attached or detached
        // at the whim of the user, I've wrapped the call into a function
        initJcrop();

        // The function is pretty simple
        function initJcrop()//{{{
        {
          // Hide any interface elements that require Jcrop
          // (This is for the local user interface portion.)
          $('.requiresjcrop').hide();

          // Invoke Jcrop in typical fashion
          $('#demo5').Jcrop({
            onRelease: releaseCheck
          },function(){

            jcrop_api = this;
            jcrop_api.animateTo([100,100,400,300]);

            // Setup and dipslay the interface for "enabled"
            $('#can_click,#can_move,#can_size').attr('checked','checked');
            App.updateUniform('#can_click,#can_move,#can_size');

            $('#ar_lock,#size_lock,#bg_swap').attr('checked',false);
            App.updateUniform('#ar_lock,#size_lock,#bg_swap');

            $('.requiresjcrop').show();

          });

        };
        //}}}

        // Use the API to find cropping dimensions
        // Then generate a random selection
        // This function is used by setSelect and animateTo buttons
        // Mainly for demonstration purposes
        function getRandom() {
          var dim = jcrop_api.getBounds();
          return [
            Math.round(Math.random() * dim[0]),
            Math.round(Math.random() * dim[1]),
            Math.round(Math.random() * dim[0]),
            Math.round(Math.random() * dim[1])
          ];
        };

        // This function is bound to the onRelease handler...
        // In certain circumstances (such as if you set minSize
        // and aspectRatio together), you can inadvertently lose
        // the selection. This callback re-enables creating selections
        // in such a case. Although the need to do this is based on a
        // buggy behavior, it's recommended that you in some way trap
        // the onRelease callback if you use allowSelect: false
        function releaseCheck()
        {
          jcrop_api.setOptions({ allowSelect: true });
          $('#can_click').attr('checked',false);
          App.updateUniform('#can_click');
        };

        // Attach interface buttons
        // This may appear to be a lot of code but it's simple stuff
        $('#setSelect').click(function(e) {
          // Sets a random selection
          jcrop_api.setSelect(getRandom());
        });
        $('#animateTo').click(function(e) {
          // Animates to a random selection
          jcrop_api.animateTo(getRandom());
        });
        $('#release').click(function(e) {
          // Release method clears the selection
          jcrop_api.release();
        });
        $('#disable').click(function(e) {
          // Disable Jcrop instance
          jcrop_api.disable();
          // Update the interface to reflect disabled state
          $('#enable').show();
          $('.requiresjcrop').hide();
        });
        $('#enable').click(function(e) {
          // Re-enable Jcrop instance
          jcrop_api.enable();
          // Update the interface to reflect enabled state
          $('#enable').hide();
          $('.requiresjcrop').show();
        });
        $('#rehook').click(function(e) {
          // This button is visible when Jcrop has been destroyed
          // It performs the re-attachment and updates the UI
          $('#rehook,#enable').hide();
          initJcrop();
          $('#unhook,.requiresjcrop').show();
          return false;
        });
        $('#unhook').click(function(e) {
          // Destroy Jcrop widget, restore original state
          jcrop_api.destroy();
          // Update the interface to reflect un-attached state
          $('#unhook,#enable,.requiresjcrop').hide();
          $('#rehook').show();
          return false;
        });

        // Hook up the three image-swapping buttons
        $('#img1').click(function(e) {
          $(this).addClass('active').closest('.btn-group')
            .find('button.active').not(this).removeClass('active');

          jcrop_api.setImage('../../assets/global/plugins/jcrop/demos/demo_files/sago.jpg');
          jcrop_api.setOptions({ bgOpacity: .6 });
          return false;
        });
        $('#img2').click(function(e) {
          $(this).addClass('active').closest('.btn-group')
            .find('button.active').not(this).removeClass('active');

          jcrop_api.setImage('../../assets/global/plugins/jcrop/demos/demo_files/pool.jpg');
          jcrop_api.setOptions({ bgOpacity: .6 });
          return false;
        });
        $('#img3').click(function(e) {
          $(this).addClass('active').closest('.btn-group')
            .find('button.active').not(this).removeClass('active');

          jcrop_api.setImage('../../assets/global/plugins/jcrop/demos/demo_files/sago.jpg',function(){
            this.setOptions({
              bgOpacity: 1,
              outerImage: '../../assets/global/plugins/jcrop/demos/demo_files/sagomod.jpg'
            });
            this.animateTo(getRandom());
          });
          return false;
        });

        // The checkboxes simply set options based on it's checked value
        // Options are changed by passing a new options object

        // Also, to prevent strange behavior, they are initially checked
        // This matches the default initial state of Jcrop

        $('#can_click').change(function(e) {
          jcrop_api.setOptions({ allowSelect: !!this.checked });
          jcrop_api.focus();
        });
        $('#can_move').change(function(e) {
          jcrop_api.setOptions({ allowMove: !!this.checked });
          jcrop_api.focus();
        });
        $('#can_size').change(function(e) {
          jcrop_api.setOptions({ allowResize: !!this.checked });
          jcrop_api.focus();
        });
        $('#ar_lock').change(function(e) {
          jcrop_api.setOptions(this.checked?
            { aspectRatio: 4/3 }: { aspectRatio: 0 });
          jcrop_api.focus();
        });
        $('#size_lock').change(function(e) {
          jcrop_api.setOptions(this.checked? {
            minSize: [ 80, 80 ],
            maxSize: [ 350, 350 ]
          }: {
            minSize: [ 0, 0 ],
            maxSize: [ 0, 0 ]
          });
          jcrop_api.focus();
        });

    }

    var demo6 = function() {
        var api;

        $('#demo6').Jcrop({
          // start off with jcrop-light class
          bgOpacity: 0.5,
          bgColor: 'white',
          addClass: 'jcrop-light'
        },function(){
          api = this;
          api.setSelect([130,65,130+350,65+285]);
          api.setOptions({ bgFade: true });
          api.ui.selection.addClass('jcrop-selection');
        });

        $('#buttonbar').on('click','button',function(e){
          var $t = $(this), $g = $t.closest('.btn-group');
          $g.find('button.active').removeClass('active');
          $t.addClass('active');
          $g.find('[data-setclass]').each(function(){
            var $th = $(this), c = $th.data('setclass'),
              a = $th.hasClass('active');
            if (a) {
              api.ui.holder.addClass(c);
              switch(c){
                case 'jcrop-light':
                  api.setOptions({ bgColor: 'white', bgOpacity: 0.5 });
                  break;

                case 'jcrop-dark':
                  api.setOptions({ bgColor: 'black', bgOpacity: 0.4 });
                  break;

                case 'jcrop-normal':
                  api.setOptions({
                    bgColor: $.Jcrop.defaults.bgColor,
                    bgOpacity: $.Jcrop.defaults.bgOpacity
                  });
                  break;
              }
            }
            else api.ui.holder.removeClass(c);
          });
        });
    }

    var demo7 = function() {
        // I did JSON.stringify(jcrop_api.tellSelect()) on a crop I liked:
        var c = {"x":13,"y":7,"x2":487,"y2":107,"w":474,"h":100};

        $('#demo7').Jcrop({
          bgFade: true,
          setSelect: [c.x,c.y,c.x2,c.y2]
        });
    }

    var demo8 = function() {
        $('#demo8').Jcrop({
          aspectRatio: 1,
          onSelect: updateCoords
        });

        function updateCoords(c)
          {
            $('#crop_x').val(c.x);
            $('#crop_y').val(c.y);
            $('#crop_w').val(c.w);
            $('#crop_h').val(c.h);
          };

          $('#demo8_form').submit(function(){
            if (parseInt($('#crop_w').val())) return true;
            alert('Please select a crop region then press submit.');
            return false;
            });

    }

    var handleResponsive = function() {
      if ($(window).width() <= 1024 && $(window).width() >= 678) {
        $('.responsive-1024').each(function(){
          $(this).attr("data-class", $(this).attr("class"));
          $(this).attr("class", 'responsive-1024 col-md-12');
        });
      } else {
        $('.responsive-1024').each(function(){
          if ($(this).attr("data-class")) {
            $(this).attr("class", $(this).attr("data-class"));
            $(this).removeAttr("data-class");
          }
        });
      }
    }

    return {
        //main function to initiate the module
        init: function () {

            if (!jQuery().Jcrop) {;
                return;
            }

            App.addResizeHandler(handleResponsive);
            handleResponsive();

            demo1();
            demo2();
            demo3();
            demo4();
            demo5();
            demo6();
            demo7();
            demo8();
        }

    };

}();

jQuery(document).ready(function() {
    FormImageCrop.init();
});


text:
package com.orientechnologies.orient.server.distributed;

import junit.framework.Assert;

import org.junit.Ignore;
import org.junit.Test;

import com.orientechnologies.orient.core.exception.OValidationException;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.tinkerpop.blueprints.impls.orient.OrientGraph;
import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory;
import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx;
import com.tinkerpop.blueprints.impls.orient.OrientVertex;
import com.tinkerpop.blueprints.impls.orient.OrientVertexType;

/**
 * Start 3 servers and wait for external commands
 */
public class ServerClusterSchemaTest extends AbstractServerClusterTest {
  final static int SERVERS = 3;

  public String getDatabaseName() {
    return "distributed";
  }

  @Test
  @Ignore
  public void test() throws Exception {
    init(SERVERS);
    prepare(false);
    execute();
  }

  @Override
  protected void executeTest() throws Exception {
    for (int s = 0; s < SERVERS; ++s) {
      OrientGraphFactory factory = new OrientGraphFactory("plocal:target/server" + s + "/databases/" + getDatabaseName());
      OrientGraphNoTx g = factory.getNoTx();

      try {
        System.out.println("Creating vertex class Client" + s + " against server " + g + "...");
        OrientVertexType t = g.createVertexType("Client" + s);
        t.createProperty("name", OType.STRING).setMandatory(true);

        System.out.println("Creating vertex class Knows" + s + " against server " + g + "...");
        g.createEdgeType("Knows" + s);
      } finally {
        g.shutdown();
      }
    }

    for (int s = 0; s < SERVERS; ++s) {
      OrientGraphFactory factory = new OrientGraphFactory("plocal:target/server" + s + "/databases/" + getDatabaseName());
      OrientGraphNoTx g = factory.getNoTx();

      try {
        for (int i = 0; i < SERVERS; ++i) {
          Assert.assertNotNull(g.getVertexType("Client" + i));
          Assert.assertNotNull(g.getEdgeType("Knows" + i));
        }
      } finally {
        g.shutdown();
      }
    }

    for (int s = 0; s < SERVERS; ++s) {
      OrientGraphFactory factory = new OrientGraphFactory("plocal:target/server" + s + "/databases/" + getDatabaseName());
      OrientGraphNoTx g = factory.getNoTx();

      try {
        for (int i = 0; i < SERVERS; ++i) {
          try {
            final OrientVertex v = g.addVertex("class:" + "Client" + i);
            Assert.assertTrue(false);
          } catch (OValidationException e) {
            // EXPECTED
          }
        }
      } finally {
        g.shutdown();
      }
    }

    for (int s = 0; s < SERVERS; ++s) {
      OrientGraphFactory factory = new OrientGraphFactory("plocal:target/server" + s + "/databases/" + getDatabaseName());
      OrientGraph g = factory.getTx();

      try {
        for (int i = 0; i < SERVERS; ++i) {
          try {
            final OrientVertex v = g.addVertex("class:" + "Client" + i);
            Assert.assertTrue(false);
          } catch (OValidationException e) {
            // EXPECTED
          }
        }
      } finally {
        g.shutdown();
      }
    }
  }
}


text:
$tag = "package-2021-07"
Write-Host "Generating control plane SDK from tag" $tag

# This is the version of the control plane SDK itself
$newVersion = "1.1.0"
Write-Host "Generated control plane SDK will have version" $newVersion

autorest https://raw.githubusercontent.com/Azure/azure-rest-api-specs/master/specification/iothub/resource-manager/readme.md `
	--version=3.1.3 `
	--use=@autorest/java@4.0.31 `
	--java.azure-libraries-for-java-folder=../.. `
	--java.output-folder=./azure-resourcemanager-iothub `
	--java.namespace=com.azure.resourcemanager.iothub `
	--tag=$tag `
	--package-version=$newVersion `
	--java `
	--pipeline.modelerfour.additional-checks=false `
	--pipeline.modelerfour.lenient-model-deduplication=true `
	--azure-arm `
	--verbose `
	--sdk-integration `
	--fluent=lite `
	--java.fluent=lite `
	--java.license-header=MICROSOFT_MIT_SMALL `
	--generate-samples


text:
module WatchBuild
  VERSION = "0.1.3"
  DESCRIPTION = "Get a notification once your iTunes Connect build is finished processing"
end