text:
namespace blink {

PassRefPtr<Picture> Picture::create(PassRefPtr<SkPicture> skPicture)
{
    ASSERT(skPicture);
    return adoptRef(new Picture(skPicture));
}

Picture::Picture(PassRefPtr<SkPicture> skPicture)
    : m_picture(skPicture)
{
}

Picture::~Picture()
{
}

} // namespace blink

redpajama_set_name: RedPajamaGithub


text:
module Meyasubako
  class MeyasubakoController < ActionController::Base
    def create
      MeyasubakoMailer.email(params[:content]).deliver_now

      render nothing: true
    end
  end
end


text:
package com.senseidb.search.query.filters;

import java.io.IOException;
import java.util.Iterator;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.DocIdSet;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Filter;
import org.json.JSONObject;

import com.browseengine.bobo.api.BoboIndexReader;
import com.browseengine.bobo.api.BrowseSelection;
import com.browseengine.bobo.facets.impl.PathFacetHandler;
import com.browseengine.bobo.facets.FacetHandler;

import com.browseengine.bobo.query.MatchAllDocIdSetIterator;

public class PathFilterConstructor extends FilterConstructor
{
  public static final String FILTER_TYPE = "path";

  @Override
  protected Filter doConstructFilter(Object param) throws Exception
  {
    JSONObject json = (JSONObject)param;

    Iterator<String> iter = json.keys();
    if (!iter.hasNext())
      return null;

    final String field = iter.next();
    final String path;
    final int depth;
    final boolean strict;

    Object obj = json.get(field);
    if (obj instanceof JSONObject)
    {
      path   = ((JSONObject)obj).getString(VALUE_PARAM);
      depth  = ((JSONObject)obj).optInt(DEPTH_PARAM, 0);
      strict = ((JSONObject)obj).optBoolean(STRICT_PARAM, false);
    }
    else
    {
      path   = String.valueOf(obj);
      depth  = 0;
      strict = false;
    }

    return new Filter()
    {
      @Override
      public DocIdSet getDocIdSet(final IndexReader reader) throws IOException
      {
        if (reader instanceof BoboIndexReader)
        {
          BoboIndexReader boboReader = (BoboIndexReader)reader;
          FacetHandler facetHandler = boboReader.getFacetHandler(field);
          if (facetHandler != null && facetHandler instanceof PathFacetHandler)
          {
            BrowseSelection sel = new BrowseSelection(field);
            sel.setValues(new String[]{path});
            sel.setSelectionProperty(PathFacetHandler.SEL_PROP_NAME_DEPTH, String.valueOf(depth));
            sel.setSelectionProperty(PathFacetHandler.SEL_PROP_NAME_STRICT, String.valueOf(strict));
            Filter filter = ((PathFacetHandler)facetHandler).buildFilter(sel);
            if (filter == null)
              return new DocIdSet()
              {
                @Override
                public boolean isCacheable()
                {
                  return false;
                }

                @Override
                public DocIdSetIterator iterator() throws IOException
                {
                  return new MatchAllDocIdSetIterator(reader);
                }
              };
            return filter.getDocIdSet(reader);
          }
        }

        throw new UnsupportedOperationException("Path filter is not supported for your field: " + field);
      }
    };
  }
}


text:
angular.module('classeur.core.filePropertiesDialog', [])
  .factory('clFilePropertiesDialog',
    function (clDialog, clToast, clFilePropertiesSvc) {
      return function (properties) {
        properties = properties || {}

        return clDialog.show({
          templateUrl: 'core/filePropertiesDialog/filePropertiesDialog.html',
          controller: ['$scope', function (scope) {
            scope.addRow = function () {
              scope.properties.push({})
            }

            function makeScopeProperties (properties) {
              scope.properties = Object.keys(properties).sort().cl_map(function (key) {
                return {
                  key: key,
                  value: properties[key]
                }
              })
              scope.addRow()
            }
            makeScopeProperties(properties)

            function propertiesToPropertiesDesc () {
              scope.propertiesDesc = clFilePropertiesSvc.propertiesDesc.cl_reduce(function (result, propertyDesc, name) {
                var property = {}
                scope.properties.cl_some(function (entry) {
                  if (entry.key === name) {
                    property = entry
                    return true
                  }
                })
                result[name] = {
                  value: propertyDesc.deserialize(property.value)
                }.cl_extend(propertyDesc)
                return result
              }, {})
            }
            propertiesToPropertiesDesc()

            function propertiesDescToProperties () {
              scope.propertiesDesc.cl_each(function (propertyDesc, name) {
                scope.properties.push({
                  key: name,
                  value: propertyDesc.serialize(propertyDesc.value)
                })
              })
              makeScopeProperties(scope.properties.cl_reduce(function (properties, property) {
                if (property.key) {
                  if (property.value) {
                    properties[property.key] = property.value
                  } else {
                    delete properties[property.key]
                  }
                }
                return properties
              }, {}))
            }

            scope.$watch('tabIndex', function (tabIndex) {
              if (tabIndex === 0) {
                propertiesToPropertiesDesc()
              } else {
                propertiesDescToProperties()
              }
            })

            scope.deleteRow = function (propertyToDelete) {
              scope.properties = scope.properties.cl_filter(function (property) {
                return property !== propertyToDelete
              })
            }

            scope.ok = function () {
              if (scope.tabIndex === 0) {
                propertiesDescToProperties()
              }
              var properties = {}
              if (Object.keys(scope.properties).length > 100) {
                return clToast('Too many properties.')
              }
              if (
                scope.properties.cl_some(function (property) {
                  if (!property.key && !property.value) {
                    return
                  }
                  if (!property.key) {
                    clToast("Property can't be empty.")
                    return true
                  }
                  if (property.key.length > 100) {
                    clToast('Property key is too long.')
                    return true
                  }
                  if (!property.value) {
                    clToast("Property can't be empty.")
                    return true
                  }
                  if (property.value.length > 500) {
                    clToast('Property value is too long.')
                    return true
                  }
                  if (properties.hasOwnProperty(property.key)) {
                    clToast('Duplicate property: ' + property.key + '.')
                    return true
                  }
                  properties[property.key] = property.value
                })
              ) {
                return
              }
              clDialog.hide(properties)
            }
            scope.cancel = function () {
              clDialog.cancel()
            }
          }]
        })
      }
    })
  .factory('clFilePropertiesSvc',
    function ($templateCache, $rootScope) {
      var propertiesDesc = JSON.parse($templateCache.get('core/filePropertiesDialog/propertyDescriptors.json'))

      var clFilePropertiesSvc = {
        propertiesDesc: propertiesDesc,
        getCurrentFilePropertiesDesc: getCurrentFilePropertiesDesc,
        setCurrentFilePropertiesDesc: setCurrentFilePropertiesDesc
      }

      propertiesDesc.cl_each(function (propertyDesc, name) {
        propertyDesc.serialize = function (val) {
          return val
            ? val.toString()
            : undefined
        }
        propertyDesc.deserialize = function (val) {
          return val
        }
        switch (propertyDesc.type) {
          case 'checkbox':
            propertyDesc.serialize = function (val) {
              val = !!val
              return val === propertyDesc.default
                ? undefined
                : (!!val).toString()
            }
            propertyDesc.deserialize = function (val) {
              switch (val) {
                case 'true':
                  return true
                case 'false':
                  return false
                default:
                  return propertyDesc.default
              }
            }
            break
        }
      })

      function getCurrentFilePropertiesDesc () {
        if (!$rootScope.currentFile || !$rootScope.currentFile.content) {
          return {}
        }
        return propertiesDesc.cl_reduce(function (result, propertyDesc, name) {
          result[name] = {
            value: propertyDesc.deserialize($rootScope.currentFile.content.properties[name])
          }.cl_extend(propertyDesc)
          return result
        }, {})
      }

      function setCurrentFilePropertiesDesc (propertiesDesc) {
        if ($rootScope.currentFile && $rootScope.currentFile.content) {
          propertiesDesc.cl_each(function (propertyDesc, name) {
            var value = propertyDesc.serialize(propertyDesc.value)
            if (value) {
              $rootScope.currentFile.content.properties[name] = value
            } else {
              delete $rootScope.currentFile.content.properties[name]
            }
          })
        }
      }

      return clFilePropertiesSvc
    })


