text:
;!function($){
    jQuery.fn.extend({
        /**
         * @method validate form
         * @description jQuery plugin
         * @param  {Object} options you can override all methods and messages
         * @return this
         */
        formValidate: function(options, hiddenCheckFlag){
            var self = this,
                inputResult,
                formResult = {
                    error: false,
                    results: []
                },
                checkSelector = '[data-role*="validation"]';

            if(!hiddenCheckFlag) checkSelector += ':visible';

            $(checkSelector, self).each(function(){
                var input = $(this).validate(options);
                inputResult = input.execute().getError();

                if(inputResult.error){
                    formResult.error = true;
                    formResult.results.push({
                        element: input,
                        message: inputResult.errorMessage,
                        type:    inputResult.errorType
                    });
                }
                return true;
            });

            self.getResult = function(){
                return formResult;
            };

            return self;
        },
        /**
         * @method set and validate
         * @description jQuery plugin
         * @param  {Object} options you can override all methods and messages
         * @return this
         */
        validate: function(options){
            var self = this,
                p,
                defaults = {
                    /**
                     * @type Object
                     * @description check method name
                     */
                    'checks': {
                        'required':   {
                            check:   'chkRequired',
                            handler: ['blur', 'keydown', 'paste', 'cut']
                        },
                        'required-check':   {
                            check:   'chkRequiredCheck',
                            handler: ['blur']
                        },
                        'max-length': {
                            check:   'chkMaxLength',
                            handler: ['blur', 'keydown', 'paste', 'cut']
                        },
                        'min-length': {
                            check:   'chkMinLength',
                            handler: ['blur']
                        },
                        'max-num':    {
                            check:   'chkMaxNum',
                            handler: ['blur', 'keydown', 'paste', 'cut']
                        },
                        'min-num':    {
                            check:   'chkMinNum',
                            handler: ['blur', 'keydown', 'paste', 'cut']
                        },
                        'format':     {
                            check:   'chkFormat',
                            handler: ['blur', 'keydown', 'paste', 'cut']
                        },
                        'regexp':     {
                            check:   'chkRegexp',
                            handler: ['blur', 'keydown', 'paste', 'cut']
                        }
                    },
                    /**
                     * @type Object
                     * @description format check RegExp Object
                     */
                    'format': {
                        'number':    /^[0-9]*$/,
                        'half-char': /^[0-9A-Za-z]*$/,
                        'half':      /^[\x20-\x7e]*$/,
                        'half-kana': /^[ヲ-ン]*$/,
                        'url':       /^[0-9A-Za-z-_.!~*'()]*$%/,
                        'mail':      /^(?:(?:(?:(?:[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+)(?:\.(?:[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+))*)|(?:"(?:\\[^\r\n]|[^\\"])*")))\@(?:(?:(?:(?:[a-zA-Z0-9_!#\$\%&'*+/=?\^`{}~|\-]+)(?:\.(?:[a-zA-Z0-9_!#\$\%&''*+/=?\^`{}~|\-]+))*)|(?:\[(?:\\\S|[\x21-\x5a\x5e-\x7e])*\])))$/,
                        'all-kana':  /^[ァ-ヶ]*$/,
                        'all-char':  /^[^\x20-\x7eア-ン゙゚ァ-ォャ-ョー]*$/
                    },
                    /**
                     * @type Object
                     * @description Messages
                     */
                    'MESSAGES': {
                        'REQUIRED':       '{title}を入力してください。',
                        'REQUIRED-CHECK': '{title}を選択してください。',
                        'MAX-LENGTH':     '{title}は{length}文字以下で入力してください。',
                        'MIN-LENGTH':     '{title}は{length}文字以上で入力してください。',
                        'MAX-NUM':        '{num}以内の数値を入力してください。',
                        'MIN-NUM':        '{num}以上の数値を入力してください。',
                        'REGEXP':         '不正な文字が含まれています。',
                        'FORMAT':         {
                            'NUMBER':    '{title}は半角数字を入力してください。',
                            'HALF-CHAR': '{title}は半角英数字で入力してください。',
                            'HALF':      '{title}は半角で入力してください。',
                            'HALF-KANA': '{title}は半角カナで入力してください。',
                            'URL':       '{title}は有効なURLを入力してください。',
                            'MAIL':      '{title}は有効なメールアドレスを入力してください。',
                            'ALL-KANA':  '{title}は全角カナで入力してください。',
                            'ALL-CHAR':  '{title}は全角で入力してください。'
                        }
                    },
                    /**
                     * @method Check required
                     * @description Check input something or not
                     * @param {Boolean} required flag
                     * @param {String} validation target
                     * @return this
                     */
                    'chkRequired': function(required, value){
                        if(required && !value){
                            self.error = true;
                            self.itemError = true;
                            self.errorMessage = options.MESSAGES['REQUIRED'];
                        }
                        return self;
                    },
                    /**
                     * @method Check required(radio and checkbox and select)
                     * @description Check select something or not
                     * @param {Boolean} required flag
                     * @param {String} validation target
                     * @return this
                     */
                    'chkRequiredCheck': function(required, value){
                        var type = self.attr('type'),
                            name = self.attr('name'),
                            errorFlag = false;
                        if(required){
                            if(type === 'radio' || type === 'checkbox'){
                                errorFlag = !$('input[name="'+ name +'"]:checked').size();
                            }else{
                                errorFlag = !value;
                            }
                            if(errorFlag){
                                self.error = true;
                                self.itemError = true;
                                self.errorMessage = options.MESSAGES['REQUIRED-CHECK'];
                            }
                        }
                        return self;
                    },
                    /**
                     * @method Check string length
                     * @description Check value length
                     * @param {Number} Max length
                     * @param {String} validation target
                     * @return this
                     */
                    'chkMaxLength': function(length, value){
                        if(length < value.length){
                            self.error = true;
                            self.itemError = true;
                            self.errorMessage = options.MESSAGES['MAX-LENGTH'].replace(/{length}/g, length);
                        }
                        return self;
                    },
                    /**
                     * @method Check string length
                     * @description Check value length
                     * @param {Number} Min length
                     * @param {String} validation target
                     * @return this
                     */
                    'chkMinLength': function(length, value){
                        if(value.length < length){
                            self.error = true;
                            self.itemError = true;
                            self.errorMessage = options.MESSAGES['MIN-LENGTH'].replace(/{length}/g, length);
                        }
                        return self;
                    },
                    /**
                     * @method Check number
                     * @description Check value number
                     * @param {Number} Max nuber
                     * @param {Number} validation target
                     * @return this
                     */
                    'chkMaxNum': function(num, value){
                        num = parseInt(num, 10);
                        value = parseInt(value, 10);
                        if(num < value){
                            self.error = true;
                            self.itemError = true;
                            self.errorMessage = options.MESSAGES['MAX-NUM'].replace(/{num}/g, num);
                        }
                        return self;
                    },
                    /**
                     * @method Check number
                     * @description Check value number
                     * @param {Number} Min nuber
                     * @param {Number} validation target
                     * @return this
                     */
                    'chkMinNum': function(num, value){
                        num = parseInt(num, 10);
                        value = parseInt(value, 10);
                        if(value < num){
                            self.error = true;
                            self.itemError = true;
                            self.errorMessage = options.MESSAGES['MIN-NUM'].replace(/{num}/g, num);
                        }
                        return self;
                    },
                    /**
                     * @method Check string format
                     * @description Check format by regType
                     * @param {String} RegExp type
                     * @param {String} validation target
                     * @return this
                     */
                    'chkFormat': function(regType, value){
                        if(regType === 'url') value = encodeURIComponent(value);
                        if(!value.match(options.format[regType]) && value){
                            self.error = true;
                            self.itemError = true;
                            self.errorMessage = options.MESSAGES['FORMAT'][regType.toUpperCase()];
                        }
                        return self;
                    },
                    /**
                     * @method Check string regexp
                     * @description Check regexp
                     * @param {Object} RegExp object
                     * @param {String} validation target
                     * @return this
                     */
                    'chkRegexp': function(reg, value){
                        if(value.match(reg)){
                            self.error = true;
                            self.itemError = true;
                            self.errorMessage = options.MESSAGES['REGEXP'];
                        }
                        return self;
                    },
                    /**
                     * @method Execute validation
                     * @description Execute validation
                     * @return this
                     */
                    'execute': function(e){
                        var p,
                            value,
                            param,
                            checks;

                        self.itemError = false;
                        for(p in options.checks){
                            param = self.data(p);
                            if(param && !self.itemError){
                                checks = options.checks[p];
                                if(e && $.inArray(e.type, checks.handler) === -1) continue;
                                value = $.trim(self.val());
                                self[checks.check](param, value);
                                self.errorType = p;
                                self.errorMessage = self.errorMessage && self.errorMessage.replace(/\{title\}/g, self.data('title'));
                                self.trigger('inputcheck', {
                                    error: self.itemError,
                                    errorType: p,
                                    errorMessage: self.errorMessage
                                });

                            }
                        }
                        return self;
                    },
                    /**
                     * @method Get error flag
                     * @description return error flag
                     * @return this
                     */
                    'getError': function(){
                        return {
                            error:        self.error,
                            errorMessage: self.errorMessage,
                            errorType:    self.errorType
                        };
                    },
                    /**
                     * @method Set validation
                     * @description set realtime validation to textbox
                     * @return this
                     */
                    'setValidation': function(){
                        self.on({
                            'blur':    self.execute,
                            'keydown': function(e){
                                if(e.keyCode === 9 || ((e.ctrlKey || e.metaKey) && (e.keyCode === 86 || e.keyCode === 88))) return true;
                                setTimeout(function(){self.execute(e);}, 0);
                            },
                            'paste':   function(e){
                                setTimeout(function(){self.execute(e);}, 0);
                            },
                            'cut':     function(e){
                                setTimeout(function(){self.execute(e);}, 0);
                            }
                        });
                        return self;
                    }

                };

            /** extend defaults object */
            options = (function(defaults, options){
                return cpObj();
                function cpObj(){
                    for(p in defaults){
                        if(!options[p]) options[p] = {};
                        switch(typeof defaults[p]){
                            case 'object':
                                cpObj(defaults[p], options[p]);
                                break;
                            default:
                                options[p] = defaults[p];
                                break;
                        }
                    }
                    return options;
                }
            })(options, defaults);

            for(p in options.checks){
                self[options.checks[p].check] = options[options.checks[p].check];
            }

            self.error = false;
            self.errorType;
            self.itemError = false;
            self.errorMessage;
            self.MESSAGES = options.MESSAGES;

            self.execute = options.execute;

            self.getError = options.getError;

            self.setValidation = options.setValidation;

            return self;
        }
    });
}.call(window, jQuery);


text:
using Selenium;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace Selenium.ComInterfaces {
#pragma warning disable 1591

    [Guid("0277FC34-FD1B-4616-BB19-FBDA3A91C82B")]
    [ComVisible(true), InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface _Window {

        [DispId(500), Description("Set the context to this window.")]
        Window Activate();

        [DispId(533), Description("Gets the size of the outer browser window")]
        Size Size();

        [DispId(536), Description("Switch to the window with the provided name")]
        Window SwitchToWindowByName(string name, int timeout = -1);

        [DispId(537), Description("Switch to the window with the provided title")]
        Window SwitchToWindowByTitle(string title, int timeout = -1);

        [DispId(538), Description("Switch to the next window")]
        Window SwitchToNextWindow(int timeout = -1);

        [DispId(540), Description("Switch to the previous window")]
        Window SwitchToPreviousWindow();

        [DispId(544), Description("Sets the size of the outer browser window, including title bars and window borders.")]
        void SetSize(int width, int height);

        [DispId(550), Description("Get the title of the window")]
        string Title { get; }

        [DispId(554), Description("Gets the position of the browser window relative to the upper-left corner of the screen.")]
        Point Position();

        [DispId(557), Description("Sets the position of the browser window relative to the upper-left corner of the screen.")]
        void SetPosition(int x, int y);

        [DispId(562), Description("Maximizes the current window if it is not already maximized")]
        void Maximize();

        [DispId(567), Description("Set the current window full screen")]
        void FullScreen();

        [DispId(574), Description("Closes the current window")]
        void Close();

        [DispId(899), Description("Evaluate equality")]
        bool Equals(object obj);

    }

}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const gravatar = require('gravatar');

const generateGravatar = function (email, size, context) {
  const options = {};
  if (context) {
    options.s = size;
  } else {
    context = size;
  }

  return gravatar.url(email, options);
};

module.exports = generateGravatar;


text:
@extends ('layouts.default')
@section ('title', 'Reset Password')

@section ('content')

Reset Password

                    <form method="POST" action="{{ route('password.request') }}">
                        @csrf

                        <input type="hidden" name="token" value="{{ $token }}">

has('email') ? ' has-error' : '' }} row">
                            E-Mail Address

                                <input id="email" type="email" class="form-control" name="email" value="{{ $email or old('email') }}" required autofocus>

                                @if ($errors->has('email'))

                                        {{ $errors->first('email') }}

                                @endif

has('password') ? ' has-error' : '' }} row">
                            Password

                                <input id="password" type="password" class="form-control" name="password" required>

                                @if ($errors->has('password'))

                                        {{ $errors->first('password') }}

                                @endif

has('password_confirmation') ? ' has-error' : '' }} row">
                            Confirm Password

                                <input id="password-confirm" type="password" class="form-control" name="password_confirmation" required>

                                @if ($errors->has('password_confirmation'))

                                        {{ $errors->first('password_confirmation') }}

                                @endif

                                <button type="submit" class="btn btn-primary">
                                    Reset Password
                                </button>

                    </form>

