text:
(function(stylesheet, stencils)
{
	// Callbacks:
	// mxClientOnLoad is called  after the script is loaded with the stylesheet and the function to create a
	//     graph (wich takes the container as an argument and returns the graph instance that was created).
	// mxClientOnCreate is called when a graph has been created with the graph.
	mxStencilRegistry.dynamicLoading = false;

	// Adds CSS for tooltips
	try
	{
		var style = document.createElement('style')
		style.type = 'text/css'
		style.innerHTML = ['div.mxTooltip {',
			'-webkit-box-shadow: 3px 3px 12px #C0C0C0;',
			'-moz-box-shadow: 3px 3px 12px #C0C0C0;',
			'box-shadow: 3px 3px 12px #C0C0C0;',
			'background: #FFFFCC;',
			'border-style: solid;',
			'border-width: 1px;',
			'border-color: black;',
			'font-family: Arial;',
			'font-size: 8pt;',
			'position: absolute;',
			'cursor: default;',
			'padding: 4px;',
			'color: black;}'].join('\n');
		document.getElementsByTagName('head')[0].appendChild(style)
	}
	catch (e)
	{
		// ignore
	}

	var originalNoFo = mxClient.NO_FO;
	var mathJaxLoading = (typeof(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined');
	var mathJaxQueue = [];

	function loadMathJax()
	{
		// Uses existing configuration if MathJax already in page
		if (!mathJaxLoading)
		{
			mathJaxLoading = true;

			window.MathJax =
			{
				skipStartupTypeset: true,
				showMathMenu: false,
				messageStyle: 'none',
				AuthorInit: function ()
				{
					MathJax.Hub.Config({"HTML-CSS":{availableFonts:[],webFont:"STIX-Web",imageFont:null}});

					MathJax.Hub.Register.StartupHook('Begin', function()
					{
						for (var i = 0; i < mathJaxQueue.length; i++)
						{
							MathJax.Hub.Queue(['Typeset', MathJax.Hub, mathJaxQueue[i]]);
						}
					});
			    }
			};

			var script = document.createElement('script');
			script.type = 'text/javascript';
			script.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js?config=TeX-MML-AM_HTMLorMML';
			document.getElementsByTagName('head')[0].appendChild(script);
		}
	};

	function addMathJaxGraph(graph)
	{
		// Initial rendering when MathJax finished loading
		if (typeof(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined')
		{
			MathJax.Hub.Queue(['Typeset', MathJax.Hub, graph.container]);
		}
		else
		{
			mathJaxQueue.push(graph.container);
		}

		// Rendering math again on repaint
		graph.addListener(mxEvent.SIZE, function(sender, evt)
		{
			if (typeof(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined')
			{
				MathJax.Hub.Queue(['Typeset', MathJax.Hub, graph.container]);
			}
		});
	};

	// Handles relative images
	mxGraph.prototype.getImageFromBundles = function(key)
	{
		if (key != null)
		{
			if (key.substring(0, 7) != 'http://' && key.substring(0, 8) != 'https://' && key.substring(0, 10) != 'data:image')
			{
				if (key.charAt(0) == '/')
				{
					key = key.substring(1, key.length);
				}

				key = 'https://www.draw.io/' + key;
			}

			return key;
		}

		return null;
	};

	if (stencils != null)
	{
		for (var i = 0; i < stencils.length; i++)
		{
			var xmlDoc = mxUtils.parseXml(stencils[i]);
			mxStencilRegistry.parseStencilSet(xmlDoc.documentElement);
		}
	}

	// Panning for touch devices
	if (mxClient.IS_TOUCH)
	{
		mxPanningHandler.prototype.isPanningTrigger = function(me)
		{
			return true;
		};
	}

	(function()
	{
		function initGraph(container)
		{
			try
			{
				var child = container.firstChild;

				while (child != null && child.nodeType != mxConstants.NODETYPE_ELEMENT)
				{
					child = child.nextSibling;
				}

				var xml = mxUtils.trim(child.innerHTML);
				container.innerHTML = '';

				// Instance needed for decompress helper function
				var graph = new Graph(container);

				if (xml.substring(0, 4) == '<')
				{
					xml = xml.replace(/</g, '<').replace(/>/g, '>').
						replace(/&gt;/g, '>').replace(/&lt;/g, '<').
						replace(/&quot;/g, '"').replace(/
/g, '\n');
				}
				else if (xml.substring(0, 3) == '%3C')
				{
					xml = decodeURIComponent(xml);
				}
				else
				{
					xml = graph.decompress(xml);
				}

				var xmlDocument = mxUtils.parseXml(xml);
				var configNode = null;
				var diagrams = null;

				if (xmlDocument.documentElement != null && xmlDocument.documentElement.nodeName == 'mxfile')
				{
					diagrams = xmlDocument.documentElement.getElementsByTagName('diagram');
					configNode = xmlDocument.documentElement;

					if (diagrams.length > 0)
					{
						xml = mxUtils.getTextContent(diagrams[0]);
						xml = graph.decompress(xml);
						xmlDocument = mxUtils.parseXml(xml);
					}
				}

				if (xmlDocument.documentElement != null && xmlDocument.documentElement.nodeName == 'mxGraphModel')
				{
					var decoder = new mxCodec(xmlDocument);
					var node = xmlDocument.documentElement;

					if (configNode == null)
					{
						configNode = node;
					}

					graph.resetViewOnRootChange = false;
					graph.setEnabled(false);

					if (diagrams != null && diagrams.length > 0)
					{
						/**
						 * Adds placeholder for %page% and %pagenumber%
						 */
						var graphGetGlobalVariable = graph.getGlobalVariable;

						graph.getGlobalVariable = function(name)
						{
							if (name == 'page')
							{
								return diagrams[0].getAttribute('name') || 'Page-1';
							}
							else if (name == 'pagenumber')
							{
								return 1;
							}

							return graphGetGlobalVariable.apply(this, arguments);
						};
					}

					graph.foldingEnabled = configNode.getAttribute('nav') == '1';
					graph.cellRenderer.forceControlClickHandler = graph.foldingEnabled;

					var tooltips = configNode.getAttribute('tooltips');

			    	if (tooltips != '0')
			    	{
			    		graph.setTooltips(true);
			    	}
			    	else
			    	{
			    		graph.setTooltips(false);
			    	}

					// Workaround for parent div ignoring child size
					if (mxClient.IS_VML)
					{
						var canvas = graph.view.getCanvas();

						if (canvas != null && canvas.nodeName == 'DIV')
						{
							canvas.style.position = 'relative';
						}
					}

					// Loads the stylesheet
					if (stylesheet != null)
					{
						var xmlDoc = mxUtils.parseXml(stylesheet);
						var dec = new mxCodec(xmlDoc);
						dec.decode(xmlDoc.documentElement, graph.getStylesheet());
					}

					var math = configNode.getAttribute('math');

					if (math == '1')
					{
						mxClient.NO_FO = true;
						loadMathJax();
					}

					// Enables panning with left mouse button
					var pan = configNode.getAttribute('pan');

					if (pan != '0')
					{
						graph.panningHandler.useLeftButtonForPanning = true;
						graph.panningHandler.ignoreCell = true;
						container.style.cursor = 'move';
						graph.setPanning(true);
					}
					else
					{
						container.style.cursor = 'default';
					}

					var resize = configNode.getAttribute('resize');
					var border = Number(configNode.getAttribute('border') || 0);
					graph.border = border;

					var fit = configNode.getAttribute('fit');

					if ((container.style.width != '100%' && fit != '1' && resize != '0') ||
						(container.style.width == '' && container.style.height == ''))
					{
						graph.resizeContainer = true;
						graph.centerZoom = false;
					}
					else
					{
						// Updates the container height for autosize width
						if (resize != '0' && container.style.width == '100%' && container.style.height == '')
						{
							graph.resizeContainer = true;
							graph.centerZoom = false;

							graph.doResizeContainer = function(width, height)
							{
								// Fixes container size for different box models
								if (mxClient.IS_IE)
								{
									if (mxClient.IS_QUIRKS)
									{
										var borders = this.getBorderSizes();

										// max(2, ...) required for native IE8 in quirks mode
										width += Math.max(2, borders.x + borders.width + 1);
										height += Math.max(2, borders.y + borders.height + 1);
									}
									else if (document.documentMode >= 9)
									{
										width += 3;
										height += 5;
									}
									else
									{
										width += 1;
										height += 1;
									}
								}
								else
								{
									height += 1;
								}

								if (this.maximumContainerSize != null)
								{
									width = Math.min(this.maximumContainerSize.width, width);
									height = Math.min(this.maximumContainerSize.height, height);
								}

								this.container.style.height = Math.ceil(height + 18) + 'px';
							};
						}
						else
						{
							graph.centerZoom = true;
						}
					}

					// Adds handling for hyperlinks, tooltips
					var links = configNode.getAttribute('links');
					var hl = configNode.getAttribute('highlight');

					if (links != '0' || tooltips != '0')
					{
						var cursor = container.style.cursor;
				    	var tol = graph.getTolerance();

						graph.addMouseListener(
						{
						    currentState: null,
						    currentLink: null,
						    highlight: (hl != null && hl != '' && hl != mxConstants.NONE) ?
						    	new mxCellHighlight(graph, hl, 2) : null,
						    startX: 0,
						    startY: 0,
						    mouseDown: function(sender, me)
						    {
						    	this.startX = me.getGraphX();
						    	this.startY = me.getGraphY();
						    },
						    mouseMove: function(sender, me)
						    {
						    	if (graph.isMouseDown)
						    	{
						    		if (this.currentLink != null)
						    		{
								    	var dx = Math.abs(this.startX - me.getGraphX());
								    	var dy = Math.abs(this.startY - me.getGraphY());

								    	if (dx > tol || dy > tol)
								    	{
								    		this.clear();
								    	}
						    		}
						    	}
						    	else
						    	{
							    	if (this.currentState != null && (me.getState() == this.currentState || me.getState() == null) &&
							    		graph.intersects(this.currentState, me.getGraphX(), me.getGraphY()))
							    	{
						    			return;
							    	}

									var tmp = graph.view.getState(me.getCell());

							      	if (tmp != this.currentState)
							      	{
							        	if (this.currentState != null)
							        	{
							          		this.clear();
							        	}

						        		this.currentState = tmp;

							        	if (this.currentState != null)
							        	{
							          		this.activate(this.currentState);
							        	}
							      	}
						    	}
						    },
						    mouseUp: function(sender, me)
						    {
						    	var tmp = this.currentLink;
						    	this.clear();

						    	if (tmp != null)
						    	{
						    		if (tmp.charAt(0) == '#')
						    		{
						    			window.location.hash = tmp;
						    		}
						    		else
						    		{
						    			window.open(tmp);
						    		}
						    	}
						    },
						    activate: function(state)
						    {
						    	this.currentLink = graph.getLinkForCell(state.cell);

						    	if (this.currentLink != null)
						    	{
						    		container.style.cursor = 'pointer';

						    		if (this.highlight != null)
						    		{
						    			this.highlight.highlight(state);
						    		}
							    }
						    },
						    clear: function()
						    {
						    	container.style.cursor = cursor;
						    	this.currentState = null;
						    	this.currentLink = null;

						    	if (this.highlight != null)
						    	{
						    		this.highlight.hide();
						    	}
						    }
						});
					}

					var x0 = Number(configNode.getAttribute('x0') || 0);
					var y0 = Number(configNode.getAttribute('y0') || 0);
					graph.view.translate.x = -x0 + border;
					graph.view.translate.y = -y0 + border;

					function graphAdded(node)
					{
						var img = node.getAttribute('backgroundImage');

						if (img != null)
						{
							img = JSON.parse(img);
							graph.setBackgroundImage(new mxImage(img.src, img.width, img.height));
							graph.view.validateBackgroundImage();
						}

						if (fit != '0')
						{
							graph.fit(border);
						}

						if (math == '1')
						{
							addMathJaxGraph(graph);
						}

						// Keeps hashtag links on same page
						var links = graph.container.getElementsByTagName('a');

						if (links != null)
						{
							for (var i = 0; i < links.length; i++)
							{
								var href = links[i].getAttribute('href');

								if (href != null && href.charAt(0) == '#' &&
									links[i].getAttribute('target') == '_blank')
								{
									links[i].removeAttribute('target');
								}
							}
						}
					};

					// Load from URL via url attribute
					var url = configNode.getAttribute('url');

					if (url != null)
					{
						try
						{
							// Workaround for unsupported CORS in IE9 XHR
							var xhr = (navigator.userAgent.indexOf('MSIE 9') > 0) ? new XDomainRequest() : new XMLHttpRequest();
							xhr.open('GET', url);

						    xhr.onload = mxUtils.bind(this, function()
						    {
						    	try
						    	{
									if (math == '1')
									{
										mxClient.NO_FO = true;
									}

							    	var data = (xhr.getText != null) ? xhr.getText() : xhr.responseText;

							    	if (data != null)
							    	{
							    		var newDocument = mxUtils.parseXml(data);

							    		// LATER: Add support for .png (with XML) files
							    		// Adds support for HTML
							    		if (newDocument != null && newDocument.documentElement.nodeName == 'html')
							    		{
							    			var divs = newDocument.documentElement.getElementsByTagName('div');

							    			if (divs.length > 0 && divs[0].getAttribute('class') == 'mxgraph')
							    			{
							    				var divs2 = divs[0].getElementsByTagName('div');

							    				if (divs2.length > 0)
							    				{
							    					var data = mxUtils.getTextContent(divs2[0]);
							    	        		data = graph.decompress(data);

							    	        		if (data.length > 0)
							    	        		{
							    	        			newDocument = mxUtils.parseXml(data);
							    	        		}
							    				}
							    			}
							    		}

							    		if (newDocument != null && newDocument.documentElement.nodeName == 'svg')
							    		{
							    			var tmp = newDocument.documentElement.getAttribute('content');

							    			if (tmp != null && tmp.charAt(0) != '<' && tmp.charAt(0) != '%')
							    			{
							    				tmp = unescape((window.atob) ? atob(tmp) : Base64.decode(cont, tmp));
							    			}

							    			if (tmp != null && tmp.charAt(0) == '%')
							    			{
							    				tmp = decodeURIComponent(tmp);
							    			}

							    			if (tmp != null && tmp.length > 0)
							    			{
							    				newDocument = mxUtils.parseXml(tmp);
							    			}
							    		}

							    		if (newDocument.documentElement.nodeName == 'mxfile')
							    		{
							    			var diagrams = newDocument.documentElement.getElementsByTagName('diagram');

							    			if (diagrams.length > 0)
							    			{
							    				data = graph.decompress(mxUtils.getTextContent(diagrams[0]));
							    				newDocument = mxUtils.parseXml(data);
							    			}
							    		}

							    		decoder = new mxCodec(newDocument);
							    		decoder.decode(newDocument.documentElement, graph.getModel());
							    		graphAdded(newDocument.documentElement);
							    	}
							    	else
							    	{
							    		graph.container.innerHTML = 'Cannot load ' + url;
							    	}

							    	mxClient.NO_FO = originalNoFo;
						    	}
								catch (e)
								{
									graph.container.innerHTML = 'Cannot load ' + url + ': ' + e.message;
								}
						    });

						    xhr.onerror = function()
						    {
						    	graph.container.innerHTML = 'Cannot load ' + url;
						    };

						    xhr.send();
						}
						catch (e)
						{
							graph.container.innerHTML = 'Cannot load ' + url + ': ' + e.message;
						}
					}
					else
					{
						decoder.decode(node, graph.getModel());
						graphAdded(node);
					}

					if (container.style.width != '100%' && fit != '0' && resize == '1')
					{
						graph.resizeContainer = true;
						graph.centerZoom = false;
					}

					// Adds zoom, edit etc in top, left corner
					var buttons = document.createElement('div');
					buttons.style.position = 'absolute';
					buttons.style.overflow = 'visible';
					buttons.style.cursor = 'pointer';

					var bs = graph.getBorderSizes();

					var left = 0;
					var fontSize = 10;
					var bw = 16;
					var bh = 16;

					if (mxClient.IS_QUIRKS)
					{
						bw -= 1;
						bh -= 1;
					}
					else if (mxClient.IS_TOUCH)
					{
						bw = 24;
						bh = 24;
						var fontSize = 14;
					}

					function addButton(label, funct)
					{
						var btn = document.createElement('div');
						btn.style.position = 'absolute';
						btn.style.border = '1px solid gray';
						btn.style.textAlign = 'center';
						btn.style.cursor = 'hand';
						btn.style.width = bw + 'px';
						btn.style.height = bh + 'px';
						btn.style.left = left + 'px';
						btn.style.top = '0px';
						btn.style.backgroundColor = 'white';
						mxUtils.setOpacity(btn, 50);

						var table = document.createElement('table');
						table.style.borderWidth = '0px';
						table.style.width = '100%';
						table.style.height = '100%';
						var tbody = document.createElement('tbody');
						var tr = document.createElement('tr');
						var td = document.createElement('td');
						td.style.verticalAlign = 'middle';
						td.style.textAlign = 'center';
						td.style.fontSize = fontSize + 'px';
						td.style.padding = '0px';
						mxUtils.write(td, label);
						tr.appendChild(td);
						tbody.appendChild(tr);
						table.appendChild(tbody);
						btn.appendChild(table);

						mxEvent.addListener(btn, (mxClient.IS_POINTER) ? 'pointerdown' : 'mousedown', function(evt)
						{
							mxEvent.consume(evt);
						});

						mxEvent.addListener(btn, (mxClient.IS_POINTER) ? 'pointerup' : 'mouseup', function(evt)
						{
							funct();
							mxEvent.consume(evt);
						});

						if (!mxClient.IS_POINTER && mxClient.IS_TOUCH)
						{
							mxEvent.addListener(btn, 'touchstart', function(evt)
							{
								mxEvent.consume(evt);
							});

							mxEvent.addListener(btn, 'touchend', function(evt)
							{
								funct();
								mxEvent.consume(evt);
							});
						}

						left += bw;
						buttons.appendChild(btn);

						return btn;
					};

					var zoom = configNode.getAttribute('zoom');

					if (zoom != '0')
					{
						addButton('+', function()
						{
							graph.zoomIn();
						});

						addButton('-', function()
						{
							graph.zoomOut();
						});
					}

					var edit = configNode.getAttribute('edit');

					if (edit != null)
					{
						var button = addButton('', function()
						{
							// _blank is a special value to open a new editor
							// in client mode and send the XML as a message
							if (edit == '_blank')
							{
								if (url != null)
								{
									window.open('https://www.draw.io/#U' + encodeURIComponent(url));
								}
								else
								{
									var wnd = null;

									var receive = function(evt)
									{
										if (evt.data == 'ready' && evt.source == wnd)
										{
											wnd.postMessage(xml, '*');
											window.removeEventListener('message', receive);
										}
									};

									window.addEventListener('message', receive);
									wnd = window.open('https://www.draw.io/?client=1');
								}
							}
							else
							{
								window.open(edit);
							}
						});

						// Do not use HTML entity to avoid problems with XHTML
						button.innerHTML = '...';
					}

					function show()
					{
						buttons.style.top = (container.offsetTop + bs.y) + 'px';
						buttons.style.left = (container.offsetLeft + bs.x) + 'px';
						buttons.style.visibility = 'visible';
					};

					if (!mxClient.IS_POINTER && !mxClient.IS_TOUCH)
					{
						function hide()
						{
							buttons.style.visibility = 'hidden';
						};

						mxEvent.addListener(container, 'mouseover', show);
						mxEvent.addListener(buttons, 'mouseover', show);
						mxEvent.addListener(container, 'mouseout', hide);
						mxEvent.addListener(buttons, 'mouseout', hide);
						hide();
					}
					else
					{
						show();
					}

					if (buttons.firstChild != null)
					{
						if (container.nextSibling != null)
						{
							container.parentNode.insertBefore(buttons, container.nextSibling);
						}
						else
						{
							container.parentNode.appendChild(buttons);
						}
					}

					if (typeof(window.mxClientOnCreate) == 'function')
					{
						window.mxClientOnCreate(graph);
					}
				}
			}
			catch (err)
			{
				if (window.console != null)
				{
					console.log('Error:', err);
				}
			}

			mxClient.NO_FO = originalNoFo;

			return graph;
		};

		if (typeof(mxClientOnLoad) == 'function')
		{
			mxClientOnLoad(stylesheet, initGraph);
		}
		else if (mxClient.isBrowserSupported())
		{
			var tmp = document.getElementsByTagName('*');
			var divs = [];

			for (var i = 0; i < tmp.length; i++)
			{
				divs.push(tmp[i]);
			}

			for (var i = 0; i < divs.length; i++)
			{
				if (divs[i].className.toString().indexOf('mxgraph') >= 0)
				{
					initGraph(divs[i]);
				}
			}
		}
	})();
// Last line will be replaced by servlet for passing arguments.


text:
/*
 * Grafeas API
 * An API to insert and retrieve annotations on cloud artifacts.
 *
 * OpenAPI spec version: v1alpha1
 *
 *
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen.git
 * Do not edit the class manually.
 */

package io.grafeas.model;

import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * A set of properties that uniquely identify a given Docker image.
 */
@ApiModel(description = "A set of properties that uniquely identify a given Docker image.")
@javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2018-06-04T13:20:14.121-07:00")
public class DockerImageFingerprint {
  @SerializedName("v1_name")
  private String v1Name = null;

  @SerializedName("v2_blob")
  private List<String> v2Blob = null;

  @SerializedName("v2_name")
  private String v2Name = null;

  public DockerImageFingerprint v1Name(String v1Name) {
    this.v1Name = v1Name;
    return this;
  }

   /**
   * The layer-id of the final layer in the Docker image's v1 representation. This field can be used as a filter in list requests.
   * @return v1Name
  **/
  @ApiModelProperty(value = "The layer-id of the final layer in the Docker image's v1 representation. This field can be used as a filter in list requests.")
  public String getV1Name() {
    return v1Name;
  }

  public void setV1Name(String v1Name) {
    this.v1Name = v1Name;
  }

  public DockerImageFingerprint v2Blob(List<String> v2Blob) {
    this.v2Blob = v2Blob;
    return this;
  }

  public DockerImageFingerprint addV2BlobItem(String v2BlobItem) {
    if (this.v2Blob == null) {
      this.v2Blob = new ArrayList<String>();
    }
    this.v2Blob.add(v2BlobItem);
    return this;
  }

   /**
   * The ordered list of v2 blobs that represent a given image.
   * @return v2Blob
  **/
  @ApiModelProperty(value = "The ordered list of v2 blobs that represent a given image.")
  public List<String> getV2Blob() {
    return v2Blob;
  }

  public void setV2Blob(List<String> v2Blob) {
    this.v2Blob = v2Blob;
  }

  public DockerImageFingerprint v2Name(String v2Name) {
    this.v2Name = v2Name;
    return this;
  }

   /**
   * Output only. The name of the image's v2 blobs computed via:   [bottom] := v2_blob[bottom]   [N] := sha256(v2_blob[N] + \" \" + v2_name[N+1]) Only the name of the final blob is kept. This field can be used as a filter in list requests.
   * @return v2Name
  **/
  @ApiModelProperty(value = "Output only. The name of the image's v2 blobs computed via:   [bottom] := v2_blob[bottom]   [N] := sha256(v2_blob[N] + \" \" + v2_name[N+1]) Only the name of the final blob is kept. This field can be used as a filter in list requests.")
  public String getV2Name() {
    return v2Name;
  }

  public void setV2Name(String v2Name) {
    this.v2Name = v2Name;
  }

  @Override
  public boolean equals(java.lang.Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    DockerImageFingerprint dockerImageFingerprint = (DockerImageFingerprint) o;
    return Objects.equals(this.v1Name, dockerImageFingerprint.v1Name) &&
        Objects.equals(this.v2Blob, dockerImageFingerprint.v2Blob) &&
        Objects.equals(this.v2Name, dockerImageFingerprint.v2Name);
  }

  @Override
  public int hashCode() {
    return Objects.hash(v1Name, v2Blob, v2Name);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();
    sb.append("class DockerImageFingerprint {\n");

    sb.append("    v1Name: ").append(toIndentedString(v1Name)).append("\n");
    sb.append("    v2Blob: ").append(toIndentedString(v2Blob)).append("\n");
    sb.append("    v2Name: ").append(toIndentedString(v2Name)).append("\n");
    sb.append("}");
    return sb.toString();
  }

  /**
   * Convert the given object to string with each line indented by 4 spaces
   * (except the first line).
   */
  private String toIndentedString(java.lang.Object o) {
    if (o == null) {
      return "null";
    }
    return o.toString().replace("\n", "\n    ");
  }

}

redpajama_set_name: RedPajamaGithub


text:
import numpy as np

from scipy import optimize

from ..base import BaseEstimator, RegressorMixin
from ._base import LinearModel
from ..utils import axis0_safe_slice
from ..utils.validation import _check_sample_weight
from ..utils.validation import _deprecate_positional_args
from ..utils.extmath import safe_sparse_dot
from ..utils.optimize import _check_optimize_result

def _huber_loss_and_gradient(w, X, y, epsilon, alpha, sample_weight=None):
    """Returns the Huber loss and the gradient.

    Parameters
    ----------
    w : ndarray, shape (n_features + 1,) or (n_features + 2,)
        Feature vector.
        w[:n_features] gives the coefficients
        w[-1] gives the scale factor and if the intercept is fit w[-2]
        gives the intercept factor.

    X : ndarray of shape (n_samples, n_features)
        Input data.

    y : ndarray of shape (n_samples,)
        Target vector.

    epsilon : float
        Robustness of the Huber estimator.

    alpha : float
        Regularization parameter.

    sample_weight : ndarray of shape (n_samples,), default=None
        Weight assigned to each sample.

    Returns
    -------
    loss : float
        Huber loss.

    gradient : ndarray, shape (len(w))
        Returns the derivative of the Huber loss with respect to each
        coefficient, intercept and the scale as a vector.
    """
    _, n_features = X.shape
    fit_intercept = (n_features + 2 == w.shape[0])
    if fit_intercept:
        intercept = w[-2]
    sigma = w[-1]
    w = w[:n_features]
    n_samples = np.sum(sample_weight)

    # Calculate the values where |y - X'w -c / sigma| > epsilon
    # The values above this threshold are outliers.
    linear_loss = y - safe_sparse_dot(X, w)
    if fit_intercept:
        linear_loss -= intercept
    abs_linear_loss = np.abs(linear_loss)
    outliers_mask = abs_linear_loss > epsilon * sigma

    # Calculate the linear loss due to the outliers.
    # This is equal to (2 * M * |y - X'w -c / sigma| - M**2) * sigma
    outliers = abs_linear_loss[outliers_mask]
    num_outliers = np.count_nonzero(outliers_mask)
    n_non_outliers = X.shape[0] - num_outliers

    # n_sq_outliers includes the weight give to the outliers while
    # num_outliers is just the number of outliers.
    outliers_sw = sample_weight[outliers_mask]
    n_sw_outliers = np.sum(outliers_sw)
    outlier_loss = (2. * epsilon * np.sum(outliers_sw * outliers) -
                    sigma * n_sw_outliers * epsilon ** 2)

    # Calculate the quadratic loss due to the non-outliers.-
    # This is equal to |(y - X'w - c)**2 / sigma**2| * sigma
    non_outliers = linear_loss[~outliers_mask]
    weighted_non_outliers = sample_weight[~outliers_mask] * non_outliers
    weighted_loss = np.dot(weighted_non_outliers.T, non_outliers)
    squared_loss = weighted_loss / sigma

    if fit_intercept:
        grad = np.zeros(n_features + 2)
    else:
        grad = np.zeros(n_features + 1)

    # Gradient due to the squared loss.
    X_non_outliers = -axis0_safe_slice(X, ~outliers_mask, n_non_outliers)
    grad[:n_features] = (
        2. / sigma * safe_sparse_dot(weighted_non_outliers, X_non_outliers))

    # Gradient due to the linear loss.
    signed_outliers = np.ones_like(outliers)
    signed_outliers_mask = linear_loss[outliers_mask] < 0
    signed_outliers[signed_outliers_mask] = -1.0
    X_outliers = axis0_safe_slice(X, outliers_mask, num_outliers)
    sw_outliers = sample_weight[outliers_mask] * signed_outliers
    grad[:n_features] -= 2. * epsilon * (
        safe_sparse_dot(sw_outliers, X_outliers))

    # Gradient due to the penalty.
    grad[:n_features] += alpha * 2. * w

    # Gradient due to sigma.
    grad[-1] = n_samples
    grad[-1] -= n_sw_outliers * epsilon ** 2
    grad[-1] -= squared_loss / sigma

    # Gradient due to the intercept.
    if fit_intercept:
        grad[-2] = -2. * np.sum(weighted_non_outliers) / sigma
        grad[-2] -= 2. * epsilon * np.sum(sw_outliers)

    loss = n_samples * sigma + squared_loss + outlier_loss
    loss += alpha * np.dot(w, w)
    return loss, grad

class HuberRegressor(LinearModel, RegressorMixin, BaseEstimator):
    """Linear regression model that is robust to outliers.

    The Huber Regressor optimizes the squared loss for the samples where
    ``|(y - X'w) / sigma| < epsilon`` and the absolute loss for the samples
    where ``|(y - X'w) / sigma| > epsilon``, where w and sigma are parameters
    to be optimized. The parameter sigma makes sure that if y is scaled up
    or down by a certain factor, one does not need to rescale epsilon to
    achieve the same robustness. Note that this does not take into account
    the fact that the different features of X may be of different scales.

    This makes sure that the loss function is not heavily influenced by the
    outliers while not completely ignoring their effect.

    Read more in the :ref:`User Guide <huber_regression>`

    .. versionadded:: 0.18

    Parameters
    ----------
    epsilon : float, greater than 1.0, default=1.35
        The parameter epsilon controls the number of samples that should be
        classified as outliers. The smaller the epsilon, the more robust it is
        to outliers.

    max_iter : int, default=100
        Maximum number of iterations that
        ``scipy.optimize.minimize(method="L-BFGS-B")`` should run for.

    alpha : float, default=0.0001
        Regularization parameter.

    warm_start : bool, default=False
        This is useful if the stored attributes of a previously used model
        has to be reused. If set to False, then the coefficients will
        be rewritten for every call to fit.
        See :term:`the Glossary <warm_start>`.

    fit_intercept : bool, default=True
        Whether or not to fit the intercept. This can be set to False
        if the data is already centered around the origin.

    tol : float, default=1e-05
        The iteration will stop when
        ``max{|proj g_i | i = 1, ..., n}`` <= ``tol``
        where pg_i is the i-th component of the projected gradient.

    Attributes
    ----------
    coef_ : array, shape (n_features,)
        Features got by optimizing the Huber loss.

    intercept_ : float
        Bias.

    scale_ : float
        The value by which ``|y - X'w - c|`` is scaled down.

    n_iter_ : int
        Number of iterations that
        ``scipy.optimize.minimize(method="L-BFGS-B")`` has run for.

        .. versionchanged:: 0.20

            In SciPy <= 1.0.0 the number of lbfgs iterations may exceed
            ``max_iter``. ``n_iter_`` will now report at most ``max_iter``.

    outliers_ : array, shape (n_samples,)
        A boolean mask which is set to True where the samples are identified
        as outliers.

    Examples
    --------
    >>> import numpy as np
    >>> from sklearn.linear_model import HuberRegressor, LinearRegression
    >>> from sklearn.datasets import make_regression
    >>> rng = np.random.RandomState(0)
    >>> X, y, coef = make_regression(
    ...     n_samples=200, n_features=2, noise=4.0, coef=True, random_state=0)
    >>> X[:4] = rng.uniform(10, 20, (4, 2))
    >>> y[:4] = rng.uniform(10, 20, 4)
    >>> huber = HuberRegressor().fit(X, y)
    >>> huber.score(X, y)
    -7.284...
    >>> huber.predict(X[:1,])
    array([806.7200...])
    >>> linear = LinearRegression().fit(X, y)
    >>> print("True coefficients:", coef)
    True coefficients: [20.4923...  34.1698...]
    >>> print("Huber coefficients:", huber.coef_)
    Huber coefficients: [17.7906... 31.0106...]
    >>> print("Linear Regression coefficients:", linear.coef_)
    Linear Regression coefficients: [-1.9221...  7.0226...]

    References
    ----------
    .. [1] Peter J. Huber, Elvezio M. Ronchetti, Robust Statistics
           Concomitant scale estimates, pg 172
    .. [2] Art B. Owen (2006), A robust hybrid of lasso and ridge regression.
           https://statweb.stanford.edu/~owen/reports/hhu.pdf
    """
    @_deprecate_positional_args
    def __init__(self, *, epsilon=1.35, max_iter=100, alpha=0.0001,
                 warm_start=False, fit_intercept=True, tol=1e-05):
        self.epsilon = epsilon
        self.max_iter = max_iter
        self.alpha = alpha
        self.warm_start = warm_start
        self.fit_intercept = fit_intercept
        self.tol = tol

    def fit(self, X, y, sample_weight=None):
        """Fit the model according to the given training data.

        Parameters
        ----------
        X : array-like, shape (n_samples, n_features)
            Training vector, where n_samples in the number of samples and
            n_features is the number of features.

        y : array-like, shape (n_samples,)
            Target vector relative to X.

        sample_weight : array-like, shape (n_samples,)
            Weight given to each sample.

        Returns
        -------
        self : object
        """
        X, y = self._validate_data(
            X, y, copy=False, accept_sparse=['csr'], y_numeric=True,
            dtype=[np.float64, np.float32])

        sample_weight = _check_sample_weight(sample_weight, X)

        if self.epsilon < 1.0:
            raise ValueError(
                "epsilon should be greater than or equal to 1.0, got %f"
                % self.epsilon)

        if self.warm_start and hasattr(self, 'coef_'):
            parameters = np.concatenate(
                (self.coef_, [self.intercept_, self.scale_]))
        else:
            if self.fit_intercept:
                parameters = np.zeros(X.shape[1] + 2)
            else:
                parameters = np.zeros(X.shape[1] + 1)
            # Make sure to initialize the scale parameter to a strictly
            # positive value:
            parameters[-1] = 1

        # Sigma or the scale factor should be non-negative.
        # Setting it to be zero might cause undefined bounds hence we set it
        # to a value close to zero.
        bounds = np.tile([-np.inf, np.inf], (parameters.shape[0], 1))
        bounds[-1][0] = np.finfo(np.float64).eps * 10

        opt_res = optimize.minimize(
            _huber_loss_and_gradient, parameters, method="L-BFGS-B", jac=True,
            args=(X, y, self.epsilon, self.alpha, sample_weight),
            options={"maxiter": self.max_iter, "gtol": self.tol, "iprint": -1},
            bounds=bounds)

        parameters = opt_res.x

        if opt_res.status == 2:
            raise ValueError("HuberRegressor convergence failed:"
                             " l-BFGS-b solver terminated with %s"
                             % opt_res.message)
        self.n_iter_ = _check_optimize_result("lbfgs", opt_res, self.max_iter)
        self.scale_ = parameters[-1]
        if self.fit_intercept:
            self.intercept_ = parameters[-2]
        else:
            self.intercept_ = 0.0
        self.coef_ = parameters[:X.shape[1]]

        residual = np.abs(
            y - safe_sparse_dot(X, self.coef_) - self.intercept_)
        self.outliers_ = residual > self.scale_ * self.epsilon
        return self


text:
module Pod
  class Command

    class Clean < Command
      self.summary = "Remove Podfile.lock, Pods/ and *.xcworkspace"

      self.description = <<-DESC
        This command will simply remove Podfile.lock, Pods/ and *.xcworkspace from the current project.
      DESC

      def initialize(argv)
        @name = argv.shift_argument
        super
      end

      def validate!
        super
      end

      def run
        system('rm -rf Podfile.lock Pods *.xcworkspace')
      end
    end
  end
end


text:
import { Disposable, Event } from 'vscode';
import { RemoteSourceProvider } from './api/git';

export interface IRemoteSourceProviderRegistry {
	readonly onDidAddRemoteSourceProvider: Event<RemoteSourceProvider>;
	readonly onDidRemoveRemoteSourceProvider: Event<RemoteSourceProvider>;
	registerRemoteSourceProvider(provider: RemoteSourceProvider): Disposable;
	getRemoteProviders(): RemoteSourceProvider[];
}


text:
package auth

import (
	"net/http"

	"github.com/concourse/atc/db"
)

type teamAuthValidator struct {
	teamDBFactory db.TeamDBFactory
	jwtValidator  Validator
}

func NewTeamAuthValidator(
	teamDBFactory db.TeamDBFactory,
	jwtValidator Validator,
) Validator {
	return &teamAuthValidator{
		teamDBFactory: teamDBFactory,
		jwtValidator:  jwtValidator,
	}
}

func (v teamAuthValidator) IsAuthenticated(r *http.Request) bool {
	teamName := r.FormValue(":team_name")
	teamDB := v.teamDBFactory.GetTeamDB(teamName)
	team, found, err := teamDB.GetTeam()
	if err != nil || !found {
		return false
	}

	if !team.IsAuthConfigured() {
		return true
	}

	if team.BasicAuth != nil && NewBasicAuthValidator(team).IsAuthenticated(r) {
		return true
	}

	return v.jwtValidator.IsAuthenticated(r)
}


text:
//////////////////////////////////////////////////////////////////////////
//
// SOURCE CODE: https://github.com/yunfuliu/pixkit
//
// BEIRF: pixkit-ml contains machine learning related methods which have been published (on articles, e.g., journal or conference papers).
//	In addition, some frequently used related tools are also involved.
//
//////////////////////////////////////////////////////////////////////////
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cmath>
#include <iostream>
#include <vector>
#include <fstream>

#ifndef __PIXKIT_ML_HPP__
#define __PIXKIT_ML_HPP__

namespace pixkit{

	namespace clustering{

		/**
		* @brief		Clustering
		* @brief		paper: V. K. Dehariya, S. K. Shrivastava, R. C. Jain, "Clustering Of Image Data Set Using K-Means And Fuzzy K-Means Algorithms", IEEE International Conf. of CICN, 2010
		*
		* @author		HuangYu Liu (yf6204220@hotmail.com)
		* @date			Jan. 3, 2014
		*
		* @param		src:			Input data. The data type is vector.
		* @param		dst:			Output data. The data type is vector.
		* @param		seedNum:		How many seed do the user want to spread
		* @param		K:				How many universe do the user want to cluster, for instance, if you want to segment the input data to two different parts, then you must set the argument to 2.
		* @param		m:				The fuzzy coefficient. If set this argument close to 1.0, then the cluster effect like K-Means clustering.
		* @param		iterNum:		Set the iteration number. If set this argument bigger, then the error of result will be much smaller.
		* @param		initialPosi:	The argument is relate to the type, which is the next argument. The initial position can define by the user or computer.
		* @param		FUZZYCM_TYPE:	If user set the type to 1, then the initial position will define by the user. If user set the type to 2, then the initial position will define random by the computer.
		* @return		bool: true: successful, false: failure
		*/
		enum FUZZYCM_TYPE{FUZZYCM_USERDEFINEPOS, FUZZYCM_RANDPOS};
		bool fuzzyCMeans(const std::vector<std::vector<double>> &src, std::vector<std::vector<double>> &dst, const int seedNum, const int K, const double m, const int iterNum, std::vector<std::vector<double>> &initialPosi = std::vector<std::vector<double>>(), pixkit::clustering::FUZZYCM_TYPE type = FUZZYCM_RANDPOS,bool debug=false);

		/**
		* @brief		clustering
		*
		* @auther		ChienYu Chen (s941314g@yahoo.com.tw)
		* @date			Jan. 24, 2014
		*
		* @param		src:			Input data. The data type is vector.
		* @param		dst:			Output data. The data type is vector.
		* @param		K:				How many universe do the user want to cluster, for instance, if you want to segment the input data to two different parts, then you must set the argument to 2.
		* @param		iter:			Set the iteration number. If set this argument bigger, then the error of result will be much smaller.
		* @param		type:			The initial position can define by the user or computer.
		* @param		KM_TYPE:		If user set the type to 1, then the initial position will define by the user. If user set the type to 2, then the initial position will define random by the computer.
		*/
		enum KM_TYPE{KM_USERDEFINEPOS, KM_RANDPOS};
		bool KMeans(std::vector<std::vector<double>> &src, std::vector<std::vector<double>> &dst, int K, int iter, pixkit::clustering::KM_TYPE type = KM_RANDPOS);
	}

	namespace classification{

		struct SSample{
			std::string			classnumber; // class
			std::vector<double>	features;
		};

		bool KNN(std::vector<SSample> &sample,const std::vector<SSample> &dataset,int k);
		bool FKNN(std::vector<SSample> &sample,const std::vector<SSample> &dataset,int k);
		bool FRNN(std::vector<SSample> &sample,const std::vector<SSample> &dataset);

	}

	namespace mldata{

		void	readTrain(std::vector<pixkit::classification::SSample>& data, const std::string file);
		void	readTest(std::vector<pixkit::classification::SSample>& data, const std::string file);
		void	write(std::vector<pixkit::classification::SSample>& data, const std::string file);

	}
}
#endif


text:
from __future__ import print_function
import os.path as op
import yaml

from bakery_cli.report import utils as report_utils

TAB = 'Pre-Build Checks'
TEMPLATE_DIR = op.join(op.dirname(__file__), 'templates')

t = lambda templatefile: op.join(TEMPLATE_DIR, templatefile)

def sort(data):
    a = []
    for d in data:
        if 'required' in d['tags']:
            a.append(d)

    for d in data:
        if 'note' in d['tags'] and 'required' not in d['tags']:
            a.append(d)

    for d in data:
        if 'note' not in d['tags'] and 'required' not in d['tags']:
            a.append(d)

    return a

def generate(config):
    upstreamdatafile = op.join(config['path'], 'upstream.yaml')
    if not op.exists(upstreamdatafile):
        return

    upstream = yaml.load(open(upstreamdatafile))

    new_data = []
    for k in upstream:
        d = {'name': k}
        d.update(upstream[k])
        new_data.append(d)

    report_app = report_utils.BuildInfo(config)
    report_app.checks_page.dump_file(new_data, 'tests.json')


text:
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');

module.exports = {
  entry: __dirname + '/app',

  output: {
    path: __dirname + '/build',
    publicPath: '/',
    filename: 'bundle.js'
  },

  module: {
    loaders: [
      {
        test: /\.css$/,
        loaders: ['style', 'css'],
        include: __dirname + '/app'
      },
      {
        test: /\.jsx?$/,
        loaders: ['babel'],
        include: __dirname + '/app'
      }
    ]
  },

  resolve: {
    extensions: ['', '.js', '.jsx']
  },

  devtool: 'source-map',
  devServer: {
    historyApiFallback: true,
    hot: true,
    inline: true,
    progress: true,

    // display only errors to reduce the amount of output
    stats: 'errors-only'
  },

  plugins: [
    new HtmlWebpackPlugin({
      title: 'React Redux Tutorial'
    }),
    new webpack.HotModuleReplacementPlugin()
  ]
};


text:
import { App, getTestApp } from '~api/test-utils/create-server';

describe('health route', () => {
  let app: App;
  beforeAll(async () => {
    app = await getTestApp();
  });

  it.each`
    endpoint
    ${'liveness'}
    ${'readiness'}
  `('responds to the $endpoint endpoint', async ({ endpoint }) => {
    expect.assertions(2);
    const res = await app.agent.get(`/${endpoint}`);

    expect(res.status).toBe(200);
    expect(res.body).toStrictEqual({
      ok: true,
    });
  });
});


text:
import logging
import threading

import cupy
from ray.util.collective.collective_group import nccl_util
from ray.util.collective.const import ENV

NCCL_STREAM_POOL_SIZE = 32
MAX_GPU_PER_ACTOR = 16

logger = logging.getLogger(__name__)

class StreamPool:
    """The class that represents a stream pool associated with a GPU.

    When multistream is enabled, we will allocate a pool of streams for each
    GPU, and get available stream from this pool when a collective kernel is
    initialized. This enables overlapping computation/communication kernels
    using multiple CUDA streams, given that the streams a appropriately
    synchronized. The class is thread-safe.

    Args:
        device_idx (int): the absolute index of the device for this pool.
    """

    def __init__(self, device_idx):
        self.device_idx = device_idx

        self._initialized = False
        self._initialized_lock = threading.Lock()

        self._pool = [None] * NCCL_STREAM_POOL_SIZE
        self._counter = 0
        self._pool_lock = threading.Lock()

    def get_stream(self):
        """Get an available stream from the pool.

        The function locks the stream pool and releases the lock before
        returning.

        Returns:
            stream (cupy.cuda.Stream): the returned stream from pool.
        """

        # check the flag
        self._initialized_lock.acquire()
        if not self._initialized:
            self._init_once()
        self._initialized_lock.release()

        # Get the stream from the pool.
        self._pool_lock.acquire()
        stream = self._pool[self._counter]
        self._counter = (self._counter + 1) % NCCL_STREAM_POOL_SIZE
        self._pool_lock.release()
        return stream

    def _init_once(self):
        """Initialize the stream pool only for once."""
        with nccl_util.Device(self.device_idx):
            for i in range(NCCL_STREAM_POOL_SIZE):
                # this is the only place where self._pool will be written.
                if ENV.NCCL_USE_MULTISTREAM.val:
                    logger.debug("NCCL multistream enabled.")
                    self._pool[i] = cupy.cuda.Stream(
                        null=False, non_blocking=False)
                else:
                    logger.debug("NCCL multistream disabled.")
                    self._pool[i] = cupy.cuda.Stream.null
        self._init_flag = True

# This is a map from GPU index to its stream pool.
# It is supposed to be READ-ONLY out of this file
_device_stream_pool_map = dict()

def _init_stream_pool():
    global _device_stream_pool_map
    for i in range(MAX_GPU_PER_ACTOR):
        _device_stream_pool_map[i] = StreamPool(i)

def get_stream_pool(device_idx):
    """Get the CUDA stream pool of a GPU device."""
    # In case there will be multiple threads writing to the pool.
    lock = threading.Lock()
    lock.acquire()
    if not _device_stream_pool_map:
        _init_stream_pool()
    lock.release()
    return _device_stream_pool_map[device_idx]


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):

        # Adding field 'CollectionRecord.updated_at'
        db.add_column('collection_record_collectionrecord', 'updated_at', self.gf('django.db.models.fields.DateTimeField')(auto_now=True, default=datetime.datetime(2011, 12, 19, 17, 27, 55, 486755), blank=True), keep_default=False)

        # Adding field 'CollectionRecord.created_at'
        db.add_column('collection_record_collectionrecord', 'created_at', self.gf('django.db.models.fields.DateTimeField')(auto_now_add=True, default=datetime.datetime(2011, 12, 19, 17, 28, 3, 966766), blank=True), keep_default=False)

    def backwards(self, orm):

        # Deleting field 'CollectionRecord.updated_at'
        db.delete_column('collection_record_collectionrecord', 'updated_at')

        # Deleting field 'CollectionRecord.created_at'
        db.delete_column('collection_record_collectionrecord', 'created_at')

    models = {
        'dublincore.qualifieddublincoreelement': {
            'Meta': {'ordering': "['term']", 'object_name': 'QualifiedDublinCoreElement'},
            'content': ('django.db.models.fields.TextField', [], {}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'object_id': ('django.db.models.fields.PositiveIntegerField', [], {}),
            'qualifier': ('django.db.models.fields.CharField', [], {'max_length': '40', 'null': 'True', 'blank': 'True'}),
            'term': ('django.db.models.fields.CharField', [], {'max_length': '4'}),
            'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'})
        },
        'collection_record.collectionrecord': {
            'Meta': {'object_name': 'CollectionRecord'},
            'abstract': ('django.db.models.fields.TextField', [], {}),
            'accessrestrict': ('django.db.models.fields.TextField', [], {}),
            'acqinfo': ('django.db.models.fields.TextField', [], {}),
            'ark': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '255'}),
            'bioghist': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            'date_dacs': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'date_iso': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'extent': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'language': ('django.db.models.fields.CharField', [], {'max_length': '3'}),
            'local_identifier': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
            'online_items_url': ('django.db.models.fields.URLField', [], {'max_length': '200', 'null': 'True', 'blank': 'True'}),
            'scopecontent': ('django.db.models.fields.TextField', [], {}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '512'}),
            'title_filing': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}),
            'updated_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'userestrict': ('django.db.models.fields.TextField', [], {})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        }
    }

    complete_apps = ['collection_record']


text:
<?php

/**
 * This code was generated by
 * \ / _    _  _|   _  _
 * | (_)\/(_)(_|\/| |(/_  v1.0.0
 * /       /
 */

namespace Twilio\Rest\Chat\V1\Service\User;

use Twilio\Exceptions\TwilioException;
use Twilio\InstanceResource;
use Twilio\Values;
use Twilio\Version;

/**
 * @property string $accountSid
 * @property string $serviceSid
 * @property string $channelSid
 * @property string $memberSid
 * @property string $status
 * @property int $lastConsumedMessageIndex
 * @property int $unreadMessagesCount
 * @property array $links
 */
class UserChannelInstance extends InstanceResource {
    /**
     * Initialize the UserChannelInstance
     *
     * @param \Twilio\Version $version Version that contains the resource
     * @param mixed[] $payload The response payload
     * @param string $serviceSid The SID of the Service that the resource is
     *                           associated with
     * @param string $userSid The unique string that identifies the resource
     * @return \Twilio\Rest\Chat\V1\Service\User\UserChannelInstance
     */
    public function __construct(Version $version, array $payload, $serviceSid, $userSid) {
        parent::__construct($version);

        // Marshaled Properties
        $this->properties = array(
            'accountSid' => Values::array_get($payload, 'account_sid'),
            'serviceSid' => Values::array_get($payload, 'service_sid'),
            'channelSid' => Values::array_get($payload, 'channel_sid'),
            'memberSid' => Values::array_get($payload, 'member_sid'),
            'status' => Values::array_get($payload, 'status'),
            'lastConsumedMessageIndex' => Values::array_get($payload, 'last_consumed_message_index'),
            'unreadMessagesCount' => Values::array_get($payload, 'unread_messages_count'),
            'links' => Values::array_get($payload, 'links'),
        );

        $this->solution = array('serviceSid' => $serviceSid, 'userSid' => $userSid, );
    }

    /**
     * Magic getter to access properties
     *
     * @param string $name Property to access
     * @return mixed The requested property
     * @throws TwilioException For unknown properties
     */
    public function __get($name) {
        if (\array_key_exists($name, $this->properties)) {
            return $this->properties[$name];
        }

        if (\property_exists($this, '_' . $name)) {
            $method = 'get' . \ucfirst($name);
            return $this->$method();
        }

        throw new TwilioException('Unknown property: ' . $name);
    }

    /**
     * Provide a friendly representation
     *
     * @return string Machine friendly representation
     */
    public function __toString() {
        return '[Twilio.Chat.V1.UserChannelInstance]';
    }
}


text:
module TaskHelper
  class Form < Base
    data_member :app_id, :name, :desc, :post_action, :position, :sort_by, :asc,
                :per_page, :allow_delete, :new_widget, :records_widget,
                :target_page, :allow_database, :send_emails, :settings

    def self.all
      Database.all.lazy.flat_map { |db| db.forms }
    end

    def self.find_by(search)
      if response = get(route: 'apps/search/entities/search.json', params: search)
        new response['form'] if response['form']
      end
    end

    def self.find(database:, form:)
      if response = get(route: "apps/#{database}/entities/#{form}.json")
        new response['form'] if response['form']
      end
    end

    def initialize(args = {}, database: nil, **params)
      @database = database
      super(args.merge(params))
    end

    def database
      @database ||= Database.find(app_id)
    end

    def fields
      @fields ||= Field.get(
        route: "apps/#{app_id}/entities/#{id}/properties.json")['fields']
          .map { |field| Field.new(field, form: self) }
    end

    def records
      if fields.any?
        @records ||= (1..page_count).lazy.flat_map do |page|
          record_page(page).lazy.map { |record| Record.new(record, form: self) }
        end
      end
    end

    private

    def page_count
      database.dtypes_count / per_page + 1
    end

    def record_page(page = 1)
      Record.get(route: "apps/#{app_id}/dtypes/entity/#{id}.json",
                 params: { page: page })['records']
    end
  end
end


text:
package com.hello2morrow.sonargraph.integration.access.model.internal;

import com.hello2morrow.sonargraph.integration.access.model.ISystemFile;
import com.hello2morrow.sonargraph.integration.access.model.SystemFileType;

public class SystemFileImpl extends ElementImpl implements ISystemFile
{
    private static final long serialVersionUID = -7804519436007162975L;
    private final SystemFileType type;
    private final long lastModified;
    private final String hash;

    public SystemFileImpl(final String path, final SystemFileType type, final long lastModified, final String hash)
    {
        super(path, extractPresentationName(path));
        assert type != null : "Parameter 'type' of method 'SystemFileImpl' must not be null";
        assert hash != null : "Parameter 'hash' of method 'SystemFileImpl' must not be null";

        this.type = type;
        this.lastModified = lastModified;
        this.hash = hash;
    }

    public SystemFileImpl(final String path, final SystemFileType type, final long lastModified)
    {
        super(path, extractPresentationName(path));
        assert type != null : "Parameter 'type' of method 'SystemFileImpl' must not be null";
        this.hash = null;
        this.type = type;
        this.lastModified = lastModified;
    }

    @Override
    public String getPath()
    {
        return getName();
    }

    @Override
    public SystemFileType getType()
    {
        return type;
    }

    @Override
    public long getLastModified()
    {
        return lastModified;
    }

    @Override
    public String getHash()
    {
        return this.hash;
    }

    private static String extractPresentationName(final String path)
    {
        assert path != null : "Parameter 'path' of method 'extractPresentationName' must not be null";

        final int slashPos = path.lastIndexOf('/');
        if (slashPos > 0)
        {
            return path.substring(slashPos + 1, path.length());
        }

        return path;
    }
}


text:
import mongoose from 'mongoose'
import mongoosePaginate from 'mongoose-paginate'
import marked from 'marked'
import moment from 'moment'
import { save, update, remove, findByPage, findById } from './utils'

moment.locale('zh-cn')

marked.Lexer.rules.gfm.heading = marked.Lexer.rules.normal.heading
marked.Lexer.rules.tables.heading = marked.Lexer.rules.normal.heading

const productSchema = new mongoose.Schema({
    name: { type: String, required: true },
    category: { type: Object, required: true },
    price: { type: Number, required: true },
    details: String,
    img: String,
    link: String,
    tags: { type: Array, default: [] },
    collectedUsers: { type: Array, default: [] },
    createdAt: { type: Date, default: Date.now },
}, {
    toJSON: {
        virtuals: true
    }
})

productSchema.plugin(mongoosePaginate)

productSchema.virtual('cateName').get(function() {
    return this.category.name
})

productSchema.virtual('markedDetails').get(function() {
    if (this.details) {
        return marked(this.details)
    } else {
        return ''
    }
})

productSchema.virtual('prettyCreatedAt').get(function() {
    return moment(this.createdAt).format('ll')
})

productSchema.virtual('collectedCount').get(function() {
    return this.collectedUsers.length
})

productSchema.statics.save = async function(product) {
    return await save(product)
}

productSchema.statics.update = async function(product) {
    return await update(this, product)
}

productSchema.statics.remove = async function(id) {
    return await remove(this, id)
}

productSchema.statics.findByPage = async function(page = 1) {
    return await findByPage(this, {}, page, 'products')
}

productSchema.statics.findByCategory = async function(category, page = 1) {
    return await findByPage(this, { 'category.url': category }, page, 'products')
}

productSchema.statics.findByTag = async function(tag, page = 1) {
    return await findByPage(this, { tags: { $in: [tag] }}, page, 'products')
}

productSchema.statics.findByCollectedUser = async function(user, page = 1) {
    let userId = user && user._id
    return await findByPage(this, { collectedUsers: { $in: [userId] }}, page, 'products')
}

productSchema.statics.findBySearch = async function(search, page = 1) {
    return await findByPage(this, { name: new RegExp(search, 'gim') }, page, 'products')
}

productSchema.statics.findById = async function(id) {
    return await findById(this, id, 'product')
}

const Product = mongoose.model('Product', productSchema)

export { Product }


text:
package com.google.security.zynamics.binnavi.ZyGraph.Implementations;

import java.awt.Window;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JFrame;

import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.security.zynamics.binnavi.CUtilityFunctions;
import com.google.security.zynamics.binnavi.Exceptions.MaybeNullException;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.CGraphModel;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.CommentDialogs.InitialTab;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.CommentDialogs.CodeNodeComments.DialogEditCodeNodeComment;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.CommentDialogs.FunctionComments.CDialogEditFunctionNodeComment;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.CommentDialogs.Interfaces.IComment;
import com.google.security.zynamics.binnavi.Gui.GraphWindows.CommentDialogs.TextNodeComments.DialogTextNodeComment;
import com.google.security.zynamics.binnavi.Gui.errordialog.NaviErrorDialog;
import com.google.security.zynamics.binnavi.disassembly.CNaviViewEdge;
import com.google.security.zynamics.binnavi.disassembly.CTextNode;
import com.google.security.zynamics.binnavi.disassembly.INaviCodeNode;
import com.google.security.zynamics.binnavi.disassembly.INaviEdge;
import com.google.security.zynamics.binnavi.disassembly.INaviFunction;
import com.google.security.zynamics.binnavi.disassembly.INaviFunctionNode;
import com.google.security.zynamics.binnavi.disassembly.INaviInstruction;
import com.google.security.zynamics.binnavi.disassembly.INaviViewNode;
import com.google.security.zynamics.binnavi.disassembly.views.INaviView;
import com.google.security.zynamics.reil.ReilGraph;
import com.google.security.zynamics.reil.translators.InternalTranslationException;
import com.google.security.zynamics.reil.translators.ReilTranslator;
import com.google.security.zynamics.reil.translators.StandardEnvironment;
import com.google.security.zynamics.zylib.gui.GuiHelper;
import com.google.security.zynamics.zylib.gui.zygraph.edges.EdgeType;

/**
 * Contains helper functions related to graph nodes.
 */
public final class CNodeFunctions {
  /**
   * You are not supposed to instantiate this class.
   */
  private CNodeFunctions() {
  }

  /**
   * Creates a comment editing dialog for a given view node.
   *
   * @param node Node for which the dialog is created.
   *
   * @return The comment editing dialog for the given node.
   */
  private static JDialog getCommentDialog(final CGraphModel model, final INaviViewNode node,
      final InitialTab initialTab) {
    if (node instanceof INaviCodeNode) {
      return new DialogEditCodeNodeComment(model, (INaviCodeNode) node, initialTab);
    } else if (node instanceof INaviFunctionNode) {
      return new CDialogEditFunctionNodeComment(model, (INaviFunctionNode) node, initialTab);
    } else {
      throw new IllegalStateException("IE02127: Unknown node type");
    }
  }

  /**
   * Transfers the comments from the old node to the two new nodes after node splitting.
   *
   * @param node The old node.
   * @param newNode1 The upper new node.
   * @param newNode2 The lower new node.
   */
  private static void transferLocalCodeNodeComments(final INaviCodeNode node,
      final INaviCodeNode newNode1, final INaviCodeNode newNode2) {
    newNode1.getComments().initializeLocalCodeNodeComment(
        node.getComments().getLocalCodeNodeComment());

    for (final INaviInstruction naviInstruction : node.getInstructions()) {
      if (newNode1.hasInstruction(naviInstruction)) {
        newNode1.getComments().initializeLocalInstructionComment(naviInstruction,
            node.getComments().getLocalInstructionComment(naviInstruction));
      } else {
        newNode2.getComments().initializeLocalInstructionComment(naviInstruction,
            node.getComments().getLocalInstructionComment(naviInstruction));
      }
    }
  }

  /**
   * Copy REIL code for node
   *
   * @param parent Parent used for dialogs
   * @param node The node for which to generate REIL code
   * @return The corresponding REIL graph
   */
  public static ReilGraph copyReilCode(final Window parent, final INaviCodeNode node) {
    final ReilTranslator<INaviInstruction> translator = new ReilTranslator<INaviInstruction>();

    try {
      return translator.translate(new StandardEnvironment(), node);
    } catch (final InternalTranslationException e) {
      CUtilityFunctions.logException(e);

      final String message = "E000XXX: " + "Could not show REIL code for node";
      final String description =
          CUtilityFunctions.createDescription(
              String.format("BinNavi could not show the REIL code for basic block at '%X'.",
                  node.getAddress()),
              new String[] {"The instructions could not be converted to REIL code."},
              new String[] {"You can not fix this problem yourself. Please contact "
                  + "the BinNavi support."});

      NaviErrorDialog.show(parent, message, description, e);
    }
    return null;
  }

  /**
   * Attaches a comment node to a given view node.
   *
   * @param parent Parent used for dialogs.
   * @param view The view where the new comment node is created.
   * @param node The node the new comment node is attached to.
   */
  public static void createCommentNode(final JFrame parent, final INaviView view,
      final INaviViewNode node) {

    Preconditions.checkNotNull(parent, "IE02128: Parent argument can not be null");
    Preconditions.checkNotNull(view, "IE02129: View argument can not be null");
    Preconditions.checkNotNull(node, "IE01726: Node argument can not be null");

    // TODO (timkornau): this is just transposed from the old code
    // needs to be checked to if we still want this to be like this.

    final CTextNode source = view.getContent().createTextNode(null);
    final CNaviViewEdge edge = view.getContent().createEdge(source, node, EdgeType.TEXTNODE_EDGE);

    final DialogTextNodeComment dlg = new DialogTextNodeComment(parent, source);

    GuiHelper.centerChildToParent(parent, dlg, true);

    dlg.setVisible(true);

    final List<IComment> newComment = dlg.getComment();

    if (newComment == null) {
      view.getContent().deleteEdge(edge);
      view.getContent().deleteNode(source);
    }
  }

  /**
   * Shows a dialog to edit the comments of a node.
   *
   * @param node The node whose comments are edited.
   * @param initialTab The initially visible tab.
   */
  public static void editNodeComments(final CGraphModel model, final INaviViewNode node,
      final InitialTab initialTab) {
    Preconditions.checkNotNull(node, "IE02131: Node argument can not be null");

    final JDialog dialog = getCommentDialog(model, node, initialTab);

    GuiHelper.centerChildToParent(model.getParent(), dialog, true);

    dialog.setVisible(true);
  }

  /**
   * Splits a node.
   *
   * @param view View the node belongs to.
   * @param originalNode Node to split.
   * @param instruction Instruction after which the node is split.
   */
  public static void splitAfter(final INaviView view, final INaviCodeNode originalNode,
      final INaviInstruction instruction) {
    final Iterable<INaviInstruction> oldInstructions = originalNode.getInstructions();

    if (instruction == Iterables.getLast(oldInstructions)) {
      // Splitting after the last instruction of a node does not make
      // sense at all.

      return;
    }

    // Step I: Find out what instructions belong to the new upper block and what
    // instructions belong to the new lower block.

    final List<INaviInstruction> upperInstructions = new ArrayList<INaviInstruction>();
    final List<INaviInstruction> lowerInstructions = new ArrayList<INaviInstruction>();

    List<INaviInstruction> currentInstructions = upperInstructions;

    for (final INaviInstruction oldInstruction : oldInstructions) {
      currentInstructions.add(oldInstruction);

      if (oldInstruction == instruction) {
        currentInstructions = lowerInstructions;
      }
    }

    // Step II: Create the two new code nodes.

    INaviFunction parentFunction = null;

    try {
      parentFunction = originalNode.getParentFunction();
    } catch (final MaybeNullException e) {
      // No parent function
    }

    final INaviCodeNode newNode1 =
        view.getContent().createCodeNode(parentFunction, upperInstructions);
    final INaviCodeNode newNode2 =
        view.getContent().createCodeNode(parentFunction, lowerInstructions);

    newNode1.setColor(originalNode.getColor());
    newNode1.setBorderColor(originalNode.getBorderColor());
    newNode2.setColor(originalNode.getColor());

    // Step III: Transfer node comments and instruction comments from the old node
    // to the new nodes.

    transferLocalCodeNodeComments(originalNode, newNode1, newNode2);

    // Step IV: Connect the two new nodes.

    view.getContent().createEdge(newNode1, newNode2, EdgeType.JUMP_UNCONDITIONAL);

    // Step V: Recreate the incoming and outgoing edges of the old node.

    for (final INaviEdge incomingEdge : originalNode.getIncomingEdges()) {
      view.getContent().createEdge(incomingEdge.getSource(), newNode1, incomingEdge.getType());
    }

    for (final INaviEdge outgoingEdge : originalNode.getOutgoingEdges()) {
      view.getContent().createEdge(newNode2, outgoingEdge.getTarget(), outgoingEdge.getType());
    }

    // Step VI: Get rid of the old node.

    view.getContent().deleteNode(originalNode);
  }
}


text:
/**
 * @author Oleg V. Khaschansky
 * @version $Revision$
 */
package java.awt.color;

public class ProfileDataException extends RuntimeException {
    private static final long serialVersionUID = 7286140888240322498L;

    public ProfileDataException(String s) {
        super(s);
    }

}


text:
module Devise

  module Models

    # Handles blocking a user access after a certain number of attempts.
    # Requires proper configuration of the Devise::Models::Lockable module.
    #
    module AuthyLockable

      extend ActiveSupport::Concern

      # Public: Determine if this is a lockable resource, via Devise::Models::Lockable.
      # Returns true
      # Raises an error if the Devise::Models::Lockable module is not configured.
      def lockable?
        raise 'Devise lockable extension required' unless respond_to? :lock_access!
        Devise.lock_strategy == :failed_attempts
      end

      # Public: Handle a failed 2FA attempt. If the resource is lockable via
      # Devise::Models::Lockable module then enforce that setting.
      #
      # Returns true if the user is locked out.
      def invalid_authy_attempt!
        return false unless lockable?

        self.failed_attempts ||= 0
        self.failed_attempts += 1

        if attempts_exceeded?
          lock_access! unless access_locked?
          true
        else
          save validate: false
          false
        end
      end

    end

  end

end


text:
package org.apache.lucene.queryParser.standard;

import java.util.Map;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.Query;

/**
 * This class behaves as the as the lucene 2.4 MultiFieldQueryParser class, but uses the new
 * query parser interface instead of the old one.

 *

 * This class should be used when the new query parser features are needed and
 * also keep at the same time the old query parser interface.

 *
 * @deprecated this class will be removed soon, it's a temporary class to be
 *             used along the transition from the old query parser to the new
 *             one
 */
@Deprecated
public class MultiFieldQueryParserWrapper extends QueryParserWrapper {

  /**
   * Creates a MultiFieldQueryParser. Allows passing of a map with term to
   * Boost, and the boost to apply to each term.
   *
   *

   * It will, when parse(String query) is called, construct a query like this
   * (assuming the query consists of two terms and you specify the two fields
   * title and body):
   *

   *
   *
     * (title:term1 body:term1) (title:term2 body:term2)
     *
   *
   *

   * When setDefaultOperator(AND_OPERATOR) is set, the result will be:
   *

   *
   *
     * +(title:term1 body:term1) +(title:term2 body:term2)
     *
   *
   *

   * When you pass a boost (title=>5 body=>10) you can get
   *

   *
   *
     * +(title:term1^5.0 body:term1^10.0) +(title:term2^5.0 body:term2^10.0)
     *
   *
   *

   * In other words, all the query's terms must appear, but it doesn't matter in
   * what fields they appear.
   *

   */
  @SuppressWarnings("unchecked")
public MultiFieldQueryParserWrapper(String[] fields, Analyzer analyzer, Map boosts) {
    this(fields, analyzer);
    StandardQueryParser qpHelper = getQueryParserHelper();

    qpHelper.setMultiFields(fields);
    qpHelper.setFieldsBoost(boosts);

  }

  /**
   * Creates a MultiFieldQueryParser.
   *
   *

   * It will, when parse(String query) is called, construct a query like this
   * (assuming the query consists of two terms and you specify the two fields
   * title and body):
   *

   *
   *
     * (title:term1 body:term1) (title:term2 body:term2)
     *
   *
   *

   * When setDefaultOperator(AND_OPERATOR) is set, the result will be:
   *

   *
   *
     * +(title:term1 body:term1) +(title:term2 body:term2)
     *
   *
   *

   * In other words, all the query's terms must appear, but it doesn't matter in
   * what fields they appear.
   *

   */
  public MultiFieldQueryParserWrapper(String[] fields, Analyzer analyzer) {
    super(null, analyzer);

    StandardQueryParser qpHelper = getQueryParserHelper();
    qpHelper.setAnalyzer(analyzer);

    qpHelper.setMultiFields(fields);
  }

  /**
   * Parses a query which searches on the fields specified.
   *

   * If x fields are specified, this effectively constructs:
   *
   *

   * <code>
   * (field1:query1) (field2:query2) (field3:query3)...(fieldx:queryx)
   * </code>
   *

   *
   * @param queries
   *          Queries strings to parse
   * @param fields
   *          Fields to search on
   * @param analyzer
   *          Analyzer to use
   * @throws ParseException
   *           if query parsing fails
   * @throws IllegalArgumentException
   *           if the length of the queries array differs from the length of the
   *           fields array
   */
  public static Query parse(String[] queries, String[] fields, Analyzer analyzer)
      throws ParseException {
    if (queries.length != fields.length)
      throw new IllegalArgumentException("queries.length != fields.length");
    BooleanQuery bQuery = new BooleanQuery();
    for (int i = 0; i < fields.length; i++) {
      QueryParserWrapper qp = new QueryParserWrapper(fields[i], analyzer);
      Query q = qp.parse(queries[i]);
      if (q != null && // q never null, just being defensive
          (!(q instanceof BooleanQuery) || ((BooleanQuery) q).getClauses().length > 0)) {
        bQuery.add(q, BooleanClause.Occur.SHOULD);
      }
    }
    return bQuery;
  }

  /**
   * Parses a query, searching on the fields specified. Use this if you need to
   * specify certain fields as required, and others as prohibited.
   *

   *
   *

   * Usage:
   * <code>
   * String[] fields = {"filename", "contents", "description"};
   * BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
   *                BooleanClause.Occur.MUST,
   *                BooleanClause.Occur.MUST_NOT};
   * MultiFieldQueryParser.parse("query", fields, flags, analyzer);
   * </code>
   *

   *

   * The code above would construct a query:
   *
   *

   * <code>
   * (filename:query) +(contents:query) -(description:query)
   * </code>
   *

   *
   * @param query
   *          Query string to parse
   * @param fields
   *          Fields to search on
   * @param flags
   *          Flags describing the fields
   * @param analyzer
   *          Analyzer to use
   * @throws ParseException
   *           if query parsing fails
   * @throws IllegalArgumentException
   *           if the length of the fields array differs from the length of the
   *           flags array
   */
  public static Query parse(String query, String[] fields,
      BooleanClause.Occur[] flags, Analyzer analyzer) throws ParseException {
    if (fields.length != flags.length)
      throw new IllegalArgumentException("fields.length != flags.length");
    BooleanQuery bQuery = new BooleanQuery();
    for (int i = 0; i < fields.length; i++) {
      QueryParserWrapper qp = new QueryParserWrapper(fields[i], analyzer);
      Query q = qp.parse(query);
      if (q != null && // q never null, just being defensive
          (!(q instanceof BooleanQuery) || ((BooleanQuery) q).getClauses().length > 0)) {
        bQuery.add(q, flags[i]);
      }
    }
    return bQuery;
  }

  /**
   * Parses a query, searching on the fields specified. Use this if you need to
   * specify certain fields as required, and others as prohibited.
   *

   *
   *

   * Usage:
   * <code>
   * String[] query = {"query1", "query2", "query3"};
   * String[] fields = {"filename", "contents", "description"};
   * BooleanClause.Occur[] flags = {BooleanClause.Occur.SHOULD,
   *                BooleanClause.Occur.MUST,
   *                BooleanClause.Occur.MUST_NOT};
   * MultiFieldQueryParser.parse(query, fields, flags, analyzer);
   * </code>
   *

   *

   * The code above would construct a query:
   *
   *

   * <code>
   * (filename:query1) +(contents:query2) -(description:query3)
   * </code>
   *

   *
   * @param queries
   *          Queries string to parse
   * @param fields
   *          Fields to search on
   * @param flags
   *          Flags describing the fields
   * @param analyzer
   *          Analyzer to use
   * @throws ParseException
   *           if query parsing fails
   * @throws IllegalArgumentException
   *           if the length of the queries, fields, and flags array differ
   */
  public static Query parse(String[] queries, String[] fields,
      BooleanClause.Occur[] flags, Analyzer analyzer) throws ParseException {
    if (!(queries.length == fields.length && queries.length == flags.length))
      throw new IllegalArgumentException(
          "queries, fields, and flags array have have different length");
    BooleanQuery bQuery = new BooleanQuery();
    for (int i = 0; i < fields.length; i++) {
      QueryParserWrapper qp = new QueryParserWrapper(fields[i], analyzer);
      Query q = qp.parse(queries[i]);
      if (q != null && // q never null, just being defensive
          (!(q instanceof BooleanQuery) || ((BooleanQuery) q).getClauses().length > 0)) {
        bQuery.add(q, flags[i]);
      }
    }
    return bQuery;
  }

}


text:
from environment import GymEnvironment
import numpy as np
import sys
import random
import os
import json
from critic import SimpleCritic
from policy import Policy
from hallucinator import SimpleHallucinator
from trainer import SimpleTrainer
from policy_buffer import PolicyBuffer

def main():
    # Get the path to the configs
    model_path = sys.argv[1]

    # Parse the config file
    conf_path = os.path.join(model_path, 'config.json')
    json_data = open(conf_path).read()
    conf = json.loads(json_data)

    '''
    # Update the relative path
    conf["agent"]["actor_path"]         = os.path.join(model_path, conf["agent"]["actor_path"] )
    conf["agent"]["critic_path"]        = os.path.join(model_path, conf["agent"]["critic_path"] )
    conf["agent"]["hallucinator_path"]  = os.path.join(model_path, conf["agent"]["critic_path"] )
    '''

    # Run the training algorithm
    run = Runner(conf['env'], conf['agent'])
    run.train(conf['train'])
    #run.test(conf['test'])

class Runner:
    def __init__(self, env_config, agent_config):
        self.n = 10
        self.noise_dim = 2
        self.env = GymEnvironment(name = env_config["name"])
        self.critic = SimpleCritic(self.n, self.env.obs_size, self.env.action_size)
        self.hallucinator = SimpleHallucinator(self.n, self.env.obs_size, self.noise_dim)
        self.policy_buffer = PolicyBuffer()
        self.policy_c = Policy
        self.trainer = SimpleTrainer(self.env, self.critic, self.hallucinator, self.policy_buffer, self.policy_c, self.noise_dim)

    def train(self, train_config, fill_replay = True):
        train_steps = train_config['steps']
        self.trainer.train(train_steps, 2, 2)

if __name__ == "__main__":
    main()


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:metrics="http://www.ryantenney.com/schema/metrics"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.ryantenney.com/schema/metrics
    http://www.ryantenney.com/schema/metrics/metrics-3.0.xsd">

	<!-- Root Context: defines shared resources visible to all other web components -->

	<!-- Registry should be defined in only one context XML file -->
	<!-- Remove Comment if you want to use annotations -->
    <!-- <metrics:metric-registry id="metrics" />	 -->

	<!-- annotation-driven must be included in all context files -->
	<!-- Remove Comment if you want to use annotations -->
    <!-- <metrics:annotation-driven metric-registry="metrics" /> -->

</beans>


text:
package transformations.value;

import java.util.Random;

/**
 * @author Alfio Ferrara, Universita` degli Studi di Milano
 * @date 18/mag/2010
 */
public class Utils {

	public static char pickChar(){
		String chars = "ABCDEFGHILMNOPGRSTUVZKJXYW1234567890abcdefghilmnopqrstuvzjkwxy?!";
		Random g = new Random();
		int index = g.nextInt(chars.length());
		return chars.charAt(index);
	}

}


text:
$(document).ready(function(){

	$('.close-nav, .sidebar-close').click(function(){
		snapper.close();
		return false;
	});

	$('.submenu-deploy').click(function(){
		$(this).parent().find('.nav-item-submenu').toggle(100);
		$(this).find('em').toggleClass('dropdown-nav');
		return false;
	});

	var snapper = new Snap({
	  element: document.getElementById('content')
	});

	$('.deploy-sidebar').click(function(){
		//$(this).toggleClass('remove-sidebar');
		if( snapper.state().state=="left" ){
			snapper.close();
		} else {
			snapper.open('left');
		}
		return false;
	});

});


text:
namespace network
{
	class HttpResponse
	{
		public:
			HttpResponse(const std::string& body, const std::string& header, short statusCode);
			HttpResponse(const std::string& body, short statusCode);
			HttpResponse(std::string&& body, std::string&& header, short statusCode);
			HttpResponse(HttpResponse&& h);
			~HttpResponse() = default;

			const std::string& getBody() const;
			const std::string& getHeader() const;
			short getStatusCode() const;

		private:
			std::string body_;
			std::string header_;
			short statusCode_;
	};
}

#endif


text:
QuestionPage::QuestionPage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::QuestionPage)
{
    ui->setupUi(this);
}

QuestionPage::~QuestionPage()
{
    delete ui;
}

bool QuestionPage::loadCase(const Section& section, const Case& caseValue)
{
    QDir sectionDir = section.dir();
    QString questionHTML = readHTML(sectionDir.absoluteFilePath(caseValue.questionFileName));
    if (questionHTML.isEmpty())
        return false;
    setImageAndHTML(section.dir(), caseValue.questionImage,
                    questionHTML, ui->questionBrowser);

    Solution solution = getSolution(SolutionPathType::Local, section);
    if (solution.isValid()) {
        Answer answer = solution.answer(caseValue);
        if (answer.isValid()) {
            QDir solutionDir = solution.dir();
            QString answerHTML = readHTML(
                        solutionDir.absoluteFilePath(answer.fileName));
            if (!answerHTML.isEmpty()) {
                ui->answerEdit->setHtml(answerHTML);
                ui->answerEdit->document()->setModified(false);
                hasFinalAnswer = answer.isFinal();
            }
        }
    }

    ui->titleLabel->setText("Кейс \"" + caseValue.name + "\"");
    this->section = section;
    this->caseValue = caseValue;
    updateButtons();
    return true;
}

bool QuestionPage::saveAnswer(Solution& solution)
{
    Solution solutionCopy = solution;
    Answer& answer = solutionCopy.addAnswer(caseValue);
    if (hasFinalAnswer) {
        answer.markAsFinal();
    } else {
        answer.version++;
    }
    QDir solutionDir = solutionCopy.dir();
    QString answerFileName = solutionDir.absoluteFilePath(answer.fileName);
    if (!writeHTML(answerFileName, ui->answerEdit->document()))
        return false;
    solution = solutionCopy;
    ui->answerEdit->document()->setModified(false);
    return true;
}

void QuestionPage::connectWith(QListWidgetItem* item)
{
    this->item = item;
}

bool QuestionPage::isAnswered() const
{
    return hasFinalAnswer;
}

bool QuestionPage::isModified() const
{
    return ui->answerEdit->document()->isModified();
}

void QuestionPage::onPageOpened()
{
    if (!ui->answerEdit->isReadOnly())
        ui->answerEdit->setFocus();
}

void QuestionPage::on_answerEdit_textChanged()
{
    ui->enterButton->setEnabled(!ui->answerEdit->document()->isEmpty());
}

void QuestionPage::on_enterButton_clicked()
{
    hasFinalAnswer = true;
    updateButtons();
    emit enteredAnswer(item);
}

void QuestionPage::on_toMentorAnswerButton_clicked()
{
    emit requestedMentorAnswer(item);
}

void QuestionPage::updateButtons()
{
    if (hasFinalAnswer) {
        ui->answerEdit->setReadOnly(true);
        ui->enterButton->hide();
        ui->toMentorAnswerButton->show();
    } else {
        ui->enterButton->setEnabled(!ui->answerEdit->document()->isEmpty());
        ui->enterButton->show();
        ui->toMentorAnswerButton->hide();
    }
}


text:
PlayTime simplifies deploying apps to the Google Play Store.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'play_time'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install play_time

Then add the following line to your Rakefile. If you don't have a Rakefile, just create it.

    require 'line_change/tasks'

Then run the rake task to create a config file.

    $ rake play_time:install
    # Generating a new config file: config/play_time.yml

## Usage

### Getting access to your Play account

First you will need a Google Play developer account. After this is setup you will need to create a Google developer project <https://console.developers.google.com>. This is the project that PlayTime will be using to access your Google Play developer account. Once your project is created you will need to enable the Google Play Android Developer API. And then also create a new client id as a service account. This will create and download a P12 key for you and present you with the P12 passphrase, (these will be needed below).

**NOTE** You should probably change this passphrase, see <http://wiki.bsdserver.nl/doku.php?id=misc:ssl:sslchangepwonpkcs12cert>.

### Fill out all of the config fields.

```yml
package_name: # package name for your google play app
secret_path: # fill path to secret.p12
secret_passphrase: # passphrase for secert.p12
apk_path: # path to apk file
client_name: # This can be anything (as far as we can tell)
client_version: # This can be anything as well
issuer: # emaill address generated by your service account (<somestuff>@developer.gserviceaccount.com)
```

**NOTE:** The apk_path can be a regular expression and PlayTime::Apk.load will find the most recent file using **mtime**. `mtime` is not always the most recent file and can change depending how your disk is mounted. Make sure that this is what you want. If not you can hard code your path each time you are uploading.

Check out your new rake commands:

	$ rake -T
	rake play_time:promote:alpha[version_code]       # Promote apk version code to alpha
	rake play_time:promote:beta[version_code]        # Promote apk version code to beta
	rake play_time:promote:production[version_code]  # Promote apk version code to production
	rake play_time:promote:rollout[version_code]     # Promote apk version code to rollout
	rake play_time:upload:alpha                      # Uploads apk to alpha
	rake play_time:upload:beta                       # Uploads apk to beta
	rake play_time:upload:production                 # Uploads apk to production
	rake play_time:upload:rollout                    # Uploads apk to rollout

### Upload

The upload namespace will attempt to upload the latest apk specified at the apk path to the track that you specify.

### Promote

Promote will remove the version code from its existing track and then add that version code to the new track.

**Note** if the version code does not exist on a current track, it will raise an error.

## Using without rake

```ruby
require 'play_time'

PlayTime.install

# modify the config file

PlayTime::Track::TRACKS
> ['alpha', 'beta', 'rollout', 'production']

track = PlayTime::Track::ALPHA
PlayTime.upload(track)

PlayTime.promote(PlayTime::Track::BETA, <version_code>)
```

## TODO

* add promotion syntax like `rake play_time:promote['alpha', 'beta']`
* Add more precise steps for linking your Google Play account and Google Developer accounts.
* add nice logging to std out and/or progress bar

## Contributing

1. Fork it ( https://github.com/[my-github-username]/play_time/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
/*
 *
 * This source code and information are provided "AS-IS" without
 * warranty of any kind, either expressed or implied, including
 * but not limited to the implied warranties of merchantability
 * and/or fitness for a particular purpose.
 *
 * This source code was generated using an evaluation copy
 * of the Cassandra/Hadoop Accelerator and may not be used for
 * production purposes.
 *
 * For more information, contact Chris Gerken at
 * chris.gerken@gerkenip.com
 *
 */
package com.gerkenip.trending.Count;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.MultipleInputs;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.cassandra.hadoop.ColumnFamilyInputFormat;
import org.apache.cassandra.hadoop.ColumnFamilyOutputFormat;
import org.apache.cassandra.hadoop.ConfigHelper;
import org.apache.cassandra.thrift.SlicePredicate;
import org.apache.cassandra.thrift.SliceRange;
import org.apache.cassandra.utils.ByteBufferUtil;

import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.SortedMap;
import org.apache.cassandra.db.IColumn;

import com.gerkenip.writable.*;

public class CountJob {

	public static void main(String[] args) {

		String count_input_parse = "file:///home/";
		String count_output_termcounts = "hdfs://localhost:9000/tmp/SocialLinks/Links";

		String countBase = "file";

		Properties prop = new Properties();
		try {
			if (args.length > 0) {
				InputStream stream = new FileInputStream(args[0]);
				prop.loadFromXML(stream);
				count_input_parse = prop.getProperty("Count.input.Parse",count_input_parse);
				count_output_termcounts = prop.getProperty("Count.output.TermCounts",count_output_termcounts);

				countBase = prop.getProperty("count.base.dir",countBase);

				prop.list(System.out);
			}
		} catch (Exception e) {
			System.out.println("Properties file not found. Will use default properties instead.");
		}

		try {
			Configuration conf = new Configuration();

			conf.set("Count.input.Parse",count_input_parse);
			conf.set("Count.output.TermCounts",count_output_termcounts);

			conf.set("count.base.dir",countBase);

				// Begin custon config logic

				// End custon config logic

			Job job = new Job(conf, "com.gerkenip.trending.Count.CountJob : ");

			job.setJarByClass(CountJob.class);

			job.setMapOutputKeyClass(Text.class);
			job.setMapOutputValueClass(LongWritable.class);

				// Configure mapper for input Parse
			MultipleInputs.addInputPath(job, new Path(count_input_parse), SequenceFileInputFormat.class, ParseMapper.class);

	        job.setReducerClass(TermCountsReducer.class);
	        job.setOutputKeyClass(Text.class);
	        job.setOutputValueClass(Text.class);
	        job.setOutputFormatClass(TextOutputFormat.class);

	        Path outPath;
	        FileSystem dfs;

	        outPath = new Path(count_output_termcounts);
			SequenceFileOutputFormat.setOutputPath(job, outPath);
	        dfs = FileSystem.get(outPath.toUri(), conf);
	        if (dfs.exists(outPath)) {
	          dfs.delete(outPath, true);
	        }
            new TermCountsConcurrentOutputFormat().configure(job.getConfiguration());
            MultipleOutputs.addNamedOutput(job, "TermCounts", TermCountsConcurrentOutputFormat.class, Text.class, LongWritable.class);

	        outPath = new Path(countBase+"/Trending/Count");
			TextOutputFormat.setOutputPath(job, outPath);
	        dfs = FileSystem.get(outPath.toUri(), conf);
	        if (dfs.exists(outPath)) {
	          dfs.delete(outPath, true);
	        }

	        job.setNumReduceTasks(1);

			job.waitForCompletion(true);

		} catch (Exception e) {
			System.out.println(e.toString());
				// Handle Exception...
		} finally {

		}

	}
}


text: jQuery Replacement


text:
namespace ash {

MockSigninUI::MockSigninUI() {}

MockSigninUI::~MockSigninUI() {}

}  // namespace ash