text:
sap.ui.define([ './library'], function(ui5strapCoreLib) {

	"use strict";

	/*
	 * -----
	 *
	 * Utils
	 *
	 * -----
	 */

	/**
	 * @Package
	 */
	var Utils = {};

	/**
	 * parse map
	 */
	Utils.parseMap = {
		'[strong]' : '',
		'[/strong]' : '',
		'[em]' : '',
		'[/em]' : '',
		'[small]' : '',
		'[/small]' : '',
		'[span]' : '',
		'[/span]' : ''
	};

	/**
	 * Parses BBCode inside text
	 *
	 * @Public
	 * @Static
	 */
	Utils.parseText = function(text) {
		return text
				.replace(
						/\[\/?strong\]|\[\/?em\]|\[\/?small\]|\[\/?span\]/gi,
						function(matched) {
							return Utils.parseMap[matched];
						});
	};

	/**
	 * Gets an object property by string regardless of depth.
	 */
	Utils.fetchFromObject = function(obj, prop) {

	    if(typeof obj === 'undefined') {
	        return obj;
	    }

	    var _index = prop.indexOf('.')
	    if(_index > -1) {
	        return this.fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
	    }

	    return obj[prop];
	};

	Utils.addToObject = function(obj, prop, value){
		var _index = prop.indexOf('.')
	    if(_index > -1) {
	    	var nextProp = prop.substring(0, _index),
	    		newObject = obj[nextProp];

	    	if(typeof newObject === 'undefined') {
	    		newObject = {};
	    		obj[nextProp] = newObject;
		    }

	        return this.addToObject(newObject, prop.substr(_index + 1), value);
	    }

	    obj[prop] = value;
	};

	/**
	 * Parses a path and replaces all {param} occurrencies by the content in the pathParam object.
	 */
	Utils.parsePath = function(path, pathParam){
        pathParam = pathParam || {};
        return path.replace(/\{([\w]+[\.\w]*)\}/g, function(m0, m1){
            return Utils.fetchFromObject(pathParam, m1);
        });
    };

	/**
	 * Gets a computed css property
	 */
	Utils.getComputedStyle = function(oElm, strCssRule){
		var strValue = "";

		if (document.defaultView
				&& document.defaultView.getComputedStyle) {
			strValue = document.defaultView.getComputedStyle(
					oElm, "").getPropertyValue(strCssRule);
		} else if (oElm.currentStyle) {
			strCssRule = strCssRule.replace(/\-(\w)/g,
					function(strMatch, p1) {
						return p1.toUpperCase();
					});
			strValue = oElm.currentStyle[strCssRule];
		}

		return strValue;
	};

	/**
	 * Builds dynamic setters from a list of html tag attributes.
	 * @Public
	 */
	Utils.dynamicAttributes = function(controlProto,
			attributeNames) {
		for (var i = 0; i < attributeNames.length; i++) {
			Utils.dynamicAttribute(controlProto,
					attributeNames[i]);
		}
	};

	/**
	 * Builds a dynamic setter from a html tag attribute.
	 * @Public
	 */
	Utils.dynamicAttribute = function(controlProto,
			attributeName) {
		controlProto['set'
				+ jQuery.sap.charToUpperCase(attributeName, 0)] = function(
				newValue, suppressInvalidate) {
			Utils.updateAttribute(this, attributeName,
					newValue, suppressInvalidate);
		};
	};

	/**
	 * Builds dynamic setters from a list of html tag attributes.
	 * @Public
	 */
	Utils.updateAttribute = function(oControl,
			attributeName, newValue, suppressInvalidate) {
		if (oControl.getDomRef()) {
			oControl.$().attr(attributeName, newValue);
			oControl.setProperty(attributeName, newValue, true);
		} else {
			oControl.setProperty(attributeName, newValue, suppressInvalidate);
		}
	};

	// @deprecated
	Utils.dynamicClass = function(controlProto,
			propertyName, valueMapping) {
		controlProto['set'
				+ jQuery.sap.charToUpperCase(propertyName, 0)] = function(
				newValue, suppressInvalidate) {
			Utils.updateClass(this, this.$(),
					propertyName, newValue, valueMapping,
					suppressInvalidate);
		};
	};

	// @deprecated
	Utils.updateClass = function(oControl, $target,
			propertyName, newValue, valueMapping,
			suppressInvalidate) {
		if (oControl.getDomRef()) {
			var oldValue = oControl['get'
					+ jQuery.sap.charToUpperCase(propertyName,
							0)]();
			if (oldValue in valueMapping) {
				$target.removeClass(valueMapping[oldValue]);
			}
			if (newValue in valueMapping) {
				$target.addClass(valueMapping[newValue]);
			}

			oControl.setProperty(propertyName, newValue, true);
		} else {
			oControl.setProperty(propertyName, newValue,
					suppressInvalidate);
		}
	};

	// @deprecated
	Utils.dynamicText = function(controlProto) {
		controlProto.setText = function(newText,
				suppressInvalidate) {
			// console.log(newText, suppressInvalidate);
			Utils.updateText(this, this.$(), newText,
					suppressInvalidate);
		};
	};

	// @deprecated
	Utils.updateText = function(oControl, $target,
			newText, suppressInvalidate) {
		if (oControl.getDomRef()
				&& oControl.getContent().length === 0) {
			//Check if text needs to be parsed
			if(oControl.getParse && oControl.getParse()){
				$target.html(Utils.parseText(newText));
			}
			else{
				$target.text(newText);
			}

			//jQuery.sap.log.info("Updated text directly for control " + oControl.getId());

			//Set property value without rerendering
			oControl.setProperty('text', newText, true);
		} else {
			//Default setter behaviour
			oControl.setProperty('text', newText,
					suppressInvalidate);
		}
	};

	/**
	 * @Static
	 * @Public
	 * @deprecated Use jQuery.sap.getObject instead.
	 */
	Utils.getObject = function(packageString, levelsUp) {
		if (!levelsUp) {
			levelsUp = 0;
		}

		var classParts = packageString.split('.');
		if (!(classParts[0] in window)) {
			return;
		}

		var constructor = window[classParts[0]];

		for (var i = 1; i < classParts.length - levelsUp; i++) {
			if (!(classParts[i] in constructor)) {
				return;
			}
			constructor = constructor[classParts[i]];
		}

		return constructor;
	};

	/**
	 * @Static
	 * @Public
	 */
	Utils.createObject = function(packageString) {
		var Constructor = this.getObject(packageString);
		return new Constructor();
	};

	/**
	 * @Static
	 * @Public
	 */
	Utils.queryToObject = function(query) {
		var vars = query.split('&'), obj = {};

		for (var i = 0; i < vars.length; i++) {
			var pair = vars[i].split('=');
			obj[pair[0]] = pair[1];
		}

		return obj;
	};

	/**
	 * @Static
	 * @Public
	 */
	Utils.parseIContent = function(iContent) {
		var iContentType = typeof iContent;

		if (iContentType === 'string') {
			if (jQuery.sap.startsWith(iContent, "?")) {
				return Utils.queryToObject(iContent
						.slice(1));
			}
		}

		return iContent;
	};

	/**
	 * @Static
	 * @Public
	 */
	Utils.qualifyURL = function(url) {
		var a = document.createElement('a');
		a.href = url;
		return a.href;
	};

	/**
	 * @Static
	 * @Public
	 */
	Utils.urlOrigin = function(url) {
		var a = document.createElement('a');
		a.href = url;

		var origin = a.protocol + "//" + a.host;
	};

	/**
	 * Returns the path of the directory of a given file url.
	 */
	Utils.getFileLocation = function(url){
		var urlParts = url.split('/');
		urlParts[urlParts.length - 1] = '';

		return urlParts.join('/');
	};

	/**
	 * Transfers a property propagation from one to an other
	 * control. Taken from ManagedObject.prototype.setParent
	 *
	 * @Public
	 * @Static
	 */
	Utils.addPropertyPropagation = function(
			fromControl, toControl) {
		toControl.oPropagatedProperties = fromControl
				._getPropertiesToPropagate();

		if (toControl.hasModel()) {
			jQuery.sap.log.info("{Utils} Added propagation from '" + fromControl.getId() + "' to '" + toControl.getId() + "'.");

			toControl.updateBindingContext(false, true,
					undefined, true);
			toControl.updateBindings(true, null); // TODO
			// could be
			// restricted
			// to models
			// that
			// changed
			toControl.propagateProperties(true);
		}
	};

	/**
	 * Finds the closest parent control of type TargetType.
	 *
	 * @Public
	 * @Static
	 */
	Utils.findClosestParentControl = function(control,
			TargetType) {
		var parentControl = control, maxDepth = 20, i = 0;
		while (parentControl && !(parentControl instanceof TargetType)) {
			parentControl = parentControl.getParent()
			i++;
			if (i >= maxDepth) {
				jQuery.sap.log
						.warning("Cannot find parent control: max depth reached.");
				parentControl = null;
			}
		}

		return parentControl;
	};

	/**
	 * Generates a random UUID
	 */
	Utils.randomUUID = function(){
	    return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, function(c){
			  return (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16);
			}
	    );

	    //return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
	    //    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
	    //    return v.toString(16);
	    //  });
	};

	/**
	 *
	 * @deprecated
	 */
	Utils.ScriptBlock = function() {
		this._pending = {};
		this._order = [];
		this._pendingRequests = 0;
		this._buffer = '';

		var _this = this;

		/**
		 * @Private
		 */
		var _successCallback = function(response, callback) {
			_this._pending[this.url]["script"] = response;

			_this._pendingRequests--;

			if (0 === _this._pendingRequests) {
				for (var i = 0; i < _this._order.length; i++) {
					if (!_this._order[i].script) {
						throw new Error(
								'Could not append script to buffer: '
										+ _this._order[i].url);
					}
					_this._buffer = _this._buffer.concat(
							"\n;\n", _this._order[i].script);
				}

				_this._pending = {};
				_this._order = [];

				callback && callback();
			}
		};

		/**
		 * @Public
		 */
		this.load = function(scripts, callback) {
			if (0 < this._pendingRequests
					|| this._order.length > 0) {
				throw new Error(
						'Could not load scripts: requests still pending.');
			}

			this._pendingRequests = scripts.length;

			for (var i = 0; i < this._pendingRequests; i++) {
				var scriptUrl = scripts[i], scriptData = {
					"index" : i,
					"url" : scriptUrl,
					"script" : null
				};

				this._pending[scriptUrl] = scriptData;
				this._order.push(scriptData);

				jQuery.ajax({
					url : scriptUrl,
					dataType : "text",
					success : function(response) {
						_successCallback.call(this, response,
								callback);
					},
					error : function() {
						throw new Error(
								'Could not load script: '
										+ scriptUrl);
					}
				});
			}
		};

		/**
		 * @Public
		 */
		this.execute = function(useEval) {
			if ('' === this._buffer) {
				return false;
			}
			var returnValue = null;
			if (true === useEval) {
				returnValue = eval.call(window, this._buffer);
			} else {
				returnValue = (new Function(this._buffer))(); // .call(window);
			}
			this._buffer = '';

			return returnValue;
		};
	};

	return Utils;
});


text:
package org.apache.beam.sdk.schemas.utils;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.beam.sdk.schemas.FieldAccessDescriptor;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.beam.sdk.values.Row;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

/** Tests for {@link SelectHelpers}. */
@RunWith(Parameterized.class)
public class SelectHelpersTest {
  @Parameterized.Parameter public boolean useOptimizedSelect;

  @Parameters
  public static Collection<Object[]> data() {
    return Arrays.asList(new Object[][] {{false}, {true}});
  }

  static final Schema FLAT_SCHEMA =
      Schema.builder()
          .addStringField("field1")
          .addInt32Field("field2")
          .addDoubleField("field3")
          .addStringField("field_extra")
          .build();
  static final Row FLAT_ROW =
      Row.withSchema(FLAT_SCHEMA).addValues("first", 42, 3.14, "extra").build();

  static final Schema NESTED_SCHEMA =
      Schema.builder().addRowField("nested", FLAT_SCHEMA).addStringField("foo").build();
  static final Row NESTED_ROW = Row.withSchema(NESTED_SCHEMA).addValues(FLAT_ROW, "").build();

  static final Schema DOUBLE_NESTED_SCHEMA =
      Schema.builder().addRowField("nested2", NESTED_SCHEMA).build();
  static final Row DOUBLE_NESTED_ROW =
      Row.withSchema(DOUBLE_NESTED_SCHEMA).addValue(NESTED_ROW).build();

  static final Schema ARRAY_SCHEMA =
      Schema.builder()
          .addArrayField("primitiveArray", FieldType.INT32)
          .addArrayField("rowArray", FieldType.row(FLAT_SCHEMA))
          .addArrayField("arrayOfRowArray", FieldType.array(FieldType.row(FLAT_SCHEMA)))
          .addArrayField("nestedRowArray", FieldType.row(NESTED_SCHEMA))
          .build();
  static final Row ARRAY_ROW =
      Row.withSchema(ARRAY_SCHEMA)
          .addArray(1, 2)
          .addArray(FLAT_ROW, FLAT_ROW)
          .addArray(ImmutableList.of(FLAT_ROW), ImmutableList.of(FLAT_ROW))
          .addArray(NESTED_ROW, NESTED_ROW)
          .build();

  static final Schema ITERABLE_SCHEMA =
      Schema.builder()
          .addIterableField("primitiveIter", FieldType.INT32)
          .addIterableField("rowIter", FieldType.row(FLAT_SCHEMA))
          .addIterableField("iterOfRowIter", FieldType.iterable(FieldType.row(FLAT_SCHEMA)))
          .addIterableField("nestedRowIter", FieldType.row(NESTED_SCHEMA))
          .build();
  static final Row ITERABLE_ROW =
      Row.withSchema(ARRAY_SCHEMA)
          .addIterable(ImmutableList.of(1, 2))
          .addIterable(ImmutableList.of(FLAT_ROW, FLAT_ROW))
          .addIterable(ImmutableList.of(ImmutableList.of(FLAT_ROW), ImmutableList.of(FLAT_ROW)))
          .addIterable(ImmutableList.of(NESTED_ROW, NESTED_ROW))
          .build();
  static final Schema MAP_SCHEMA =
      Schema.builder().addMapField("map", FieldType.INT32, FieldType.row(FLAT_SCHEMA)).build();
  static final Row MAP_ROW =
      Row.withSchema(MAP_SCHEMA).addValue(ImmutableMap.of(1, FLAT_ROW)).build();