@endsection


text:
package org.wso2.carbon.bpel.ui.bpel2svg;

public interface CompensateScopeInterface extends ActivityInterface {

}


text:
package com.azure.resourcemanager.compute;

import com.azure.core.credential.TokenCredential;
import com.azure.core.http.HttpClient;
import com.azure.core.http.HttpMethod;
import com.azure.core.http.HttpRequest;
import com.azure.core.http.HttpResponse;
import com.azure.core.management.AzureEnvironment;
import com.azure.core.management.profile.AzureProfile;
import com.azure.core.util.serializer.JacksonAdapter;
import com.azure.core.util.serializer.SerializerEncoding;
import com.azure.identity.DefaultAzureCredentialBuilder;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;

import java.io.IOException;
import java.util.HashMap;

public class ReadmeSamples {

    public void authenticate() {
        // BEGIN: com.azure.resourcemanager.compute.authenticate
        String armEndpoint = "https://management.<region>.<your-domain>";
        AzureProfile profile = new AzureProfile(getAzureEnvironmentFromArmEndpoint(armEndpoint));
        TokenCredential credential = new DefaultAzureCredentialBuilder()
            .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
            .build();
        ComputeManager manager = ComputeManager
            .authenticate(credential, profile);
        // END: com.azure.resourcemanager.compute.authenticate
    }