  static final Schema MAP_ARRAY_SCHEMA =
      Schema.builder()
          .addMapField("map", FieldType.INT32, FieldType.array(FieldType.row(FLAT_SCHEMA)))
          .build();
  static final Row MAP_ARRAY_ROW =
      Row.withSchema(MAP_ARRAY_SCHEMA)
          .addValue(ImmutableMap.of(1, ImmutableList.of(FLAT_ROW)))
          .build();

  static final Schema MAP_ITERABLE_SCHEMA =
      Schema.builder()
          .addMapField("map", FieldType.INT32, FieldType.iterable(FieldType.row(FLAT_SCHEMA)))
          .build();
  static final Row MAP_ITERABLE_ROW =
      Row.withSchema(MAP_ITERABLE_SCHEMA)
          .addValue(ImmutableMap.of(1, ImmutableList.of(FLAT_ROW)))
          .build();

  Row selectRow(Schema inputScema, FieldAccessDescriptor fieldAccessDescriptor, Row row) {
    RowSelector rowSelector =
        useOptimizedSelect
            ? SelectHelpers.getRowSelectorOptimized(inputScema, fieldAccessDescriptor)
            : SelectHelpers.getRowSelector(inputScema, fieldAccessDescriptor);
    return rowSelector.select(row);
  }

  @Test
  public void testSelectAll() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("*").resolve(FLAT_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(FLAT_SCHEMA, fieldAccessDescriptor);
    assertEquals(FLAT_SCHEMA, outputSchema);

    Row row = selectRow(FLAT_SCHEMA, fieldAccessDescriptor, FLAT_ROW);
    assertEquals(FLAT_ROW, row);
  }