    // BEGIN: com.azure.resourcemanager.compute.getazureenvironment
    private static AzureEnvironment getAzureEnvironmentFromArmEndpoint(String armEndpoint) {
        // Create HTTP client and request
        HttpClient httpClient = HttpClient.createDefault();

        HttpRequest request = new HttpRequest(HttpMethod.GET,
                String.format("%s/metadata/endpoints?api-version=2019-10-01", armEndpoint))
                .setHeader("accept", "application/json");

        // Execute the request and read the response
        HttpResponse response = httpClient.send(request).block();
        if (response.getStatusCode() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatusCode());
        }
        String body = response.getBodyAsString().block();
        try {
            ArrayNode metadataArray = JacksonAdapter.createDefaultSerializerAdapter()
                    .deserialize(body, ArrayNode.class, SerializerEncoding.JSON);

            if (metadataArray == null || metadataArray.isEmpty()) {
                throw new RuntimeException("Failed to find metadata : " + body);
            }

            JsonNode metadata = metadataArray.iterator().next();
            AzureEnvironment azureEnvironment = new AzureEnvironment(new HashMap<String, String>() {
                {
                    put("managementEndpointUrl", metadata.at("/authentication/audiences/0").asText());
                    put("resourceManagerEndpointUrl", armEndpoint);
                    put("galleryEndpointUrl", metadata.at("/gallery").asText());
                    put("activeDirectoryEndpointUrl", metadata.at("/authentication/loginEndpoint").asText());
                    put("activeDirectoryResourceId", metadata.at("/authentication/audiences/0").asText());
                    put("activeDirectoryGraphResourceId", metadata.at("/graph").asText());
                    put("storageEndpointSuffix", "." + metadata.at("/suffixes/storage").asText());
                    put("keyVaultDnsSuffix", "." + metadata.at("/suffixes/keyVaultDns").asText());
                }
            });
            return azureEnvironment;
        } catch (IOException ioe) {
            ioe.printStackTrace();
            throw new RuntimeException(ioe);
        }
    }
    // END: com.azure.resourcemanager.compute.getazureenvironment
}


text:
SYNONYM

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

#### Published in
Nouv. Mem. Soc. Imp. nat. Moscou 15: 302 (1898)

#### Original name
Sphaeria helvellae P. Karst., 1867

### Remarks
null


text:
// Code generated by client-gen. DO NOT EDIT.

package internalversion

import (
	servicecatalog "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog"
	scheme "github.com/kubernetes-incubator/service-catalog/pkg/client/clientset_generated/internalclientset/scheme"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	types "k8s.io/apimachinery/pkg/types"
	watch "k8s.io/apimachinery/pkg/watch"
	rest "k8s.io/client-go/rest"
)

// ServicePlansGetter has a method to return a ServicePlanInterface.
// A group's client should implement this interface.
type ServicePlansGetter interface {
	ServicePlans(namespace string) ServicePlanInterface
}

// ServicePlanInterface has methods to work with ServicePlan resources.
type ServicePlanInterface interface {
	Create(*servicecatalog.ServicePlan) (*servicecatalog.ServicePlan, error)
	Update(*servicecatalog.ServicePlan) (*servicecatalog.ServicePlan, error)
	UpdateStatus(*servicecatalog.ServicePlan) (*servicecatalog.ServicePlan, error)
	Delete(name string, options *v1.DeleteOptions) error
	DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error
	Get(name string, options v1.GetOptions) (*servicecatalog.ServicePlan, error)
	List(opts v1.ListOptions) (*servicecatalog.ServicePlanList, error)
	Watch(opts v1.ListOptions) (watch.Interface, error)
	Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *servicecatalog.ServicePlan, err error)
	ServicePlanExpansion
}

// servicePlans implements ServicePlanInterface
type servicePlans struct {
	client rest.Interface
	ns     string
}

// newServicePlans returns a ServicePlans
func newServicePlans(c *ServicecatalogClient, namespace string) *servicePlans {
	return &servicePlans{
		client: c.RESTClient(),
		ns:     namespace,
	}
}

// Get takes name of the servicePlan, and returns the corresponding servicePlan object, and an error if there is any.
func (c *servicePlans) Get(name string, options v1.GetOptions) (result *servicecatalog.ServicePlan, err error) {
	result = &servicecatalog.ServicePlan{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("serviceplans").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}

// List takes label and field selectors, and returns the list of ServicePlans that match those selectors.
func (c *servicePlans) List(opts v1.ListOptions) (result *servicecatalog.ServicePlanList, err error) {
	result = &servicecatalog.ServicePlanList{}
	err = c.client.Get().
		Namespace(c.ns).
		Resource("serviceplans").
		VersionedParams(&opts, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}

// Watch returns a watch.Interface that watches the requested servicePlans.
func (c *servicePlans) Watch(opts v1.ListOptions) (watch.Interface, error) {
	opts.Watch = true
	return c.client.Get().
		Namespace(c.ns).
		Resource("serviceplans").
		VersionedParams(&opts, scheme.ParameterCodec).
		Watch()
}

// Create takes the representation of a servicePlan and creates it.  Returns the server's representation of the servicePlan, and an error, if there is any.
func (c *servicePlans) Create(servicePlan *servicecatalog.ServicePlan) (result *servicecatalog.ServicePlan, err error) {
	result = &servicecatalog.ServicePlan{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("serviceplans").
		Body(servicePlan).
		Do().
		Into(result)
	return
}

// Update takes the representation of a servicePlan and updates it. Returns the server's representation of the servicePlan, and an error, if there is any.
func (c *servicePlans) Update(servicePlan *servicecatalog.ServicePlan) (result *servicecatalog.ServicePlan, err error) {
	result = &servicecatalog.ServicePlan{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("serviceplans").
		Name(servicePlan.Name).
		Body(servicePlan).
		Do().
		Into(result)
	return
}

// UpdateStatus was generated because the type contains a Status member.
// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus().

func (c *servicePlans) UpdateStatus(servicePlan *servicecatalog.ServicePlan) (result *servicecatalog.ServicePlan, err error) {
	result = &servicecatalog.ServicePlan{}
	err = c.client.Put().
		Namespace(c.ns).
		Resource("serviceplans").
		Name(servicePlan.Name).
		SubResource("status").
		Body(servicePlan).
		Do().
		Into(result)
	return
}

// Delete takes name of the servicePlan and deletes it. Returns an error if one occurs.
func (c *servicePlans) Delete(name string, options *v1.DeleteOptions) error {
	return c.client.Delete().
		Namespace(c.ns).
		Resource("serviceplans").
		Name(name).
		Body(options).
		Do().
		Error()
}

// DeleteCollection deletes a collection of objects.
func (c *servicePlans) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error {
	return c.client.Delete().
		Namespace(c.ns).
		Resource("serviceplans").
		VersionedParams(&listOptions, scheme.ParameterCodec).
		Body(options).
		Do().
		Error()
}

// Patch applies the patch and returns the patched servicePlan.
func (c *servicePlans) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *servicecatalog.ServicePlan, err error) {
	result = &servicecatalog.ServicePlan{}
	err = c.client.Patch(pt).
		Namespace(c.ns).
		Resource("serviceplans").
		SubResource(subresources...).
		Name(name).
		Body(data).
		Do().
		Into(result)
	return
}


text:
mackerel-plugin-nginx
=====================

Nginx custom metrics plugin for mackerel.io agent.

## Synopsis

```shell
mackerel-plugin-nginx [-scheme=<'http'|'https'>] [-host=<host>] [-port=<port>] [-path=<path>] [-tempfile=<tempfile>]
```

## Requirements

- [ngx_http_stub_status_module](http://nginx.org/en/docs/http/ngx_http_stub_status_module.html)

## Example of mackerel-agent.conf

```
[plugin.metrics.nginx]
command = "/path/to/mackerel-plugin-nginx"
```


text:
"""Base class for linear operators."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import contextlib

from tensorflow.contrib import framework as contrib_framework
from tensorflow.contrib.linalg.python.ops import linear_operator_util
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import linalg_ops

__all__ = ["LinearOperator"]

# TODO(langmore) Use matrix_solve_ls for singular or non-square matrices.
# TODO(langmore) Add adjoint_x arg to apply, solve.
class LinearOperator(object):
  """Base class defining a [batch of] linear operator[s].

  Subclasses of `LinearOperator` provide a access to common methods on a
  (batch) matrix, without the need to materialize the matrix.  This allows:

  * Matrix free computations
  * Operators that take advantage of special structure, while providing a
    consistent API to users.

  #### Subclassing

  To enable a public method, subclasses should implement the leading-underscore
  version of the method.  The argument signature should be identical except for
  the omission of `name="..."`.  For example, to enable
  `apply(x, adjoint=False, name="apply")` a subclass should implement
  `_apply(x, adjoint=False)`.

  #### Performance contract

  Subclasses should implement a method only if it can be done with a reasonable
  performance increase over generic dense operations, either in time, parallel
  scalability, or memory usage.  For example, if the determinant can only be
  computed using `tf.matrix_determinant(self.to_dense())`, then determinants
  should not be implemented.

  Class docstrings should contain an explanation of computational complexity.
  Since this is a high-performance library, attention should be paid to detail,
  and explanations can include constants as well as Big-O notation.

  #### Shape compatibility

  `LinearOperator` sub classes should operate on a [batch] matrix with
  compatible shape.  Class docstrings should define what is meant by compatible
  shape.  Some sub-classes may not support batching.

  An example is:

  `x` is a batch matrix with compatible shape for `apply` if

  ```
  operator.shape = [B1,...,Bb] + [M, N],  b >= 0,
  x.shape =   [B1,...,Bb] + [N, R]
  ```

  `rhs` is a batch matrix with compatible shape for `solve` if

  ```
  operator.shape = [B1,...,Bb] + [M, N],  b >= 0,
  rhs.shape =   [B1,...,Bb] + [M, R]
  ```

  #### Example docstring for subclasses.

  This operator acts like a (batch) matrix `A` with shape
  `[B1,...,Bb, M, N]` for some `b >= 0`.  The first `b` indices index a
  batch member.  For every batch index `(i1,...,ib)`, `A[i1,...,ib, : :]` is
  an `m x n` matrix.  Again, this matrix `A` may not be materialized, but for
  purposes of identifying and working with compatible arguments the shape is
  relevant.

  Examples:

  ```python
  some_tensor = ... shape = ????
  operator = MyLinOp(some_tensor)

  operator.shape()
  ==> [2, 4, 4]

  operator.log_determinant()
  ==> Shape [2] Tensor

  x = ... Shape [2, 4, 5] Tensor

  operator.apply(x)
  ==> Shape [2, 4, 5] Tensor
  ```

  #### Shape compatibility

  This operator acts on batch matrices with compatible shape.
  FILL IN WHAT IS MEANT BY COMPATIBLE SHAPE

  #### Performance

  FILL THIS IN

  #### Matrix property hints

  This `LinearOperator` is initialized with boolean flags of the form `is_X`,
  for `X = non_singular, self_adjoint, positive_definite, square`.
  These have the following meaning
  * If `is_X == True`, callers should expect the operator to have the
    property `X`.  This is a promise that should be fulfilled, but is *not* a
    runtime assert.  For example, finite floating point precision may result
    in these promises being violated.
  * If `is_X == False`, callers should expect the operator to not have `X`.
  * If `is_X == None` (the default), callers should have no expectation either
    way.
  """

  def __init__(self,
               dtype,
               graph_parents=None,
               is_non_singular=None,
               is_self_adjoint=None,
               is_positive_definite=None,
               is_square=None,
               name=None):
    r"""Initialize the `LinearOperator`.

    **This is a private method for subclass use.**
    **Subclasses should copy-paste this `__init__` documentation.**

    Args:
      dtype: The type of the this `LinearOperator`.  Arguments to `apply` and
        `solve` will have to be this type.
      graph_parents: Python list of graph prerequisites of this `LinearOperator`
        Typically tensors that are passed during initialization.
      is_non_singular:  Expect that this operator is non-singular.
      is_self_adjoint:  Expect that this operator is equal to its hermitian
        transpose.  If `dtype` is real, this is equivalent to being symmetric.
      is_positive_definite:  Expect that this operator is positive definite,
        meaning the quadratic form `x^H A x` has positive real part for all
        nonzero `x`.  Note that we do not require the operator to be
        self-adjoint to be positive-definite.  See:
        https://en.wikipedia.org/wiki/Positive-definite_matrix\
            #Extension_for_non_symmetric_matrices
      is_square:  Expect that this operator acts like square [batch] matrices.
      name: A name for this `LinearOperator`.

    Raises:
      ValueError:  If any member of graph_parents is `None` or not a `Tensor`.
      ValueError:  If hints are set incorrectly.
    """
    # Check and auto-set flags.
    if is_square is False:
      if is_non_singular or is_positive_definite:
        raise ValueError(
            "A non-singular or positive definite operator is always square.")
    self._is_square_set_by_user = is_square

    if is_positive_definite:
      if is_non_singular is False:
        raise ValueError("A positive definite matrix is always non-singular.")
      is_non_singular = True

    graph_parents = [] if graph_parents is None else graph_parents
    for i, t in enumerate(graph_parents):
      if t is None or not contrib_framework.is_tensor(t):
        raise ValueError("Graph parent item %d is not a Tensor; %s." % (i, t))
    self._dtype = dtype
    self._graph_parents = graph_parents
    self._is_non_singular = is_non_singular
    self._is_self_adjoint = is_self_adjoint
    self._is_positive_definite = is_positive_definite
    self._name = name or type(self).__name__

    # We will cache some tensors to avoid repeatedly adding shape
    # manipulation ops to the graph.
    # Naming convention:
    #   self._cached_X_tensor is the cached version of self._X_tensor.
    self._cached_shape_tensor = None
    self._cached_batch_shape_tensor = None
    self._cached_domain_dimension_tensor = None
    self._cached_range_dimension_tensor = None
    self._cached_tensor_rank_tensor = None

  @contextlib.contextmanager
  def _name_scope(self, name=None, values=None):
    """Helper function to standardize op scope."""
    with ops.name_scope(self.name):
      with ops.name_scope(
          name, values=((values or []) + self._graph_parents)) as scope:
        yield scope

  @property
  def dtype(self):
    """The `DType` of `Tensor`s handled by this `LinearOperator`."""
    return self._dtype

  @property
  def name(self):
    """Name prepended to all ops created by this `LinearOperator`."""
    return self._name

  @property
  def graph_parents(self):
    """List of graph dependencies of this `LinearOperator`."""
    return self._graph_parents

  @property
  def is_non_singular(self):
    return self._is_non_singular

  @property
  def is_self_adjoint(self):
    return self._is_self_adjoint

  @property
  def is_positive_definite(self):
    return self._is_positive_definite

  @property
  def is_square(self):
    """Return `True/False` depending on if this operator is square."""
    # Static checks done after __init__.  Why?  Because domain/range dimension
    # sometimes requires lots of work done in the derived class after init.
    static_square_check = self.domain_dimension == self.range_dimension
    if self._is_square_set_by_user is False and static_square_check:
      raise ValueError(
          "User set is_square hint to False, but the operator was square.")
    if self._is_square_set_by_user is None:
      return static_square_check

    return self._is_square_set_by_user

  def _shape(self):
    # Write this in derived class to enable all static shape methods.
    raise NotImplementedError("_shape is not implemented.")

  @property
  def shape(self):
    """`TensorShape` of this `LinearOperator`.

    If this operator acts like the batch matrix `A` with
    `A.shape = [B1,...,Bb, M, N]`, then this returns
    `TensorShape([B1,...,Bb, M, N])`, equivalent to `A.get_shape()`.

    Returns:
      `TensorShape`, statically determined, may be undefined.
    """
    return self._shape()

  def _shape_tensor(self):
    raise NotImplementedError("_shape_tensor is not implemented.")

  def shape_tensor(self, name="shape_tensor"):
    """Shape of this `LinearOperator`, determined at runtime.

    If this operator acts like the batch matrix `A` with
    `A.shape = [B1,...,Bb, M, N]`, then this returns a `Tensor` holding
    `[B1,...,Bb, M, N]`, equivalent to `tf.shape(A)`.

    Args:
      name:  A name for this `Op.

    Returns:
      `int32` `Tensor`
    """
    with self._name_scope(name):
      # Be clean by avoiding adding shape Ops to the graph too many times.
      if self._cached_shape_tensor is None:
        # Prefer to use statically defined shape if available.
        if self.shape.is_fully_defined():
          self._cached_shape_tensor = linear_operator_util.shape_tensor(
              self.shape.as_list())
        else:
          self._cached_shape_tensor = self._shape_tensor()
      return self._cached_shape_tensor

  @property
  def batch_shape(self):
    """`TensorShape` of batch dimensions of this `LinearOperator`.

    If this operator acts like the batch matrix `A` with
    `A.shape = [B1,...,Bb, M, N]`, then this returns
    `TensorShape([B1,...,Bb])`, equivalent to `A.get_shape()[:-2]`

    Returns:
      `TensorShape`, statically determined, may be undefined.
    """
    # Derived classes get this "for free" once .shape is implemented.
    return self.shape[:-2]

  def batch_shape_tensor(self, name="batch_shape_tensor"):
    """Shape of batch dimensions of this operator, determined at runtime.

    If this operator acts like the batch matrix `A` with
    `A.shape = [B1,...,Bb, M, N]`, then this returns a `Tensor` holding
    `[B1,...,Bb]`.

    Args:
      name:  A name for this `Op.

    Returns:
      `int32` `Tensor`
    """
    # Derived classes get this "for free" once .shape() is implemented.
    with self._name_scope(name):
      if self._cached_batch_shape_tensor is None:
        # Prefer to use statically defined shape if available.
        if self.batch_shape.is_fully_defined():
          self._cached_batch_shape_tensor = linear_operator_util.shape_tensor(
              self.batch_shape.as_list(), name="batch_shape")
        else:
          self._cached_batch_shape_tensor = self.shape_tensor()[:-2]
      return self._cached_batch_shape_tensor

  @property
  def tensor_rank(self, name="tensor_rank"):
    """Rank (in the sense of tensors) of matrix corresponding to this operator.

    If this operator acts like the batch matrix `A` with
    `A.shape = [B1,...,Bb, M, N]`, then this returns `b + 2`.

    Args:
      name:  A name for this `Op.

    Returns:
      Python integer, or None if the tensor rank is undefined.
    """
    # Derived classes get this "for free" once .shape() is implemented.
    with self._name_scope(name):
      return self.shape.ndims

  def tensor_rank_tensor(self, name="tensor_rank_tensor"):
    """Rank (in the sense of tensors) of matrix corresponding to this operator.

    If this operator acts like the batch matrix `A` with
    `A.shape = [B1,...,Bb, M, N]`, then this returns `b + 2`.

    Args:
      name:  A name for this `Op.

    Returns:
      `int32` `Tensor`, determined at runtime.
    """
    # Derived classes get this "for free" once .shape() is implemented.
    with self._name_scope(name):
      if self._cached_tensor_rank_tensor is None:
        # Prefer to use statically defined shape if available.
        if self.tensor_rank is not None:
          self._cached_tensor_rank_tensor = ops.convert_to_tensor(
              self.tensor_rank)
        else:
          self._cached_tensor_rank_tensor = array_ops.size(
              self.shape_tensor())
      return self._cached_tensor_rank_tensor

  @property
  def domain_dimension(self):
    """Dimension (in the sense of vector spaces) of the domain of this operator.

    If this operator acts like the batch matrix `A` with
    `A.shape = [B1,...,Bb, M, N]`, then this returns `N`.

    Returns:
      `Dimension` object.
    """
    # Derived classes get this "for free" once .shape is implemented.
    return self.shape[-1]

  def domain_dimension_tensor(self, name="domain_dimension_tensor"):
    """Dimension (in the sense of vector spaces) of the domain of this operator.

    Determined at runtime.

    If this operator acts like the batch matrix `A` with
    `A.shape = [B1,...,Bb, M, N]`, then this returns `N`.

    Args:
      name:  A name for this `Op`.

    Returns:
      `int32` `Tensor`
    """
    # Derived classes get this "for free" once .shape() is implemented.
    with self._name_scope(name):
      if self._cached_domain_dimension_tensor is None:
        # Prefer to use statically defined shape if available.
        if self.domain_dimension.value is not None:
          self._cached_domain_dimension_tensor = ops.convert_to_tensor(
              self.domain_dimension.value)
        else:
          self._cached_domain_dimension_tensor = self.shape_tensor()[-1]
      return self._cached_domain_dimension_tensor

  @property
  def range_dimension(self):
    """Dimension (in the sense of vector spaces) of the range of this operator.

    If this operator acts like the batch matrix `A` with
    `A.shape = [B1,...,Bb, M, N]`, then this returns `M`.

    Returns:
      `Dimension` object.
    """
    # Derived classes get this "for free" once .shape is implemented.
    return self.shape[-2]

  def range_dimension_tensor(self, name="range_dimension_tensor"):
    """Dimension (in the sense of vector spaces) of the range of this operator.

    Determined at runtime.

    If this operator acts like the batch matrix `A` with
    `A.shape = [B1,...,Bb, M, N]`, then this returns `M`.

    Args:
      name:  A name for this `Op`.

    Returns:
      `int32` `Tensor`
    """
    # Derived classes get this "for free" once .shape() is implemented.
    with self._name_scope(name):
      if self._cached_range_dimension_tensor is None:
        # Prefer to use statically defined shape if available.
        if self.range_dimension.value is not None:
          self._cached_range_dimension_tensor = ops.convert_to_tensor(
              self.range_dimension.value)
        else:
          self._cached_range_dimension_tensor = self.shape_tensor()[-2]
      return self._cached_range_dimension_tensor

  def _assert_non_singular(self):
    raise NotImplementedError("assert_non_singular is not implemented.")

  def assert_non_singular(self, name="assert_non_singular"):
    """Returns an `Op` that asserts this operator is non singular."""
    with self._name_scope(name):
      return self._assert_non_singular()

  def _assert_positive_definite(self):
    raise NotImplementedError("assert_positive_definite is not implemented.")

  def assert_positive_definite(self, name="assert_positive_definite"):
    """Returns an `Op` that asserts this operator is positive definite.

    Here, positive definite means that the quadratic form `x^H A x` has positive
    real part for all nonzero `x`.  Note that we do not require the operator to
    be self-adjoint to be positive definite.

    Args:
      name:  A name to give this `Op`.

    Returns:
      An `Op` that asserts this operator is positive definite.
    """
    with self._name_scope(name):
      return self._assert_positive_definite()

  def _assert_self_adjoint(self):
    raise NotImplementedError("assert_self_adjoint is not implemented.")

  def assert_self_adjoint(self, name="assert_self_adjoint"):
    """Returns an `Op` that asserts this operator is self-adjoint."""
    with self._name_scope(name):
      return self._assert_self_adjoint()

  def _check_input_dtype(self, arg):
    """Check that arg.dtype == self.dtype."""
    if arg.dtype != self.dtype:
      raise TypeError(
          "Expected argument to have dtype %s.  Found: %s in tensor %s"
          % (self.dtype, arg.dtype, arg))

  def _apply(self, x, adjoint=False):
    raise NotImplementedError("_apply is not implemented.")

  def apply(self, x, adjoint=False, name="apply"):
    """Transform `x` with left multiplication:  `x --> Ax`.

    Args:
      x: `Tensor` with compatible shape and same `dtype` as `self`.
        See class docstring for definition of compatibility.
      adjoint: Python `bool`.  If `True`, left multiply by the adjoint.
      name:  A name for this `Op.

    Returns:
      A `Tensor` with shape `[..., M, R]` and same `dtype` as `self`.
    """
    with self._name_scope(name, values=[x]):
      x = ops.convert_to_tensor(x, name="x")
      self._check_input_dtype(x)
      if adjoint:
        self.shape[-2].assert_is_compatible_with(x.get_shape()[-2])
      else:
        self.shape[-1].assert_is_compatible_with(x.get_shape()[-2])
      return self._apply(x, adjoint=adjoint)

  def _determinant(self):
    raise NotImplementedError("_det is not implemented.")

  def determinant(self, name="det"):
    """Determinant for every batch member.

    Args:
      name:  A name for this `Op.

    Returns:
      `Tensor` with shape `self.batch_shape` and same `dtype` as `self`.

    Raises:
      NotImplementedError:  If `self.is_square` is `False`.
    """
    if self.is_square is False:
      raise NotImplementedError(
          "Determinant not implemented for an operator that is expected to "
          "not be square.")
    with self._name_scope(name):
      return self._determinant()

  def _log_abs_determinant(self):
    raise NotImplementedError("_log_abs_det is not implemented.")

  def log_abs_determinant(self, name="log_abs_det"):
    """Log absolute value of determinant for every batch member.

    Args:
      name:  A name for this `Op.

    Returns:
      `Tensor` with shape `self.batch_shape` and same `dtype` as `self`.

    Raises:
      NotImplementedError:  If `self.is_square` is `False`.
    """
    if self.is_square is False:
      raise NotImplementedError(
          "Determinant not implemented for an operator that is expected to "
          "not be square.")
    with self._name_scope(name):
      return self._log_abs_determinant()

  def _solve(self, rhs, adjoint=False):
    # Since this is an exact solve method for all rhs, this will only be
    # available for non-singular (batch) operators, in particular the operator
    # must be square.
    raise NotImplementedError("_solve is not implemented.")

  def solve(self, rhs, adjoint=False, name="solve"):
    """Solve `R` (batch) systems of equations exactly: `A X = rhs`.

    Examples:

    ```python
    # Create an operator acting like a 10 x 2 x 2 matrix.
    operator = LinearOperator(...)
    operator.shape # = 10 x 2 x 2

    # Solve one linear system (R = 1) for every member of the length 10 batch.
    RHS = ... # shape 10 x 2 x 1
    X = operator.solve(RHS)  # shape 10 x 2 x 1

    # Solve five linear systems (R = 5) for every member of the length 10 batch.
    RHS = ... # shape 10 x 2 x 5
    X = operator.solve(RHS)
    X[3, :, 2]  # Solution to the linear system A[3, :, :] X = RHS[3, :, 2]
    ```

    Args:
      rhs: `Tensor` with same `dtype` as this operator and compatible shape.
        See class docstring for definition of compatibility.
      adjoint: Python `bool`.  If `True`, solve the system involving the adjoint
        of this `LinearOperator`.
      name:  A name scope to use for ops added by this method.

    Returns:
      `Tensor` with shape `[...,N, R]` and same `dtype` as `rhs`.

    Raises:
      NotImplementedError:  If `self.is_non_singular` or `is_square` is False.
    """
    if self.is_non_singular is False:
      raise NotImplementedError(
          "Exact solve not implemented for an operator that is expected to "
          "be singular.")
    if self.is_square is False:
      raise NotImplementedError(
          "Exact solve not implemented for an operator that is expected to "
          "not be square.")
    with self._name_scope(name, values=[rhs]):
      rhs = ops.convert_to_tensor(rhs, name="rhs")
      self._check_input_dtype(rhs)
      if adjoint:
        self.shape[-1].assert_is_compatible_with(rhs.get_shape()[-2])
      else:
        self.shape[-2].assert_is_compatible_with(rhs.get_shape()[-2])
      return self._solve(rhs, adjoint=adjoint)

  def _to_dense(self):
    """Generic and often inefficient implementation.  Override often."""
    if self.batch_shape.is_fully_defined():
      batch_shape = self.batch_shape
    else:
      batch_shape = self.batch_shape_tensor()

    if self.domain_dimension.value is not None:
      n = self.domain_dimension.value
    else:
      n = self.domain_dimension_tensor()

    eye = linalg_ops.eye(num_rows=n, batch_shape=batch_shape, dtype=self.dtype)
    return self.apply(eye)

  def to_dense(self, name="to_dense"):
    """Return a dense (batch) matrix representing this operator."""
    with self._name_scope(name):
      return self._to_dense()

  def _diag_part(self):
    """Generic and often inefficient implementation.  Override often."""
    return array_ops.matrix_diag_part(self.to_dense())

  def diag_part(self, name="diag_part"):
    """Efficiently get the [batch] diagonal part of this operator.

    If this operator has shape `[B1,...,Bb, M, N]`, this returns a
    `Tensor` `diagonal`, of shape `[B1,...,Bb, min(M, N)]`, where
    `diagonal[b1,...,bb, i] = self.to_dense()[b1,...,bb, i, i]`.

    ```
    my_operator = LinearOperatorDiag([1., 2.])

    # Efficiently get the diagonal
    my_operator.diag_part()
    ==> [1., 2.]

    # Equivalent, but inefficient method
    tf.matrix_diag_part(my_operator.to_dense())
    ==> [1., 2.]
    ```

    Args:
      name:  A name for this `Op`.

    Returns:
      diag_part:  A `Tensor` of same `dtype` as self.
    """
    with self._name_scope(name):
      return self._diag_part()

  def _add_to_tensor(self, x):
    # Override if a more efficient implementation is available.
    return self.to_dense() + x

  def add_to_tensor(self, x, name="add_to_tensor"):
    """Add matrix represented by this operator to `x`.  Equivalent to `A + x`.

    Args:
      x:  `Tensor` with same `dtype` and shape broadcastable to `self.shape`.
      name:  A name to give this `Op`.

    Returns:
      A `Tensor` with broadcast shape and same `dtype` as `self`.
    """
    with self._name_scope(name, values=[x]):
      x = ops.convert_to_tensor(x, name="x")
      self._check_input_dtype(x)
      return self._add_to_tensor(x)


text:
require 'spec_helper'

# This spec is trivial, we test more complex generations in
# Via SQL::Generator::Emitter.visit
describe SQL::AST::Node, '#to_sql' do
  let(:object) { described_class.new(type, children) }

  subject { object.to_sql }

  let(:type)     { :true }
  let(:children) { []    }

  it 'returns sql representation' do
    should eql('TRUE')
  end
end


text:
package com.okwallet.util;

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

import com.okwallet_test.R;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.View;

/**
 * @author Andreas Schildbach
 */
public class ViewPagerTabs extends View implements OnPageChangeListener {
    private final List<String> labels = new ArrayList<String>();
    private final Paint paint = new Paint();
    private int maxWidth = 0;

    // instance state
    private int pagePosition = 0;
    private float pageOffset = 0;

    public ViewPagerTabs(final Context context, final AttributeSet attrs) {
        super(context, attrs);

        setSaveEnabled(true);

        paint.setTextSize(getResources().getDimension(R.dimen.font_size_tiny));
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        paint.setShadowLayer(2, 0, 0, Color.WHITE);
    }

    public void addTabLabels(final int... labelResId) {
        final Context context = getContext();

        paint.setTypeface(Typeface.DEFAULT_BOLD);

        for (final int resId : labelResId) {
            final String label = context.getString(resId);

            final int width = (int) paint.measureText(label);

            if (width > maxWidth)
                maxWidth = width;

            labels.add(label);
        }
    }

    private final Path path = new Path();

    @Override
    protected void onDraw(final Canvas canvas) {
        super.onDraw(canvas);

        final int viewWidth = getWidth();
        final int viewHalfWidth = viewWidth / 2;
        final int viewBottom = getHeight();

        final float density = getResources().getDisplayMetrics().density;
        final float spacing = 32 * density;

        path.reset();
        path.moveTo(viewHalfWidth, viewBottom - 5 * density);
        path.lineTo(viewHalfWidth + 5 * density, viewBottom);
        path.lineTo(viewHalfWidth - 5 * density, viewBottom);
        path.close();

        paint.setColor(Color.WHITE);
        canvas.drawPath(path, paint);

        paint.setTypeface(Typeface.DEFAULT_BOLD);
        final float y = getPaddingTop() + -paint.getFontMetrics().top;

        for (int i = 0; i < labels.size(); i++) {
            final String label = labels.get(i);

            paint.setTypeface(i == pagePosition ? Typeface.DEFAULT_BOLD : Typeface.DEFAULT);
            paint.setColor(i == pagePosition ? Color.BLACK : Color.DKGRAY);

            final float x = viewHalfWidth + (maxWidth + spacing) * (i - pageOffset);
            final float labelWidth = paint.measureText(label);
            final float labelHalfWidth = labelWidth / 2;

            final float labelLeft = x - labelHalfWidth;
            final float labelVisibleLeft = labelLeft >= 0 ? 1f : 1f - (-labelLeft / labelWidth);

            final float labelRight = x + labelHalfWidth;
            final float labelVisibleRight = labelRight < viewWidth ? 1f : 1f - ((labelRight - viewWidth) / labelWidth);

            final float labelVisible = Math.min(labelVisibleLeft, labelVisibleRight);

            paint.setAlpha((int) (labelVisible * 255));

            canvas.drawText(label, labelLeft, y, paint);
        }
    }

    @Override
    protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        final int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        final int width;
        if (widthMode == MeasureSpec.EXACTLY)
            width = widthSize;
        else if (widthMode == MeasureSpec.AT_MOST)
            width = Math.min(getMeasuredWidth(), widthSize);
        else
            width = 0;

        final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        final int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        final int height;
        if (heightMode == MeasureSpec.EXACTLY)
            height = heightSize;
        else if (heightMode == MeasureSpec.AT_MOST)
            height = Math.min(getSuggestedMinimumHeight(), heightSize);
        else
            height = getSuggestedMinimumHeight();

        setMeasuredDimension(width, height);
    }

    @Override
    protected int getSuggestedMinimumHeight() {
        paint.setTypeface(Typeface.DEFAULT_BOLD);
        return (int) (-paint.getFontMetrics().top + paint.getFontMetrics().bottom) + getPaddingTop()
                + getPaddingBottom();
    }

    @Override
    public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
        pageOffset = position + positionOffset;
        invalidate();
    }

    @Override
    public void onPageSelected(final int position) {
        pagePosition = position;
        invalidate();
    }

    @Override
    public void onPageScrollStateChanged(final int state) {
    }

    @Override
    public Parcelable onSaveInstanceState() {
        final Bundle state = new Bundle();
        state.putParcelable("super_state", super.onSaveInstanceState());
        state.putInt("page_position", pagePosition);
        state.putFloat("page_offset", pageOffset);
        return state;
    }

    @Override
    public void onRestoreInstanceState(final Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            pagePosition = bundle.getInt("page_position");
            pageOffset = bundle.getFloat("page_offset");
            super.onRestoreInstanceState(bundle.getParcelable("super_state"));
            return;
        }

        super.onRestoreInstanceState(state);
    }
}


text:
/* jshint evil: true */
import a = require('./helpers/array');
import BEM = require('./BEM');
import Configuration = require('./browser/Configuration');
import Formatter = require('./Formatter');
import o = require('./helpers/object');
import Rule = require('./Rule');

class Compiler<T extends Configuration> {

	constructor(public config: T) {
	}

	compile(contents: string): string;
	compile(rules: Rule[]): string;
	compile(rules: {}[]): string;
	compile(rule: Rule): string;
	compile(block: BEM.Block): string;
	compile(rules: {}): string;
	compile(rules: any): string {
		function createRulesFromObject(rule: any) {
			return Object.keys(rule).map(selectors => {
				return new Rule(selectors, rule[selectors]);
			});
		}
		if (typeof rules === 'string') {
			/* tslint:disable:no-eval */
			rules = eval(rules);
		}
		rules = a.flatten([rules]).map(rule => {
			if (o.isPlainObject(rule)) {
				return createRulesFromObject(rule);
			}
			return rule;
		});
		return this.compileRules(a.flatten(rules));
	}

	private compileRules(rules: Rule[]) {
		return this.format(this.resolve(rules));
	}

	private resolve(rules: Rule[]) {
		return rules.map(rule => {
			return rule.resolve(this.config)[0];
		});
	}

	private format(rules: any[][]) {
		return new Formatter().format(this.config, rules);
	}

}

export = Compiler;


text:
<!DOCTYPE html>
<html ng-app="openhds">
  <head>
    <title>OpenHDS</title>
    <link rel="stylesheet" href="node_modules/bootstrap/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="node_modules/angular-ui-tree/dist/angular-ui-tree.min.css">
    <link rel="stylesheet" href="app.css">

  </head>
  <body>
    <script src="node_modules/jquery/dist/jquery.min.js"></script>
    <script src="node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="node_modules/bootstrap/js/alert.js"></script>
    <script src="node_modules/angular/angular.min.js"></script>
    <script src="node_modules/angular-route/angular-route.min.js"></script>
    <script src="node_modules/angular-smart-table/dist/smart-table.min.js"></script>
    <script src="node_modules/angular-sanitize/angular-sanitize.min.js"></script>
    <script src="node_modules/i18next/i18next.min.js"></script>
    <script src="node_modules/i18next-xhr-backend/i18nextXHRBackend.js"></script>
    <script src="node_modules/ng-i18next/dist/ng-i18next.min.js"></script>
    <script src="node_modules/angular-ui-tree/dist/angular-ui-tree.js"></script>

    <script type="text/javascript">
      if(window.i18next) {
        window.i18next.use(window.i18nextXHRBackend);

        window.i18next.init({
          debug: true,
          backend: {
            loadPath: '../locales/{{lng}}/{{ns}}.json'
          },
          useCookie: false,
          useLocalStorage: false
        }, function (err, t) {
          console.log('resources loaded');
        });
      }
    </script>
    <script src="index.js"></script>
    <script src="domain/entity/service.js"></script>
    <script src="domain/locationHierarchy/service.js"></script>
    <script src="domain/fieldworker/service.js"></script>
    <script src="domain/individual/service.js"></script>
    <script src="domain/socialGroup/service.js"></script>
    <script src="domain/relationship/service.js"></script>
    <script src="domain/membership/service.js"></script>
    <script src="domain/residency/service.js"></script>
    <script src="domain/death/service.js"></script>
    <script src="domain/inMigration/service.js"></script>
    <script src="domain/outMigration/service.js"></script>
    <script src="domain/pregnancyOutcome/service.js"></script>
    <script src="domain/pregnancyObservation/service.js"></script>
    <script src="domain/pregnancyResult/service.js"></script>
    <script src="domain/visit/service.js"></script>
    <script src="domain/visitEvent/service.js"></script>
    <script src="auth/controller/loginController.js"></script>
    <script src="baseline/controller/baseline.js"></script>
    <script src="audit/controller/audit.js"></script>
    <script src="components.js"></script>
    <script src="validation.js"></script>
    <script src="domain/location/service.js"></script>
    <script src="update/controller/update.js"></script>
    <div ng-view class="app-div"></div>
  </body>
</html>


text:
package liquibase.precondition;

import liquibase.changelog.DatabaseChangeLog;
import liquibase.changelog.ChangeSet;
import liquibase.database.Database;
import liquibase.exception.PreconditionErrorException;
import liquibase.exception.PreconditionFailedException;
import liquibase.exception.ValidationErrors;
import liquibase.exception.Warnings;

public class MockPrecondition implements Precondition {
    @Override
    public String getName() {
        return "mock";
    }

    @Override
    public Warnings warn(Database database) {
        return new Warnings();
    }

    @Override
    public ValidationErrors validate(Database database) {
        return new ValidationErrors();
    }

    @Override
    public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet) throws PreconditionFailedException, PreconditionErrorException {

    }
}


text:
import json

import msgpack

from .util import create_url, get_or_else, parse_date

class TableAPI:
    """Access to Table API

    This class is inherited by :class:`tdclient.api.API`.
    """

    def list_tables(self, db):
        """Gets the list of table in the database.

        Args:
            db (str): Target database name.

        Returns:
            dict: Detailed table information.

        Examples:
            >>> td.api.list_tables("my_db")
            { 'iris': {'id': 21039862,
              'name': 'iris',
              'estimated_storage_size': 1236,
              'counter_updated_at': '2019-09-18T07:14:28Z',
              'last_log_timestamp': datetime.datetime(2019, 1, 30, 5, 34, 42, tzinfo=tzutc()),
              'delete_protected': False,
              'created_at': datetime.datetime(2019, 1, 30, 5, 34, 42, tzinfo=tzutc()),
              'updated_at': datetime.datetime(2019, 1, 30, 5, 34, 46, tzinfo=tzutc()),
              'type': 'log',
              'include_v': True,
              'count': 150,
              'schema': [['sepal_length', 'double', 'sepal_length'],
               ['sepal_width', 'double', 'sepal_width'],
               ['petal_length', 'double', 'petal_length'],
               ['petal_width', 'double', 'petal_width'],
               ['species', 'string', 'species']],
              'expire_days': None,
              'last_import': datetime.datetime(2019, 9, 18, 7, 14, 28, tzinfo=tzutc())},
            }
        """
        with self.get(create_url("/v3/table/list/{db}", db=db)) as res:
            code, body = res.status, res.read()
            if code != 200:
                self.raise_error("List tables failed", res, body)
            js = self.checked_json(body, ["tables"])
            result = {}
            for m in js["tables"]:
                m = dict(m)
                m["type"] = m.get("type", "?")
                m["count"] = int(m.get("count", 0))
                m["created_at"] = parse_date(
                    get_or_else(m, "created_at", "1970-01-01T00:00:00Z")
                )
                m["updated_at"] = parse_date(
                    get_or_else(m, "updated_at", "1970-01-01T00:00:00Z")
                )
                m["last_import"] = parse_date(
                    get_or_else(m, "counter_updated_at", "1970-01-01T00:00:00Z")
                )
                m["last_log_timestamp"] = parse_date(
                    get_or_else(m, "last_log_timestamp", "1970-01-01T00:00:00Z")
                )
                m["estimated_storage_size"] = int(m["estimated_storage_size"])
                m["schema"] = json.loads(m.get("schema", "[]"))
                result[m["name"]] = m
            return result

    def create_log_table(self, db, table):
        """Create a new table in the database and registers it in PlazmaDB.

        Args:
            db (str): Target database name.
            table (str): Target table name.

        Returns:
            bool: `True` if succeeded.
        """
        return self._create_table(db, table, "log")

    def _create_table(self, db, table, type, params=None):
        params = {} if params is None else params
        with self.post(
            create_url(
                "/v3/table/create/{db}/{table}/{type}", db=db, table=table, type=type
            ),
            params,
        ) as res:
            code, body = res.status, res.read()
            if code != 200:
                self.raise_error("Create %s table failed" % (type), res, body)
            return True

    def swap_table(self, db, table1, table2):
        """Swap the two specified tables with each other belonging to the same database
        and basically exchanges their names.

        Args:
            db (str): Target database name
            table1 (str): First target table for the swap.
            table2 (str): Second target table for the swap.
        Returns:
            bool: `True` if succeeded.
        """
        with self.post(
            create_url(
                "/v3/table/swap/{db}/{table1}/{table2}",
                db=db,
                table1=table1,
                table2=table2,
            )
        ) as res:
            code, body = res.status, res.read()
            if code != 200:
                self.raise_error("Swap tables failed", res, body)
            return True

    def update_schema(self, db, table, schema_json):
        """Update the table schema.

        Args:
            db (str): Target database name.
            table (str): Target table name.
            schema_json (str): Schema format JSON string. See also: ~`Client.update_schema`
                e.g. '[["sep_len", "long", "sep_len"], ["sep_wid", "long", "sep_wid"]]'

        Returns:
            bool: `True` if succeeded.
        """
        with self.post(
            create_url("/v3/table/update-schema/{db}/{table}", db=db, table=table),
            {"schema": schema_json},
        ) as res:
            code, body = res.status, res.read()
            if code != 200:
                self.raise_error("Create schema table failed", res, body)
            return True

    def update_expire(self, db, table, expire_days):
        """Update the expire days for the specified table

        Args:
            db (str): Target database name.
            table (str): Target table name.
            expire_days (int): Number of days where the contents of the specified table
                would expire.
        Returns:
            bool: True if succeeded.
        """
        with self.post(
            create_url("/v3/table/update/{db}/{table}", db=db, table=table),
            {"expire_days": expire_days},
        ) as res:
            code, body = res.status, res.read()
            if code != 200:
                self.raise_error("Update table expiration failed", res, body)
            return True

    def delete_table(self, db, table):
        """Delete the specified table.

        Args:
            db (str): Target database name.
            table (str): Target table name.

        Returns:
            str: Type information of the table (e.g. "log").
        """
        with self.post(
            create_url("/v3/table/delete/{db}/{table}", db=db, table=table)
        ) as res:
            code, body = res.status, res.read()
            if code != 200:
                self.raise_error("Delete table failed", res, body)
            js = self.checked_json(body, [])
            t = js.get("type", "?")
            return t

    def tail(self, db, table, count, to=None, _from=None, block=None):
        """Get the contents of the table in reverse order based on the registered time
        (last data first).

        Args:
            db (str): Target database name.
            table (str): Target table name.
            count (int): Number for record to show up from the end.
            to: Deprecated parameter.
            _from: Deprecated parameter.
            block: Deprecated parameter.

        Returns:
            [dict]: Contents of the table.
        """
        params = {"count": count, "format": "msgpack"}
        with self.get(
            create_url("/v3/table/tail/{db}/{table}", db=db, table=table), params
        ) as res:
            code = res.status
            if code != 200:
                self.raise_error("Tail table failed", res, "")

            unpacker = msgpack.Unpacker(res, raw=False)
            result = []
            for row in unpacker:
                result.append(row)

            return result

    def change_database(self, db, table, dest_db):
        """Move a target table from it's original database to new destination database.

        Args:
            db (str): Target database name.
            table (str): Target table name.
            dest_db (str): Destination database name.

        Returns:
            bool: `True` if succeeded
        """
        params = {"dest_database_name": dest_db}
        with self.post(
            create_url("/v3/table/change_database/{db}/{table}", db=db, table=table),
            params,
        ) as res:
            code, body = res.status, res.read()
            if code != 200:
                self.raise_error("Change database failed", res, body)
            return True


text:
package io.gatling.http.feeder

import io.gatling.commons.validation._
import io.gatling.core.config.{ GatlingConfiguration, GatlingFiles }
import io.gatling.core.feeder.{ FileBasedFeederBuilder, InMemoryFeederSource, SourceFeederBuilder }
import io.gatling.core.util.{ Resource, ResourceCache }

/**
 * Feeder for [[http://www.sitemaps.org/protocol.html sitemap]] file format.
 */
trait SitemapFeederSupport extends ResourceCache {
  def sitemap(filePath: String)(implicit configuration: GatlingConfiguration): FileBasedFeederBuilder[String] =
    sitemap(cachedResource(GatlingFiles.customResourcesDirectory(configuration), filePath))

  def sitemap(resource: Validation[Resource])(implicit configuration: GatlingConfiguration): FileBasedFeederBuilder[String] =
    resource match {
      case Success(res) =>
        SourceFeederBuilder(InMemoryFeederSource(SitemapParser.parse(res, configuration.core.charset), s"sitemap(${res.name})"), configuration)
      case Failure(message) => throw new IllegalArgumentException(s"Could not locate sitemap file: $message")
    }
}


text:
import Vue from 'vue'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
import './assets/paths.css'
import 'whatwg-fetch'
import Paths from './Paths.vue'

Vue.use(ElementUI)

new Vue({
  el: '.container',
  render: h => h(Paths)
})


text:
/*
 * ResourcePathStore.java
 * Creation date: Nov 23, 2004.
 * By: Edward Lam
 */
package org.openquark.cal.services;

import java.util.List;

/**
 * A ModuleResourceStore which uses ResourcePaths to find resources.
 * @author Edward Lam
 */
public interface ResourcePathStore extends ResourceStore {

    /**
     * Get the path to the resource representing a given feature in this store.
     * @param resourceName the name of the resource.
     * @return the path under which the resource corresponding to the feature will be stored, or null
     *   if the file can not correspond to a resource in the store.
     */
    public ResourcePath.FilePath getResourcePath(ResourceName resourceName);

    /**
     * @param folder a folder
     * @return the names representing the resources in the given folder.
     */
    public List<ResourceName> getFolderResourceNames(ResourcePath.Folder folder);

    /**
     * @param folder a folder
     * @param filter the filter used for identifying the resource names to keep in the returned list.
     * @return the names representing the resources in the given folder.
     */
    public List<ResourceName> getFilteredFolderResourceNames(ResourcePath.Folder folder, ResourceName.Filter filter);
}