  @Test
  public void testsSimpleSelectSingle() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field1").resolve(FLAT_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(FLAT_SCHEMA, fieldAccessDescriptor);
    Schema expectedSchema = Schema.builder().addStringField("field1").build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(FLAT_SCHEMA, fieldAccessDescriptor, FLAT_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addValue("first").build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testsSimpleSelectSingleWithUnderscore() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field_extra").resolve(FLAT_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(FLAT_SCHEMA, fieldAccessDescriptor);
    Schema expectedSchema = Schema.builder().addStringField("field_extra").build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(FLAT_SCHEMA, fieldAccessDescriptor, FLAT_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addValue("extra").build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testsSimpleSelectMultiple() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("field1", "field3").resolve(FLAT_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(FLAT_SCHEMA, fieldAccessDescriptor);
    Schema expectedSchema =
        Schema.builder().addStringField("field1").addDoubleField("field3").build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(FLAT_SCHEMA, fieldAccessDescriptor, FLAT_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addValues("first", 3.14).build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectedNested() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("nested").resolve(NESTED_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(NESTED_SCHEMA, fieldAccessDescriptor);
    Schema expectedSchema = Schema.builder().addRowField("nested", FLAT_SCHEMA).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(NESTED_SCHEMA, fieldAccessDescriptor, NESTED_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addValue(FLAT_ROW).build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectedNestedSingle() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("nested.field1").resolve(NESTED_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(NESTED_SCHEMA, fieldAccessDescriptor);
    Schema expectedSchema = Schema.builder().addStringField("field1").build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(NESTED_SCHEMA, fieldAccessDescriptor, NESTED_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addValue("first").build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectedNestedWildcard() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("nested.*").resolve(NESTED_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(NESTED_SCHEMA, fieldAccessDescriptor);
    assertEquals(FLAT_SCHEMA, outputSchema);

    Row row = selectRow(NESTED_SCHEMA, fieldAccessDescriptor, NESTED_ROW);
    assertEquals(FLAT_ROW, row);
  }

  @Test
  public void testSelectDoubleNested() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("nested2.nested.field1").resolve(DOUBLE_NESTED_SCHEMA);
    Schema outputSchema =
        SelectHelpers.getOutputSchema(DOUBLE_NESTED_SCHEMA, fieldAccessDescriptor);
    Schema expectedSchema = Schema.builder().addStringField("field1").build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(DOUBLE_NESTED_SCHEMA, fieldAccessDescriptor, DOUBLE_NESTED_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addValue("first").build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectArrayOfPrimitive() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("primitiveArray").resolve(ARRAY_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(ARRAY_SCHEMA, fieldAccessDescriptor);
    Schema expectedSchema =
        Schema.builder().addArrayField("primitiveArray", FieldType.INT32).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(ARRAY_SCHEMA, fieldAccessDescriptor, ARRAY_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addArray(1, 2).build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectIterableOfPrimitive() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("primitiveIter").resolve(ITERABLE_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(ITERABLE_SCHEMA, fieldAccessDescriptor);
    Schema expectedSchema =
        Schema.builder().addIterableField("primitiveIter", FieldType.INT32).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(ITERABLE_SCHEMA, fieldAccessDescriptor, ITERABLE_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addIterable(ImmutableList.of(1, 2)).build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectArrayOfRow() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("rowArray").resolve(ARRAY_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(ARRAY_SCHEMA, fieldAccessDescriptor);
    Schema expectedSchema =
        Schema.builder().addArrayField("rowArray", FieldType.row(FLAT_SCHEMA)).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(ARRAY_SCHEMA, fieldAccessDescriptor, ARRAY_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addArray(FLAT_ROW, FLAT_ROW).build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectIterableOfRow() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("rowIter").resolve(ITERABLE_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(ITERABLE_SCHEMA, fieldAccessDescriptor);
    Schema expectedSchema =
        Schema.builder().addIterableField("rowIter", FieldType.row(FLAT_SCHEMA)).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(ITERABLE_SCHEMA, fieldAccessDescriptor, ITERABLE_ROW);
    Row expectedRow =
        Row.withSchema(expectedSchema).addIterable(ImmutableList.of(FLAT_ROW, FLAT_ROW)).build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectArrayOfRowPartial() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("rowArray[].field1").resolve(ARRAY_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(ARRAY_SCHEMA, fieldAccessDescriptor);

    Schema expectedSchema = Schema.builder().addArrayField("field1", FieldType.STRING).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(ARRAY_SCHEMA, fieldAccessDescriptor, ARRAY_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addArray("first", "first").build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectIterableOfRowPartial() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("rowIter[].field1").resolve(ITERABLE_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(ITERABLE_SCHEMA, fieldAccessDescriptor);

    Schema expectedSchema = Schema.builder().addIterableField("field1", FieldType.STRING).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(ITERABLE_SCHEMA, fieldAccessDescriptor, ITERABLE_ROW);
    Row expectedRow =
        Row.withSchema(expectedSchema).addIterable(ImmutableList.of("first", "first")).build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectArrayOfRowArray() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("arrayOfRowArray[][].field1").resolve(ARRAY_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(ARRAY_SCHEMA, fieldAccessDescriptor);

    Schema expectedSchema =
        Schema.builder().addArrayField("field1", FieldType.array(FieldType.STRING)).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(ARRAY_SCHEMA, fieldAccessDescriptor, ARRAY_ROW);

    Row expectedRow =
        Row.withSchema(expectedSchema)
            .addArray(ImmutableList.of("first"), ImmutableList.of("first"))
            .build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectIterableOfRowIterable() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("iterOfRowIter[][].field1").resolve(ITERABLE_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(ITERABLE_SCHEMA, fieldAccessDescriptor);

    Schema expectedSchema =
        Schema.builder().addIterableField("field1", FieldType.iterable(FieldType.STRING)).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(ITERABLE_SCHEMA, fieldAccessDescriptor, ITERABLE_ROW);

    Row expectedRow =
        Row.withSchema(expectedSchema)
            .addIterable(ImmutableList.of(ImmutableList.of("first"), ImmutableList.of("first")))
            .build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectArrayOfNestedRow() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("nestedRowArray[].nested.field1")
            .resolve(ARRAY_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(ARRAY_SCHEMA, fieldAccessDescriptor);

    Schema expectedElementSchema = Schema.builder().addStringField("field1").build();
    Schema expectedSchema = Schema.builder().addArrayField("field1", FieldType.STRING).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(ARRAY_SCHEMA, fieldAccessDescriptor, ARRAY_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addArray("first", "first").build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectIterableOfNestedRow() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("nestedRowIter[].nested.field1")
            .resolve(ITERABLE_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(ITERABLE_SCHEMA, fieldAccessDescriptor);

    Schema expectedElementSchema = Schema.builder().addStringField("field1").build();
    Schema expectedSchema = Schema.builder().addIterableField("field1", FieldType.STRING).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(ITERABLE_SCHEMA, fieldAccessDescriptor, ITERABLE_ROW);
    Row expectedRow =
        Row.withSchema(expectedSchema).addIterable(ImmutableList.of("first", "first")).build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectMapOfRowSelectSingle() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("map{}.field1").resolve(MAP_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(MAP_SCHEMA, fieldAccessDescriptor);

    Schema expectedValueSchema = Schema.builder().addStringField("field1").build();
    Schema expectedSchema =
        Schema.builder().addMapField("field1", FieldType.INT32, FieldType.STRING).build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(MAP_SCHEMA, fieldAccessDescriptor, MAP_ROW);
    Row expectedRow = Row.withSchema(expectedSchema).addValue(ImmutableMap.of(1, "first")).build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectMapOfRowSelectAll() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("map{}.*").resolve(MAP_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(MAP_SCHEMA, fieldAccessDescriptor);
    Schema expectedSchema =
        Schema.builder()
            .addMapField("field1", FieldType.INT32, FieldType.STRING)
            .addMapField("field2", FieldType.INT32, FieldType.INT32)
            .addMapField("field3", FieldType.INT32, FieldType.DOUBLE)
            .addMapField("field_extra", FieldType.INT32, FieldType.STRING)
            .build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(MAP_SCHEMA, fieldAccessDescriptor, MAP_ROW);
    Row expectedRow =
        Row.withSchema(expectedSchema)
            .addValue(ImmutableMap.of(1, FLAT_ROW.getValue(0)))
            .addValue(ImmutableMap.of(1, FLAT_ROW.getValue(1)))
            .addValue(ImmutableMap.of(1, FLAT_ROW.getValue(2)))
            .addValue(ImmutableMap.of(1, FLAT_ROW.getValue(3)))
            .build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectMapOfArray() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("map.field1").resolve(MAP_ARRAY_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(MAP_ARRAY_SCHEMA, fieldAccessDescriptor);

    Schema expectedSchema =
        Schema.builder()
            .addMapField("field1", FieldType.INT32, FieldType.array(FieldType.STRING))
            .build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(MAP_ARRAY_SCHEMA, fieldAccessDescriptor, MAP_ARRAY_ROW);

    Row expectedRow =
        Row.withSchema(expectedSchema)
            .addValue(ImmutableMap.of(1, ImmutableList.of("first")))
            .build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectMapOfIterable() {
    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("map.field1").resolve(MAP_ITERABLE_SCHEMA);
    Schema outputSchema = SelectHelpers.getOutputSchema(MAP_ITERABLE_SCHEMA, fieldAccessDescriptor);

    Schema expectedSchema =
        Schema.builder()
            .addMapField("field1", FieldType.INT32, FieldType.iterable(FieldType.STRING))
            .build();
    assertEquals(expectedSchema, outputSchema);

    Row row = selectRow(MAP_ITERABLE_SCHEMA, fieldAccessDescriptor, MAP_ITERABLE_ROW);

    Row expectedRow =
        Row.withSchema(expectedSchema)
            .addValue(ImmutableMap.of(1, ImmutableList.of("first")))
            .build();
    assertEquals(expectedRow, row);
  }

  @Test
  public void testSelectFieldOfRecord() {
    Schema f1 = Schema.builder().addInt64Field("f0").build();
    Schema f2 = Schema.builder().addRowField("f1", f1).build();
    Schema f3 = Schema.builder().addRowField("f2", f2).build();

    Row r1 = Row.withSchema(f1).addValue(42L).build(); // {"f0": 42}
    Row r2 = Row.withSchema(f2).addValue(r1).build(); // {"f1": {"f0": 42}}
    Row r3 = Row.withSchema(f3).addValue(r2).build(); // {"f2": {"f1": {"f0": 42}}}

    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("f2.f1").resolve(f3);

    Schema outputSchema = SelectHelpers.getOutputSchema(f3, fieldAccessDescriptor);

    Row out = selectRow(f3, fieldAccessDescriptor, r3);

    assertEquals(f2, outputSchema);
    assertEquals(r2, out);
  }

  @Test
  public void testSelectFieldOfRecordOrRecord() {
    Schema f1 = Schema.builder().addInt64Field("f0").build();
    Schema f2 = Schema.builder().addRowField("f1", f1).build();
    Schema f3 = Schema.builder().addRowField("f2", f2).build();
    Schema f4 = Schema.builder().addRowField("f3", f3).build();

    Row r1 = Row.withSchema(f1).addValue(42L).build(); // {"f0": 42}
    Row r2 = Row.withSchema(f2).addValue(r1).build(); // {"f1": {"f0": 42}}
    Row r3 = Row.withSchema(f3).addValue(r2).build(); // {"f2": {"f1": {"f0": 42}}}
    Row r4 = Row.withSchema(f4).addValue(r3).build(); // {"f3": {"f2": {"f1": {"f0": 42}}}}

    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("f3.f2").resolve(f4);

    Schema outputSchema = SelectHelpers.getOutputSchema(f4, fieldAccessDescriptor);

    Row out = selectRow(f4, fieldAccessDescriptor, r4);

    assertEquals(f3, outputSchema);
    assertEquals(r3, out);
  }

  @Test
  public void testArrayRowArray() {
    Schema f1 = Schema.builder().addStringField("f0").build();
    Schema f2 = Schema.builder().addArrayField("f1", FieldType.row(f1)).build();
    Schema f3 = Schema.builder().addRowField("f2", f2).build();
    Schema f4 = Schema.builder().addArrayField("f3", FieldType.row(f3)).build();

    Row r1 = Row.withSchema(f1).addValue("first").build();
    Row r2 = Row.withSchema(f2).addArray(r1, r1).build();
    Row r3 = Row.withSchema(f3).addValue(r2).build();
    Row r4 = Row.withSchema(f4).addArray(r3, r3).build();

    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("f3.f2.f1.f0").resolve(f4);
    Schema outputSchema = SelectHelpers.getOutputSchema(f4, fieldAccessDescriptor);
    Schema expectedSchema =
        Schema.builder().addArrayField("f0", FieldType.array(FieldType.STRING)).build();
    assertEquals(expectedSchema, outputSchema);
    Row out = selectRow(f4, fieldAccessDescriptor, r4);
    Row expected =
        Row.withSchema(outputSchema)
            .addArray(Lists.newArrayList("first", "first"), Lists.newArrayList("first", "first"))
            .build();
    assertEquals(expected, out);
  }

  @Test
  public void testIterableRowIterable() {
    Schema f1 = Schema.builder().addStringField("f0").build();
    Schema f2 = Schema.builder().addIterableField("f1", FieldType.row(f1)).build();
    Schema f3 = Schema.builder().addRowField("f2", f2).build();
    Schema f4 = Schema.builder().addIterableField("f3", FieldType.row(f3)).build();

    Row r1 = Row.withSchema(f1).addValue("first").build();
    Row r2 = Row.withSchema(f2).addIterable(ImmutableList.of(r1, r1)).build();
    Row r3 = Row.withSchema(f3).addValue(r2).build();
    Row r4 = Row.withSchema(f4).addIterable(ImmutableList.of(r3, r3)).build();

    FieldAccessDescriptor fieldAccessDescriptor =
        FieldAccessDescriptor.withFieldNames("f3.f2.f1.f0").resolve(f4);
    Schema outputSchema = SelectHelpers.getOutputSchema(f4, fieldAccessDescriptor);
    Schema expectedSchema =
        Schema.builder().addIterableField("f0", FieldType.iterable(FieldType.STRING)).build();
    assertEquals(expectedSchema, outputSchema);
    Row out = selectRow(f4, fieldAccessDescriptor, r4);
    Row expected =
        Row.withSchema(outputSchema)
            .addIterable(
                ImmutableList.of(
                    ImmutableList.of("first", "first"), ImmutableList.of("first", "first")))
            .build();
    assertEquals(expected, out);
  }

  static final Schema NESTED_NULLABLE_SCHEMA =
      Schema.builder()
          .addNullableField("nested", FieldType.row(FLAT_SCHEMA))
          .addNullableField("nestedArray", FieldType.array(FieldType.row(FLAT_SCHEMA)))
          .addNullableField(
              "nestedMap", FieldType.map(FieldType.STRING, FieldType.row(FLAT_SCHEMA)))
          .build();
  static final Row NESTED_NULLABLE_ROW = Row.nullRow(NESTED_NULLABLE_SCHEMA);

  @Test
  public void testNullableSchema() {
    FieldAccessDescriptor fieldAccessDescriptor1 =
        FieldAccessDescriptor.withFieldNames("nested.field1").resolve(NESTED_NULLABLE_SCHEMA);
    Schema schema1 = SelectHelpers.getOutputSchema(NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1);
    Schema expectedSchema1 = Schema.builder().addNullableField("field1", FieldType.STRING).build();
    assertEquals(expectedSchema1, schema1);

    FieldAccessDescriptor fieldAccessDescriptor2 =
        FieldAccessDescriptor.withFieldNames("nested.*").resolve(NESTED_NULLABLE_SCHEMA);
    Schema schema2 = SelectHelpers.getOutputSchema(NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor2);
    Schema expectedSchema2 =
        Schema.builder()
            .addNullableField("field1", FieldType.STRING)
            .addNullableField("field2", FieldType.INT32)
            .addNullableField("field3", FieldType.DOUBLE)
            .addNullableField("field_extra", FieldType.STRING)
            .build();
    assertEquals(expectedSchema2, schema2);
  }

  @Test
  public void testNullableSchemaArray() {
    FieldAccessDescriptor fieldAccessDescriptor1 =
        FieldAccessDescriptor.withFieldNames("nestedArray.field1").resolve(NESTED_NULLABLE_SCHEMA);
    Schema schema1 = SelectHelpers.getOutputSchema(NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1);
    Schema expectedSchema1 =
        Schema.builder().addNullableField("field1", FieldType.array(FieldType.STRING)).build();
    assertEquals(expectedSchema1, schema1);

    FieldAccessDescriptor fieldAccessDescriptor2 =
        FieldAccessDescriptor.withFieldNames("nestedArray.*").resolve(NESTED_NULLABLE_SCHEMA);
    Schema schema2 = SelectHelpers.getOutputSchema(NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor2);
    Schema expectedSchema2 =
        Schema.builder()
            .addNullableField("field1", FieldType.array(FieldType.STRING))
            .addNullableField("field2", FieldType.array(FieldType.INT32))
            .addNullableField("field3", FieldType.array(FieldType.DOUBLE))
            .addNullableField("field_extra", FieldType.array(FieldType.STRING))
            .build();
    assertEquals(expectedSchema2, schema2);
  }

  @Test
  public void testNullableSchemaMap() {
    FieldAccessDescriptor fieldAccessDescriptor1 =
        FieldAccessDescriptor.withFieldNames("nestedMap.field1").resolve(NESTED_NULLABLE_SCHEMA);
    Schema schema1 = SelectHelpers.getOutputSchema(NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1);
    Schema expectedSchema1 =
        Schema.builder()
            .addNullableField("field1", FieldType.map(FieldType.STRING, FieldType.STRING))
            .build();
    assertEquals(expectedSchema1, schema1);

    FieldAccessDescriptor fieldAccessDescriptor2 =
        FieldAccessDescriptor.withFieldNames("nestedMap.*").resolve(NESTED_NULLABLE_SCHEMA);
    Schema schema2 = SelectHelpers.getOutputSchema(NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor2);
    Schema expectedSchema2 =
        Schema.builder()
            .addNullableField("field1", FieldType.map(FieldType.STRING, FieldType.STRING))
            .addNullableField("field2", FieldType.map(FieldType.STRING, FieldType.INT32))
            .addNullableField("field3", FieldType.map(FieldType.STRING, FieldType.DOUBLE))
            .addNullableField("field_extra", FieldType.map(FieldType.STRING, FieldType.STRING))
            .build();
    assertEquals(expectedSchema2, schema2);
  }

  @Test
  public void testSelectNullableNestedRow() {
    FieldAccessDescriptor fieldAccessDescriptor1 =
        FieldAccessDescriptor.withFieldNames("nested.field1").resolve(NESTED_NULLABLE_SCHEMA);
    Row out1 =
        selectRow(
            NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1, Row.nullRow(NESTED_NULLABLE_SCHEMA));
    assertNull(out1.getValue(0));

    FieldAccessDescriptor fieldAccessDescriptor2 =
        FieldAccessDescriptor.withFieldNames("nested.*").resolve(NESTED_NULLABLE_SCHEMA);
    Row out2 =
        selectRow(
            NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor2, Row.nullRow(NESTED_NULLABLE_SCHEMA));
    assertEquals(Collections.nCopies(4, null), out2.getValues());
  }

  @Test
  public void testSelectNullableNestedRowArray() {
    FieldAccessDescriptor fieldAccessDescriptor1 =
        FieldAccessDescriptor.withFieldNames("nestedArray.field1").resolve(NESTED_NULLABLE_SCHEMA);
    Row out1 =
        selectRow(
            NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1, Row.nullRow(NESTED_NULLABLE_SCHEMA));
    assertNull(out1.getValue(0));

    FieldAccessDescriptor fieldAccessDescriptor2 =
        FieldAccessDescriptor.withFieldNames("nestedArray.*").resolve(NESTED_NULLABLE_SCHEMA);
    Row out2 =
        selectRow(
            NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor2, Row.nullRow(NESTED_NULLABLE_SCHEMA));
    assertEquals(Collections.nCopies(4, null), out2.getValues());
  }

  @Test
  public void testSelectNullableNestedRowMap() {
    FieldAccessDescriptor fieldAccessDescriptor1 =
        FieldAccessDescriptor.withFieldNames("nestedMap.field1").resolve(NESTED_NULLABLE_SCHEMA);
    Row out1 =
        selectRow(
            NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor1, Row.nullRow(NESTED_NULLABLE_SCHEMA));
    assertNull(out1.getValue(0));

    FieldAccessDescriptor fieldAccessDescriptor2 =
        FieldAccessDescriptor.withFieldNames("nestedMap.*").resolve(NESTED_NULLABLE_SCHEMA);
    Row out2 =
        selectRow(
            NESTED_NULLABLE_SCHEMA, fieldAccessDescriptor2, Row.nullRow(NESTED_NULLABLE_SCHEMA));
    assertEquals(Collections.nCopies(4, null), out2.getValues());
  }
}


text:
mkdir -p $HOME/.sip-communicator/log

# Get architecture
ARCH=`uname -m | sed -e s/x86_64/64/ -e s/i.86/32/`

# Additionnal JVM arguments
CLIENTARGS=""

if [ $ARCH -eq 32 ]
then
    CLIENTARGS="-client -Xmx256m"
fi

export PATH=$PATH:native
java $CLIENTARGS -classpath "lib/felix.jar:sc-bundles/sc-launcher.jar:sc-bundles/util.jar:lib/" -Djava.library.path=native -Dfelix.config.properties=file:./lib/felix.client.run.properties -Djava.util.logging.config.file=lib/logging.properties net.java.sip.communicator.launcher.SIPCommunicator


text:
<?php

class Google_Service_ArtifactRegistry_TestIamPermissionsRequest extends Google_Collection
{
  protected $collection_key = 'permissions';
  public $permissions;

  public function setPermissions($permissions)
  {
    $this->permissions = $permissions;
  }
  public function getPermissions()
  {
    return $this->permissions;
  }
}


text: module.exports = require('./lib/morton');


text:
package org.apache.shardingsphere.underlying.merge.result;

import java.io.InputStream;
import java.sql.SQLException;
import java.util.Calendar;

/**
 * Merged result after merge engine.
 */
public interface MergedResult {

    /**
     * Iterate next data.
     *
     * @return has next data
     * @throws SQLException SQL Exception
     */
    boolean next() throws SQLException;

    /**
     * Get data value.
     *
     * @param columnIndex column index
     * @param type class type of data value
     * @return data value
     * @throws SQLException SQL Exception
     */
    Object getValue(int columnIndex, Class<?> type) throws SQLException;

    /**
     * Get calendar value.
     *
     * @param columnIndex column index
     * @param type class type of data value
     * @param calendar calendar
     * @return calendar value
     * @throws SQLException SQL Exception
     */
    Object getCalendarValue(int columnIndex, Class<?> type, Calendar calendar) throws SQLException;

    /**
     * Get InputStream.
     *
     * @param columnIndex column index
     * @param type class type of data value
     * @return InputStream
     * @throws SQLException SQL Exception
     */
    InputStream getInputStream(int columnIndex, String type) throws SQLException;

    /**
     * Judge ResultSet is null or not.
     *
     * @return ResultSet is null or not
     * @throws SQLException SQL Exception
     */
    boolean wasNull() throws SQLException;
}


text:
#ifndef ANDROID_HARDWARE_HIDL_HAL_DEATH_HANDLER_H
#define ANDROID_HARDWARE_HIDL_HAL_DEATH_HANDLER_H

#include <functional>
#include <mutex>
#include <unordered_map>

#include <hidl/HidlSupport.h>
#include <utils/Singleton.h>

using android::hardware::hidl_death_recipient;
using android::hidl::base::V1_0::IBase;

namespace android {

class HalDeathHandler : public hidl_death_recipient, private Singleton<HalDeathHandler> {
  public:
    typedef std::function<void()> AtExitHandler;

    // Note that the exit handler gets called using a thread from
    // RPC threadpool, thus it needs to be thread-safe.
    void registerAtExitHandler(void* cookie, AtExitHandler handler);
    void unregisterAtExitHandler(void* cookie);

    // hidl_death_recipient
    virtual void serviceDied(uint64_t cookie, const wp<IBase>& who);

    // Used both for (un)registering handlers, and for passing to
    // '(un)linkToDeath'.
    static sp<HalDeathHandler> getInstance();

  private:
    friend class Singleton<HalDeathHandler>;
    typedef std::unordered_map<void*, AtExitHandler> Handlers;

    HalDeathHandler();
    virtual ~HalDeathHandler();

    sp<HalDeathHandler> mSelf;  // Allows the singleton instance to live forever.
    std::mutex mHandlersLock;
    Handlers mHandlers;
};

}  // namespace android

#endif // ANDROID_HARDWARE_HIDL_HAL_DEATH_HANDLER_H


text:
package uk.gov.hmrc.nisp.views

import akka.util.Timeout
import org.apache.commons.text.StringEscapeUtils
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.play.guice.GuiceOneAppPerSuite
import play.api.Application
import play.api.i18n.{Lang, Messages, MessagesApi, MessagesImpl}
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.{FakeRequest, Injecting}
import play.twirl.api.Html
import uk.gov.hmrc.nisp.utils.UnitSpec

import java.util.Locale
import scala.concurrent.duration._

trait HtmlSpec extends UnitSpec with GuiceOneAppPerSuite with Injecting with BeforeAndAfterEach {

  implicit val request                      = FakeRequest()
  implicit val defaultAwaitTimeout: Timeout = 5.seconds
  implicit lazy val messages: MessagesImpl  = MessagesImpl(Lang(Locale.getDefault), inject[MessagesApi])

  override def fakeApplication(): Application = GuiceApplicationBuilder()
    .build()

  def asDocument(html: String): Document = Jsoup.parse(html)

  def assertEqualsMessage(doc: Document, cssSelector: String, expectedMessageKey: String) = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty) throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assertMessageKeyHasValue(expectedMessageKey)

    assert(
      StringEscapeUtils.unescapeHtml4(elements.first().html().replace("\n", "")) == StringEscapeUtils
        .unescapeHtml4(Messages(expectedMessageKey))
    )
  }

  def assertNotEqualsMessage(doc: Document, cssSelector: String, expectedMessageKey: String) = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty) throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assertMessageKeyHasValue(expectedMessageKey)

    assert(
      StringEscapeUtils.unescapeHtml4(elements.first().html().replace("\n", "")) != StringEscapeUtils
        .unescapeHtml4(Messages(expectedMessageKey))
        .toString()
    )
  }

  def assertEqualsValue(doc: Document, cssSelector: String, expectedValue: String) = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty) throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assert(StringEscapeUtils.unescapeHtml4(elements.first().text().replace("\n", "")) == expectedValue)
  }

  def assertMessageKeyHasValue(expectedMessageKey: String): Unit =
    assert(
      expectedMessageKey != Html(Messages(expectedMessageKey)).toString(),
      s"$expectedMessageKey has no messages file value setup"
    )

  def assertContainsDynamicMessage(doc: Document, cssSelector: String, expectedMessageKey: String, args: String*) = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty) throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assertMessageKeyHasValue(expectedMessageKey)

    val expectedString = StringEscapeUtils.unescapeHtml4(Messages(expectedMessageKey, args: _*))
    assert(StringEscapeUtils.unescapeHtml4(elements.first().html().replace("\n", "")) == expectedString)
  }

  def assertContainsDynamicMessageUsingClass(
    doc: Document,
    className: String,
    expectedMessageKey: String,
    args: String*
  ) = {
    val elements = doc.getElementsByClass(className)

    if (elements === null) throw new IllegalArgumentException(s"Class Selector $className wasn't rendered.")

    assertMessageKeyHasValue(expectedMessageKey)

    val expectedString = StringEscapeUtils.unescapeHtml4(Messages(expectedMessageKey, args: _*))
    assert(StringEscapeUtils.unescapeHtml4(elements.first().html().replace("\n", "")) == expectedString)
  }

  def assertDoesNotContainDynamicMessage(
    doc: Document,
    cssSelector: String,
    expectedMessageKey: String,
    args: String*
  ) = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty) throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assertMessageKeyHasValue(expectedMessageKey)

    val expectedString = StringEscapeUtils.unescapeHtml4(Messages(expectedMessageKey, args: _*))
    assert(StringEscapeUtils.unescapeHtml4(elements.first().html().replace("\n", "")) != expectedString)
  }

  def assertDoesNotContainDynamicMessageUsingId(
    doc: Document,
    id: String,
    expectedMessageKey: String,
    args: String*
  ) = {
    val elements = doc.getElementById(id)

    if (elements === null) throw new IllegalArgumentException(s"id Selector $id wasn't rendered.")

    assertMessageKeyHasValue(expectedMessageKey)

    val expectedString = StringEscapeUtils.unescapeHtml4(Messages(expectedMessageKey, args: _*))
    assert(StringEscapeUtils.unescapeHtml4(elements.html().replace("\n", "")) != expectedString)
  }

  def assertPageContainsDynamicMessage(doc: Document, expectedMessageKey: String, args: String*) = {
    assertMessageKeyHasValue(expectedMessageKey)

    val expectedString = StringEscapeUtils.unescapeHtml4(Messages(expectedMessageKey, args: _*))
    assert(doc.text().contains(expectedString))
  }

  def assertPageDoesNotContainDynamicMessage(doc: Document, expectedMessageKey: String, args: String*) = {
    assertMessageKeyHasValue(expectedMessageKey)

    val expectedString = StringEscapeUtils.unescapeHtml4(Messages(expectedMessageKey, args: _*))
    assert(!doc.text().contains(expectedString))
  }

  def assertPageContainsMessage(doc: Document, expectedMessage: String) = {
    assertMessageKeyHasValue(expectedMessage)
    assert(doc.text().contains(expectedMessage))
  }

  def assertPageDoesNotContainMessage(doc: Document, expectedMessage: String) = {
    assertMessageKeyHasValue(expectedMessage)
    assert(!doc.text().contains(expectedMessage))
  }

  def assertRenderedByCssSelector(doc: Document, cssSelector: String) =
    assert(!doc.select(cssSelector).isEmpty, "Element " + cssSelector + " was not rendered on the page.")

  def assertElementContainsText(doc: Document, cssSelector: String, text: String) = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty)
      throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assert(elements.first().html().contains(text), s"\n\nText '$text' was not rendered inside '$cssSelector'.\n")
  }

  def assertContainsMessageBetweenTags(
    doc: Document,
    cssSelector: String,
    expectedMessageKey: String,
    cssSelectorSecondElement: String
  ) = {

    val elements      = doc.select(cssSelector)
    val secondElement = doc.select(cssSelectorSecondElement);

    if (elements.isEmpty) throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assertMessageKeyHasValue(expectedMessageKey)

    val expectedString    = StringEscapeUtils.unescapeHtml4(Messages(expectedMessageKey).toString())
    val elementText       = elements.first().text().replace("\n", "");
    val secondElementText = secondElement.first().text().replace("\n", "");
    val mainElementText   = elementText.replace(secondElementText, "");

    assert(StringEscapeUtils.unescapeHtml4(mainElementText.replace("\u00a0", "").toString()) == expectedString)
  }

  def assertContainsTextBetweenTags(
    doc: Document,
    cssSelector: String,
    expectedMessageValue: String,
    cssSelectorSecondElement: String
  ) = {

    val elements      = doc.select(cssSelector)
    val secondElement = doc.select(cssSelectorSecondElement);

    if (elements.isEmpty) throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    val expectedString    = expectedMessageValue
    val elementText       = elements.first().text().replace("\n", "");
    val secondElementText = secondElement.first().text().replace("\n", "");
    val mainElementText   = elementText.replace(secondElementText, "");

    assert(StringEscapeUtils.unescapeHtml4(mainElementText.replace("\u00a0", "").toString()) == expectedString)
  }

  def assertLinkHasValue(doc: Document, cssSelector: String, linkValue: String) = {
    val elements = doc.select(cssSelector)
    assert(elements.attr("href") === linkValue)
  }

  def assertContainsChildWithMessage(
    doc: Document,
    cssSelector: String,
    expectedMessageKey: String,
    messageArgs1: String,
    messageArgs2: String,
    messageArgs3: String
  ) = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty) throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assertMessageKeyHasValue(expectedMessageKey)
    val sMessage =
      Messages(expectedMessageKey) + " " + Messages(messageArgs1) + " " + Messages(messageArgs2) + " " + Messages(
        messageArgs3
      );

    val expectedString = StringEscapeUtils.unescapeHtml4(sMessage.toString());
    assert(
      StringEscapeUtils.unescapeHtml4(elements.first().text().replace("\u00a0", "")) == expectedString
        .replace("\u00a0", "")
    )
  }

  def assertRenderedById(doc: Document, id: String) =
    assert(doc.getElementById(id) != null, "\n\nElement " + id + " was not rendered on the page.\n")

  def assertElementHasValue(doc: Document, id: String, value: String) = {
    assertRenderedById(doc, id)

    assert(
      doc.getElementById(id).attr("value") == value,
      s"\n\nElement $id has incorrect value. Expected '$value', found '${doc.getElementById(id).attr("value")}'."
    )
  }

  def assertElementNotContainsText(doc: Document, cssSelector: String, text: String) = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty)
      throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assert(!elements.first().html().contains(text), s"\n\nText '$text' was rendered inside '$cssSelector'.\n")
  }

  def assertHasClass(doc: Document, cssSelector: String, className: String) = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty)
      throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assert(elements.first().hasClass(className), s"\n\nElement '$cssSelector' doesn't have '$className' class.\n")
  }

  def assertDoesNotHaveClass(doc: Document, cssSelector: String, className: String) = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty)
      throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assert(!elements.first().hasClass(className), s"\n\nElement '$cssSelector' has '$className' class.\n")
  }

  def assertElementsOwnMessage(doc: Document, cssSelector: String, messageKey: String, stringValue: String = "") = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty)
      throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assertMessageKeyHasValue(messageKey)

    val expectedString = StringEscapeUtils.unescapeHtml4(Messages(messageKey).toString() + stringValue);
    assert(
      StringEscapeUtils.unescapeHtml4(elements.first().ownText().replace("\u00a0", "")) == expectedString
        .replace("\u00a0", "")
    )
  }

  def assertElementsOwnText(doc: Document, cssSelector: String, expectedText: String) = {
    val elements = doc.select(cssSelector)

    if (elements.isEmpty)
      throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    val expectedString = StringEscapeUtils.unescapeHtml4(expectedText);
    assert(
      StringEscapeUtils.unescapeHtml4(elements.first().ownText().replace("\u00a0", "")) == expectedString
        .replace("\u00a0", "")
    )
  }

  def assertContainsExpectedValue(
    doc: Document,
    cssSelector: String,
    expectedMessageKey: String,
    secondMessageValue: String
  ) = {

    val elements = doc.select(cssSelector)
    if (elements.isEmpty) throw new IllegalArgumentException(s"CSS Selector $cssSelector wasn't rendered.")

    assertMessageKeyHasValue(expectedMessageKey)

    val expectedString = StringEscapeUtils.unescapeHtml4(Messages(expectedMessageKey, secondMessageValue).toString())
    val elementText    = elements.first().html().replace("\n", "");

    assert(StringEscapeUtils.unescapeHtml4(elementText.replace("\u00a0", "").toString()) == expectedString)
  }
}


text:
from MedipReport import *

##############################################################
##############################################################
##############################################################

class TrackerDMRSummary(ProjectTracker, SingleTableTrackerRows):
    table = "dmr_stats"
    fields = ("method", "track", "treatment", "control")

class TrackerDESeqSizeFactors(ProjectTracker):
    pattern = "(.*)_deseq_size_factors"

    def __call__(self, track):
        return self.getAll("SELECT sample, * FROM %(track)s_deseq_size_factors")

class TrackerDESeqSummary(ProjectTracker):
    pattern = "(.*)_deseq_summary"

    def __call__(self, track):
        return self.getAll("SELECT sample, * FROM %(track)s_deseq_summary")

class TrackerEdgeRSummary(ProjectTracker):
    pattern = "(.*)_edger_summary"

    def __call__(self, track):
        return self.getAll("SELECT sample, * FROM %(track)s_edger_summary")

class TrackerDESeqSpikeIn(TrackerMatrices):
    pass

class TrackerEdgeRSpikeIn(TrackerMatrices):
    pass

class TrackerDESeqPower(ProjectTracker, MultipleTableTrackerEdgeList):
    pattern = '(.*)_power_deseq'
    row = 'fdr'
    column = 'power'
    value = 'intervals_percent'

class TrackerEdgeRPower(TrackerDESeqPower):
    pattern = '(.*)_power_edger'

class TrackerDESeqSpikeInPercent(ProjectTracker):
    '''select spike-in results for track and FDR.'''
    pattern = "(.*)_deseq_spike"
    slices = (0.01, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0)

    def __call__(self, track, slice):
        data = self.get(
            """SELECT expression, fold, percent
            FROM %(track)s_deseq_spike
            WHERE fdr = %(slice)s
            ORDER BY expression, fold""")
        result = odict()
        for expression, fold, value in data:
            try:
                result[expression][fold] = value
            except KeyError:
                result[expression] = odict()
                result[expression][fold] = value

        return result

class TrackerEdgeRSpikeInPercent(TrackerDESeqSpikeInPercent):
    pattern = "(.*)_edger_spike"

# ##############################################################
# ##############################################################
# ##############################################################
# class TrackerDESeqFit( Tracker ):
#     method = "deseq"
#     tracks = [ x.asFile() for x in EXPERIMENTS ]
#     slices = [ x.asFile() for x in GENESET_TRACKS ]

#     def __call__(self, track, slice = None ):
#         edir = EXPORTDIR
#         level = "gene"
#         geneset = slice
#         method = self.method

#         filename = "%(edir)s/%(method)s/%(geneset)s_%(method)s_%(level)s_fit_%(track)s.png" % locals()

# fitting information will not exist if there are no replicates
#         if not os.path.exists( filename ): return None

#         rst_text = '''
# %(level)s %(track)s %(geneset)s
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# .. figure:: %(edir)s/%(method)s/%(geneset)s_%(method)s_%(level)s_fit_%(track)s.png

# .. figure:: %(edir)s/%(method)s/%(geneset)s_%(method)s_%(level)s_residuals_%(track)s.png

# ''' % locals()

#         return odict( (("text", rst_text),) )

# ##############################################################
# ##############################################################
# ##############################################################
# class TrackerDESummaryPlots( Tracker ):

#     tracks = [ x.asFile() for x in GENESET_TRACKS ]

#     def __call__(self, track, slice = None ):
#         edir = EXPORTDIR
#         geneset = track
#         method = self.method

#         rst_text = []

#         for level in self.levels:
#             for fn in (
#                 "%(edir)s/%(method)s/%(geneset)s_%(method)s_%(level)s_heatmap.png",
#                 "%(edir)s/%(method)s/%(geneset)s_%(method)s_%(level)s_scvplot.png",
#                 "%(edir)s/%(method)s/%(geneset)s_%(method)s_%(level)s_pvalue_vs_length.png" ):
#                 f = fn % locals()
#                 if not os.path.exists(f): continue
#                 rst_text.append( ".. figure:: %(f)s" % locals() )

#         if rst_text:
#             rst_text = '''
# %(geneset)s
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# ''' % locals() + "\n\n".join( rst_text )
#         else:
#             rst_text = ""

#         return odict( (("text", rst_text),) )

# class TrackerDESummaryPlotsDESeq(TrackerDESummaryPlots ):
#     method = "deseq"
#     levels = ("gene",)

# class TrackerDESummaryPlotsCuffdiff(TrackerDESummaryPlots ):
#     method = "cuffdiff"
#     levels = CUFFDIFF_LEVELS

# ################################################################
# ################################################################
# ################################################################
# class TrackerDifferentialExpression( Tracker ):

#     tracks = [ x.asFile() for x in GENESET_TRACKS ]

#     def __call__(self, track, slice = None ):

#         edir, method = EXPORTDIR, self.method
#         rst_text = []

#         geneset = track
#         for level in self.levels:
#             for x,y in itertools.combinations( EXPERIMENTS, 2 ):
#                 filename = "%(edir)s/%(method)s/%(geneset)s_%(method)s_%(level)s_%(x)s_vs_%(y)s_significance.png" % locals()
#                 if not os.path.exists( filename ): continue

#                 rst_text.append('''
# %(geneset)s %(level)s %(x)s vs %(y)s
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

# .. figure:: %(filename)s

# ''' % locals())

#         return odict( (("text", "\n".join( rst_text)),) )

# class TrackerDEPairwiseDESeq( TrackerDifferentialExpression ):
#     method = "deseq"
#     levels = ("gene",)

# class TrackerDEPairwiseCuffdiff( TrackerDifferentialExpression ):
#     method = "cuffdiff"
#     levels = CUFFDIFF_LEVELS

# #############################################################
# #############################################################
# #############################################################
# ##
# #############################################################
# class DifferentialExpressionComparison( RnaseqTracker ):

#     tracks = list( itertools.combinations( ("deseq", "cuffdiff"), 2 ))
#     slices = [ x.asFile() for x in GENESET_TRACKS ]

# class DifferentialExpressionOverlap( DifferentialExpressionComparison ):

#     def __call__(self, track, slice = None ):

#         pair1, pair2 = track

#         a = self.get('''SELECT test_id, track1, track2 FROM %(slice)s_%(pair1)s_gene_diff WHERE significant''')
#         b = self.get('''SELECT test_id, track1, track2 FROM %(slice)s_%(pair2)s_gene_diff WHERE significant''')

#         a = set(map(str,a))
#         b = set(map(str,b))

#         return odict( ( (pair1, len(a)),
#                         (pair2, len(b)),
#                         ("shared", len(a.intersection(b)) ) ) )

# class DifferentialExpressionCorrelationPValue( DifferentialExpressionComparison ):
#     '''fold change estimates per gene set.'''
#     def __call__(self, track, slice = None ):

#         pair1, pair2 = track

#         data = self.getAll( '''
#                    SELECT a.pvalue as %(pair1)s, b.pvalue as %(pair2)s
#                           FROM %(slice)s_%(pair1)s_gene_diff AS a,
#                                %(slice)s_%(pair2)s_gene_diff AS b
#                    WHERE a.test_id = b.test_id AND a.track1 = b.track1 AND a.track2 = b.track2
#                          AND ABS( a.lfold ) != 10
#                          AND ABS( b.lfold ) != 10
#                          AND a.pvalue IS NOT NULL
#                          AND b.pvalue IS NOT NULL
#                          AND a.status == 'OK' and b.status == 'OK'
#                          ''' )

#         for k in data.keys():
#             data[k] = [ math.log10( x + 0.0000001 ) for x in data[k]  ]

#         return data

# class DifferentialExpressionCorrelationFoldChange( DifferentialExpressionComparison ):
#     '''fold change estimates per gene set.'''
#     def __call__(self, track, slice = None ):

#         pair1, pair2 = track

#         data = self.getAll( '''
#                    SELECT a.lfold as %(pair1)s, b.lfold as %(pair2)s
#                           FROM %(slice)s_%(pair1)s_gene_diff AS a,
#                                %(slice)s_%(pair2)s_gene_diff AS b
#                    WHERE a.test_id = b.test_id AND a.track1 = b.track1 AND a.track2 = b.track2
#                          AND ABS( a.lfold ) != 10
#                          AND ABS( b.lfold ) != 10''' )

#         return data

# #############################################################
# #############################################################
# #############################################################
# ##
# #############################################################
# class VolcanoTracker( RnaseqTracker ):
#     '''insert volcano plots.'''
#     tracks = [ x.asFile() for x in GENESET_TRACKS ]

#     def __call__(self, track, slice = None ):

#         data = self.getAll( """SELECT lfold,
#                                     pvalue,
#                                     CASE WHEN value1 < value2 THEN value2 ELSE value1 END AS max_fpkm
#                                     FROM %(track)s_%(method)s_%(slice)s_diff
#                                     WHERE pvalue IS NOT NULL AND pvalue != 'nan' AND
#                                           lfold IS NOT NULL AND
#                                           max_fpkm > 0""" )
#         if data:
#             data["pvalue"] = [ -math.log10( x + 0.00001 ) for x in data["pvalue"] ]
#             data["max_fpkm"] = [ math.log10( x + 0.00001 ) for x in data["max_fpkm"] ]
#         return data

# class VolcanoPlotCuffdiff( VolcanoTracker ):
#     method = "cuffdiff"
#     slices = CUFFDIFF_LEVELS

# class VolcanoPlotDESeq( VolcanoTracker ):
#     method = "deseq"
#     slices = ("gene",)

# #############################################################
# #############################################################
# #############################################################
# ##
# #############################################################
# class ExonCounts( RnaseqTracker ):
#     '''get unnormalized read counts in the exons for a gene.

#     The gene name is given as the slice.'''

#     pattern = "(.*)_exon_counts"

#     def __call__(self, track, options = None ):

#         if not options: raise ValueError( 'tracker requires gene_id' )

#         data = self.getAll('''SELECT gene_id, * FROM
#                        %(track)s_exon_counts
#                        WHERE gene_id = '%(options)s' ''' )

#         if data: del data["gene_id"]
#         return data


text:
module RKMotion
  module RestKit
    class RestfulHelpers
      attr_reader :an_attr_accessor

      def initialize
      end

      def helper_1
      end

    end
  end
end


text:
package org.apache.oodt.config.distributed;

import org.apache.commons.io.FileUtils;
import org.apache.oodt.config.distributed.cli.ConfigPublisher;
import org.apache.oodt.config.test.AbstractDistributedConfigurationTest;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Testing the functionality of {@link DistributedConfigurationPublisher} and its CLI
 *
 * @author Imesha Sudasingha
 */
public class DistributedConfigurationPublisherTest extends AbstractDistributedConfigurationTest {

    private static final String CONFIG_PUBLISHER_XML = "config-publisher.xml";

    @Before
    public void setUpTest() {
        System.setProperty("org.apache.oodt.cas.cli.action.spring.config", "src/main/resources/cmd-line-actions.xml");
        System.setProperty("org.apache.oodt.cas.cli.option.spring.config", "src/main/resources/cmd-line-options.xml");
    }

    @After
    public void tearDownTest() {
        System.clearProperty("org.apache.oodt.cas.cli.action.spring.config");
        System.clearProperty("org.apache.oodt.cas.cli.option.spring.config");
    }

    @Test
    public void publishConfigurationTest() throws Exception {
        // Publishing configuration through CLI and verifying whether they were stored correctly
        ConfigPublisher.main(new String[]{
                "-connectString", zookeeper.getConnectString(),
                "-config", CONFIG_PUBLISHER_XML,
                "-a", "publish"
        });

        ApplicationContext applicationContext = new ClassPathXmlApplicationContext(CONFIG_PUBLISHER_XML);
        Map distributedConfigurationPublishers = applicationContext.getBeansOfType(DistributedConfigurationPublisher.class);

        List<DistributedConfigurationPublisher> publishers = new ArrayList<>(distributedConfigurationPublishers.values().size());
        for (Object bean : distributedConfigurationPublishers.values()) {
            publishers.add((DistributedConfigurationPublisher) bean);
        }

        for (DistributedConfigurationPublisher publisher : publishers) {
            Assert.assertTrue(publisher.verifyPublishedConfiguration());

            ZNodePaths zNodePaths = publisher.getZNodePaths();

            // Checking for configuration files
            for (Map.Entry<String, String> entry : publisher.getPropertiesFiles().entrySet()) {
                String zNodePath = zNodePaths.getPropertiesZNodePath(entry.getValue());
                Assert.assertNotNull(client.checkExists().forPath(zNodePath));

                String storedContent = new String(client.getData().forPath(zNodePath));
                String fileContent = FileUtils.readFileToString(new File(entry.getKey()));
                Assert.assertEquals(fileContent, storedContent);
            }

            // Checking for configuration files
            for (Map.Entry<String, String> entry : publisher.getConfigFiles().entrySet()) {
                String zNodePath = zNodePaths.getConfigurationZNodePath(entry.getValue());
                Assert.assertNotNull(client.checkExists().forPath(zNodePath));

                String storedContent = new String(client.getData().forPath(zNodePath));
                String fileContent = FileUtils.readFileToString(new File(entry.getKey()));
                Assert.assertEquals(fileContent, storedContent);
            }
        }

        // Clearing configuration through CLI and checking whether the configuration has actually been gone
        ConfigPublisher.main(new String[]{
                "-connectString", zookeeper.getConnectString(),
                "-config", CONFIG_PUBLISHER_XML,
                "-a", "clear"
        });

        for (DistributedConfigurationPublisher publisher : publishers) {
            Assert.assertFalse(publisher.verifyPublishedConfiguration());

            ZNodePaths zNodePaths = publisher.getZNodePaths();

            // Checking for configuration files
            for (Map.Entry<String, String> entry : publisher.getPropertiesFiles().entrySet()) {
                String zNodePath = zNodePaths.getPropertiesZNodePath(entry.getValue());
                Assert.assertNull(client.checkExists().forPath(zNodePath));
            }

            // Checking for configuration files
            for (Map.Entry<String, String> entry : publisher.getConfigFiles().entrySet()) {
                String zNodePath = zNodePaths.getConfigurationZNodePath(entry.getValue());
                Assert.assertNull(client.checkExists().forPath(zNodePath));
            }
        }

        for (DistributedConfigurationPublisher publisher : publishers) {
            publisher.destroy();
        }
    }
}


text:
from cryptolock.main import main

if __name__ == '__main__':
    main()


text:
XML3D.shaders.register("background-video", {

    vertex : [
        "attribute vec2 position;",

        "varying vec2 fragTexCoord;",

        "void main(void) {",
        "    gl_Position = vec4(position, 0.9999, 1.0);",
        "    fragTexCoord = 0.5 * position + vec2(0.5);",
        "}"
    ].join("\n"),

    fragment : [
        "#ifdef GL_ES",
          "precision highp float;",
        "#endif",

        "uniform sampler2D videoTex;",

        "varying vec2 fragTexCoord;",

        "void main(void) {",
        "  vec3 color = texture2D(videoTex, fragTexCoord).rgb;",
        "  gl_FragColor = vec4(color, 1.0);",
        "}"
    ].join("\n"),

    samplers: {
        videoTex : null
    }
});

// we have to deactivate frustum culling at all - otherwise the background disappears
// console.log(XML3D.options.getKeys());
XML3D.options.setValue("renderer-frustumCulling", false);


text:
using Signum.Utilities;

namespace Signum.Upgrade.Upgrades;

class Upgrade_20210119_DeepL : CodeUpgradeBase
{
    public override string Description => "Add DeepL support and parallel translations";

    public override void Execute(UpgradeContext uctx)
    {
        uctx.ChangeCodeFile(@"Southwind.Entities/ApplicationConfiguration.cs ", file =>
        {
            file.InsertBeforeFirstLine(a => a.Contains("[AutoInit]"),
@"
[Serializable]
public class TranslationConfigurationEmbedded : EmbeddedEntity
{
[Description(""Azure Cognitive Service API Key"")]
[StringLengthValidator(Max = 300), FileNameValidator]
public string? AzureCognitiveServicesAPIKey { get; set; }

[Description(""Azure Cognitive Service Region"")]
[StringLengthValidator(Max = 300), FileNameValidator]
public string? AzureCognitiveServicesRegion { get; set; }

[Description(""DeepL API Key"")]
[StringLengthValidator(Max = 300), FileNameValidator]
public string? DeepLAPIKey { get; set; }
}

");

            file.InsertAfterFirstLine(a => a.Contains("public FoldersConfigurationEmbedded Folders { get; set; }"),
@"
public TranslationConfigurationEmbedded Translation { get; set; }");
        });

        uctx.ChangeCodeFile(@"Southwind.React/App/Southwind/Templates/ApplicationConfiguration.tsx", file =>
        {
            file.InsertAfterLastLine(a => a.Contains("</Tab>"),
@"<Tab eventKey=""translation"" title={ctx.niceName(a => a.translation)}>
<RenderEntity ctx={ctx.subCtx(a => a.translation)} />
</Tab>");

        });

        uctx.ChangeCodeFile(@"Southwind.React/Startup.cs", file =>
        {
            file.ReplaceLine(a => a.Contains("TranslationServer.Start(app, new AlreadyTranslatedTranslator"),
@"TranslationServer.Start(app,
new AlreadyTranslatedTranslator(),
new AzureTranslator(
    () => Starter.Configuration.Value.Translation.AzureCognitiveServicesAPIKey,
    () => Starter.Configuration.Value.Translation.AzureCognitiveServicesRegion),
new DeepLTranslator(() => Starter.Configuration.Value.Translation.DeepLAPIKey)
);");

        });

        var azureKey = SafeConsole.AskString("Azure API Key?");
        var deeplKey = SafeConsole.AskString("DeepL API Key?");

        uctx.ChangeCodeFile(@"Southwind.Terminal\SouthwindMigrations.cs", file =>
        {
            file.InsertBeforeFirstLine(a => a.Contains("Folders = new FoldersConfigurationEmbedded"),
@$"Translation = new TranslationConfigurationEmbedded
{{
AzureCognitiveServicesAPIKey = ""{azureKey}"",
DeepLAPIKey = ""{deeplKey}"",
}},");
        });

        uctx.ChangeCodeFile(@"Southwind.Test.Environment/SouthwindEnvironment.cs", file =>
            {
                file.InsertBeforeFirstLine(a => a.Contains("Folders = new FoldersConfigurationEmbedded"),
@$"Translation = new TranslationConfigurationEmbedded
{{
AzureCognitiveServicesAPIKey = ""{azureKey}"",
DeepLAPIKey = ""{deeplKey}"",
}},");

            });
    }
}


text:
<?php

namespace Inertia\WinspireBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class ExperienceController extends Controller
{
    public function extendedFooterAction()
    {
        $repository = $this->getDoctrine()
            ->getEntityManager()
            ->getRepository('InertiaWinspireBundle:Experience');
        $query = $repository->createQueryBuilder('e')
            ->where('e.is_featured = true')
            ->andWhere('e.is_active = true')
            ->getQuery();
        $featured = $query->getResult();

        $repository = $this->getDoctrine()
            ->getEntityManager()
            ->getRepository('InertiaWinspireBundle:Category');
        $query = $repository->createQueryBuilder('c')
            ->where('c.is_active = true')
            ->orderBy('c.name', 'ASC')
            ->getQuery();
        $categories = $query->getResult();

        return $this->render('InertiaWinspireBundle::extendedFooter.html.twig',
            array(
                'featured' => $featured,
                'categories' => $categories,
            )
        );
    }
}


text:
if(typeof process !== "undefined")
	var define = require.define;
define(function(require, exports, module){
//	The Globalization class in Noodles is designed to allow warnings, errors, tags, and miscellaneous identifiers
//to be translated dynamically into other languages. This allows templates of other languages to be created.
//	The Class relies on a particular data structure being created as a dictionary whose keys are english
//allowing a translation into the target language to occur. This, unfortunately, means  that all plugins
//need to be written in English if they are expected to work globally. If the Globalization Class is not used,
//the original language that warnings, error, etc are written in wil always be the text that is passed for
//those particular messages.

/*--module--
name:currentLanguages
description: list of lanugages currently available.
@type{object}
*/
var currentLanguages = {};
/*--module--
name:LanguageClasses
description: hash of saved classes
@type{object}
*/
var languageClasses = {}
/*--exports--
name:language
description: function that returns the appropriate class
@param{string}
@param{function}
*/
exports.language = function(lang,callback){
	if(typeof lang !== "string") lang = 'english';
	lang = lang.toLowerCase();
	if(!currentLanguages[this.language]){
		var _self = this;
		if(lang === "english"){
			currentLanguages[lang] = true;
			languageClasses[lang] = new Globalization(lang,{});
			callback(languageClasses[lang]);
		}
		else{
			require(['./../globalization/' + lang],function(lanuage){
				currentLanguages[lang] = true;
				languageClasses[lang] = new Globalization(lang,language);
				callback(languageClasses[lang]);
			});
		}
	}
	else{
		callback(languageClasses[lang]);
	}
};
/*--exports--
name:addToLanguage
description: function adds warnings, tags, errors, etc
	to specified language
@param{string}
@param{object}
*/
exports.addToLanguage = function(language,languageObject){
	language = language.toString();
	language = languageClasses[language];
	var keys = Object.keys(languageObject),
		i = keys.length,
		keys2, i2,temp,temp2;
	while(i-- !== 0){
		temp2 = languageObject[keys[i]];
		keys2 = Object.keys(temp2);
		i2 = keys2.length;
		temp = language[keys[i]];
		while(i2-- !== 0){
			temp[keys2[i2].toLowerCase()] = temp2[keys2[i2]];
		}
	}
};
/*--module--
name:Language
description:Language Class.
*/
var Globalization = function(lang,language){
	this.language = lang;
	if(this.language !== 'english'){
		var keys = Object.keys(language),
			i = keys.length;
		while(i-- !== 0){
			this[keys[i]] = language[keys[i]];
		}
	}
}
/*--Globalization--
name:warning
description:translate warnings
*/
Globalization.prototype.warning = function(string){
	if(typeof string !== "string") return "";
	if(this.language === "english") return string;
	var args = Array.prototype.slice.call(arguments);
	args.shift();
	return (this.warnings[string.toLowerCase()] || string || "") + args.join('');
};
/*--Globalization--
name:error
description:translate warnings
*/
Globalization.prototype.error = function(string){
	if(typeof string !== "string") return "";
	if(this.language === "english") return string;
	var args = Array.prototype.slice.call(arguments);
	args.shift();
	return (this.errors[string.toLowerCase()] || string || "") + args.join('');;
};
/*--Globalization--
name:tag
description:translate warnings
*/
Globalization.prototype.tag = function(string){
	if(typeof string !== "string") return "";
	if(this.language === "english") return string;
	var args = Array.prototype.slice.call(arguments);
	args.shift();
	return (this.tags[string.toLowerCase()] || string || "") + args.join('');
};
/*--Globalization--
name:error
description:translate warnings
*/
Globalization.prototype.other = function(string){
	if(typeof string !== "string") return "";
	if(this.language === "english") return string;
	var args = Array.prototype.slice.call(arguments);
	args.shift();
	return (this.others[string.toLowerCase()] || string || "") + args.join('');
};
/*--Globalization--
name:plugin
description:translate pluginName
*/
Globalization.prototype.plugin = function(string){
	if(typeof string !== "string") return "";
	if(this.language === "english") return string;
	var args = Array.prototype.slice.call(arguments);
	args.shift();
	return (this.plugin[string.toLowerCase()] || string || "") + args.join('');
};
/*--Globalization--
name:coreTags
description:coreTags in english
*/
Globalization.prototype.coreTags = require('./config').coretags;
});


text:
namespace UnitTestHelpers.Tests
{
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using System;

    [TestClass]
    public class TestExpectedArgumentExceptionTest : BaseTestClass
    {
        [TestMethod]
        public void TestExpectedArgumentExceptionWithArgumentExceptionNotValidRaised()
        {
            try
            {
                Action<string> func = str => { throw new ArgumentException("The input string should have a value", "str"); };

                TestExpectedArgumentException<ArgumentException>(() => func(string.Empty), "The input string should have a value\r\nParameter name: str");
            }
            catch (AssertFailedException ex)
            {
                Assert.AreEqual("Assert.AreEqual failed. Expected:<Test>. Actual:<Value does not fall within the expected range.>. ", ex.Message);
            }
        }

        [TestMethod]
        public void TestExpectedArgumentExceptionWithArgumentExceptionRaised()
        {
            TestExpectedArgumentException<ArgumentException>(() => { throw new ArgumentException("Test"); }, "Test");
        }

        [TestMethod]
        public void TestExpectedArgumentExceptionWithArgumentNullExceptionRaised()
        {
            Action<object> func = obj => { throw new ArgumentNullException("obj"); };

            TestExpectedArgumentException<ArgumentNullException>(() => func(null), "obj");
        }

        [TestMethod]
        public void TestExpectedArgumentExceptionWithNoExceptionRaised()
        {
            try
            {
                TestExpectedArgumentException<ArgumentException>(() => { }, "Test");
            }
            catch (NoExceptionRaisedException ex)
            {
                Assert.AreEqual(Strings.NoExceptionRaisedExceptionDefaultMessage, ex.Message);
            }
        }

        [TestMethod]
        public void TestExpectedArgumentExceptionWithNullAction()
        {
            try
            {
                TestExpectedArgumentException<ArgumentException>(null, string.Empty);
            }
            catch (ArgumentNullException ex)
            {
                Assert.AreEqual("action", ex.ParamName);
            }
        }

        [TestMethod]
        public void TestExpectedArgumentExceptionWithStringEmpty()
        {
            try
            {
                TestExpectedArgumentException<ArgumentException>(() => { }, string.Empty);
            }
            catch (ArgumentException ex)
            {
                Assert.AreEqual("The parameter name cannot be null, empty or composed only by spaces.\r\nParameter name: parameterName", ex.Message);
            }
        }
    }
}


text:
"""The presentation module for GSoC statistics."""

from gviz import gviz_api
from django.utils import simplejson

from soc.models import countries
from soc.modules.gsoc.statistics import mapping
from soc.modules.gsoc.models.program import GSoCProgram
from soc.modules.gsoc.models.statistic_data import GSoCStatisticData

class AbstractPresenter(object):

  def _getDataSources(self, key_name):
    key_names = mapping.DEPENDENCIES[key_name]
    statistics = GSoCStatisticData.get_by_key_name(key_names)
    sources = {}
    for statistic in statistics:
      sources[statistic.key().name()] = simplejson.loads(statistic.data)

    if len(sources) != len(key_names):
      raise Exception('At least one of the dependencies cannot be loaded.')

    return sources

  def _getDataTableRows(self, key_name, sources):
    if key_name == 'admins':
      return self._getAdmins(key_name, sources)
    if key_name == 'profiles':
      return self._getProfiles(key_name, sources)
    if key_name == 'proposals_per_student':
      return self._getProposalsPerStudent(key_name, sources)
    if key_name == 'mentors':
      return self._getMentors(key_name, sources)
    if key_name == 'mentors_per_country':
      return self._getMentorsPerCountry(key_name, sources)
    if key_name == 'students':
      return self._getStudents(key_name, sources)
    if key_name == 'students_per_country':
      return self._getStudentsPerCountry(key_name, sources)

    raise Exception('Statistic %s not supported.' % key_name)

  def _getAdmins(self, key_name, sources):
    return self._getNumberPerProgramRows(key_name, sources)

  def _getMentors(self, key_name, sources):
    return self._getNumberPerProgramRows(key_name, sources)

  def _getMentorsPerCountry(self, key_name, sources):
    return self._getPerProgramPerCountryRows(key_name, sources)

  def _getProfiles(self, key_name, sources):
    return self._getNumberPerProgramRows(key_name, sources)

  def _getProposalsPerStudent(self, key_name, sources):
    values = range(21)
    return self._getPerProgramPerNumberRows(key_name, sources, values)

  def _getStudents(self, key_name, sources):
    return self._getNumberPerProgramRows(key_name, sources)

  def _getStudentsPerCountry(self, key_name, sources):
    return self._getPerProgramPerCountryRows(key_name, sources)

  def _getNumberPerProgramRows(self, key_name, sources):
    source = sources[key_name]

    rows = []
    for program, number in source.iteritems():
      program = GSoCProgram.get_by_key_name(program)
      rows.append([program.name, int(number)])

    return rows

  def _getPerProgramPerCountryRows(self, key_name, sources):
    source = sources[key_name]

    rows = []
    for country in countries.COUNTRIES_AND_TERRITORIES:
      rows.append([country] +
          [program.get(country, 0) for program in source.values()])
    return rows

  def _getPerProgramPerNumberRows(self, key_name, sources, values=None):
    source = sources[key_name]

    if not values:
      existingValues = set(i.keys() for i in source.itervalues())
      values = range(min(values), max(values) - 1)

    rows = []
    for value in values:
      rows.append([value] +
          [program.get(str(value), 0) for program in source.values()])
    return rows

class JsonPresenter(AbstractPresenter):
  def get(self, key_name):
    statistic = GSoCStatisticData.get_by_key_name(key_name)
    return statistic.data if statistic else {}

_NUMBER_PER_PROGRAM_DESCRIPTION = [
    ('program', 'string', 'Program'),
    ('number', 'number', 'Number')]

class GvizPresenter(AbstractPresenter):
  def get(self, key_name):
    sources = self._getDataSources(key_name)
    description = self._getDataTableDescriptions(key_name, sources)
    rows = self._getDataTableRows(key_name, sources)

    data_table = gviz_api.DataTable(description)
    data_table.LoadData(rows)

    json = data_table.ToJSon()
    return json

  def _getDataTableDescriptions(self, key_name, sources):
    if key_name in ['profiles', 'students', 'mentors', 'admins',
                    'students_with_proposals', 'students_with_projects']:
      return _NUMBER_PER_PROGRAM_DESCRIPTION
    if key_name in ['students_per_country', 'mentors_per_country']:
      columns = []
      columns.append(('country', 'string', 'Country'))
      source = sources[key_name]
      programs = GSoCProgram.get_by_key_name(source.keys())
      for program in programs:
        columns.append((program.key().name(), 'number', program.name))
      return columns
    if key_name in ['proposals_per_student']:
      columns = []
      columns.append(('proposals', 'number', 'Proposals'))
      source = sources[key_name]
      programs = GSoCProgram.get_by_key_name(source.keys())
      for program in programs:
        columns.append((program.key().name(), 'number', program.name))
      return columns