text:
package pick

import (
	"io"

	"golang.org/x/net/html"
)

// Option
// PageSource: html reader
// TagName: element's tag. ex: div, p, form, input...
type Option struct {
	PageSource io.Reader
	TagName    string
	Attr       *Attr // optional
}

// Attr to define an element's attribute
// <input type="hidden" />
// -> Attr{Label: "type", Value: "hidden"}
type Attr struct {
	Label string
	Value string
}

// PickAttr gets attribute Option.Attr of elements that matches the Option.TagName
func PickAttr(option *Option, AttrLabel string, limit int) (res []string) {
	if option == nil || option.PageSource == nil {
		return
	}

	z := html.NewTokenizer(option.PageSource)

	for {
		tokenType := z.Next()

		switch tokenType {

		// ignore the error token
		// quit on eof
		case html.ErrorToken:
			if z.Err() == io.EOF {
				return
			}

		case html.StartTagToken, html.SelfClosingTagToken:
			tagName, attr := z.TagName()

			if string(tagName) != option.TagName {
				continue
			}

			var label, value []byte

			matched := false
			tmpRes := []string{}

			// get attr
			for attr {
				label, value, attr = z.TagAttr()

				labelStr := string(label)
				valueStr := string(value)

				// check the attr
				if option.Attr == nil || (option.Attr.Label == labelStr && option.Attr.Value == valueStr) {
					matched = true
				}

				// get the result - even the matched false or true
				if labelStr == AttrLabel {
					tmpRes = append(tmpRes, valueStr)
				}
			}

			// skip the non matched one
			if !matched {
				continue
			}

			// send the result for matched only
			res = append(res, tmpRes...)

			// return when limit
			if limit > 0 && len(res) >= limit {
				return
			}
		}
	}

	return
}

// PickText gets text of elements that matches the Option.TagName (including it's child elements)
func PickText(option *Option, limit int) (res []string) {
	if option == nil || option.PageSource == nil {
		return
	}

	z := html.NewTokenizer(option.PageSource)

	depth := 0

	for {
		tokenType := z.Next()

		switch tokenType {

		// ignore the error token
		// quit on eof
		case html.ErrorToken:
			if z.Err() == io.EOF {
				return
			}

		// get text
		case html.TextToken:
			if depth > 0 {
				// append to the last element
				res[len(res)-1] = res[len(res)-1] + string(z.Text())
			}

		case html.EndTagToken:
			if depth > 0 {
				depth--
			}

		case html.StartTagToken:
			tagName, attr := z.TagName()

			// inside the target
			if depth > 0 && !isSelfClosingTag(tagName) {
				depth++
				continue
			}

			// check limit
			if limit > 0 && len(res) >= limit {
				return
			}

			if string(tagName) != option.TagName {
				continue
			}

			var label, value []byte

			matched := false

			// empty attr element
			if !attr && option.Attr == nil {
				matched = true
			}

			// get attr
			for attr {
				label, value, attr = z.TagAttr()

				if option.Attr == nil || (option.Attr.Label == string(label) && option.Attr.Value == string(value)) {
					matched = true
				}
			}

			if !matched {
				continue
			}

			depth++

			// init an empty element
			res = append(res, "")
		}
	}

	return
}

// isSelfClosingTag returns if it's a self closing tag
// html.SelfClosingTagToken is not always correct
// <input/> -> html.SelfClosingTagToken
// <input> -> html.StartTagToken
func isSelfClosingTag(tag []byte) bool {
	switch string(tag) {
	case "area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr":
		return true
	}

	return false
}

// PickHtml gets html of elements that matches the Option.TagName (including it's child elements)
func PickHtml(option *Option, limit int) (res []string) {
	if option == nil || option.PageSource == nil {
		return
	}

	z := html.NewTokenizer(option.PageSource)

	depth := 0

	for {
		tokenType := z.Next()

		switch tokenType {

		// ignore the error token
		// quit on eof
		case html.ErrorToken:
			if z.Err() == io.EOF {
				return
			}

		// get text
		case html.TextToken:
			if depth > 0 {
				// append to the last element
				res[len(res)-1] = res[len(res)-1] + string(z.Raw())
			}

		case html.EndTagToken:
			if depth > 0 {
				depth--
			}

			if depth > 0 {
				// append to the last element
				res[len(res)-1] = res[len(res)-1] + string(z.Raw())
			}

		case html.SelfClosingTagToken:
			if depth > 0 {
				// append to the last element
				res[len(res)-1] = res[len(res)-1] + string(z.Raw())
			}

		case html.StartTagToken:
			tagName, attr := z.TagName()

			// inside the target
			if depth > 0 {
				// append to the last element
				res[len(res)-1] = res[len(res)-1] + string(z.Raw())

				if !isSelfClosingTag(tagName) {
					depth++
				}
				continue
			}

			// check limit
			if limit > 0 && len(res) >= limit {
				return
			}

			if string(tagName) != option.TagName {
				continue
			}

			var label, value []byte

			matched := false

			// empty attr element
			if !attr && option.Attr == nil {
				matched = true
			}

			// get attr
			for attr {
				label, value, attr = z.TagAttr()

				if option.Attr == nil || (option.Attr.Label == string(label) && option.Attr.Value == string(value)) {

					matched = true
				}
			}

			if !matched {
				continue
			}

			depth++

			// init an empty element
			res = append(res, "")
		}
	}

	return
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Dの索引</title>
<meta name="date" content="2015-03-02">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

ブラウザのJavaScriptが無効になっています。

概要

パッケージ

クラス

階層ツリー

非推奨

索引

ヘルプ

前の文字

次の文字

フレーム

フレームなし

すべてのクラス

A B C D E F G H I L M N O P Q R S T U V W Y Z

D

data_sending - クラス のstatic変数geologger.saints.com.geologger.R.string

DBNAME - クラス のstatic変数geologger.saints.com.geologger.models.TableDefinitions

DEBUG - クラス のstatic変数geologger.saints.com.geologger.BuildConfig

decline - クラス のstatic変数geologger.saints.com.geologger.R.string

decor_content_parent - クラス のstatic変数geologger.saints.com.geologger.R.id

default_activity_button - クラス のstatic変数geologger.saints.com.geologger.R.id

delete - クラス のstatic変数geologger.saints.com.geologger.R.string

deleteSelectedLog() - クラス のメソッドgeologger.saints.com.geologger.activities.LogListActivity

dialog - クラス のstatic変数geologger.saints.com.geologger.R.id

dialog_fixed_height_major - クラス のstatic変数geologger.saints.com.geologger.R.dimen

dialog_fixed_height_minor - クラス のstatic変数geologger.saints.com.geologger.R.dimen

dialog_fixed_width_major - クラス のstatic変数geologger.saints.com.geologger.R.dimen

dialog_fixed_width_minor - クラス のstatic変数geologger.saints.com.geologger.R.dimen

dim_foreground_disabled_material_dark - クラス のstatic変数geologger.saints.com.geologger.R.color

dim_foreground_disabled_material_light - クラス のstatic変数geologger.saints.com.geologger.R.color

dim_foreground_material_dark - クラス のstatic変数geologger.saints.com.geologger.R.color

dim_foreground_material_light - クラス のstatic変数geologger.saints.com.geologger.R.color

Direction - geologger.saints.com.geologger.utilsのクラス

Created by Mizuno on 2015/02/13.

Direction() - クラス のコンストラクタgeologger.saints.com.geologger.utils.Direction

DIRECTION - クラス のstatic変数geologger.saints.com.geologger.utils.Direction

disableChildrenWhenDisabled - クラス のstatic変数geologger.saints.com.geologger.R.attr

Must be a boolean value, either "true" or "false".

disabled_alpha_material_dark - クラス のstatic変数geologger.saints.com.geologger.R.dimen

disabled_alpha_material_light - クラス のstatic変数geologger.saints.com.geologger.R.dimen

disableHome - クラス のstatic変数geologger.saints.com.geologger.R.id

dismissProgress() - クラス のメソッドgeologger.saints.com.geologger.activities.LogActivity

dismissProgress() - クラス のメソッドgeologger.saints.com.geologger.activities.LogActivity_

dismissProgress() - クラス のメソッドgeologger.saints.com.geologger.activities.PoiActivity

dismissProgress() - クラス のメソッドgeologger.saints.com.geologger.activities.PoiActivity_

dismissProgress() - クラス のメソッドgeologger.saints.com.geologger.activities.PoiConfirmationActivity

dismissProgress() - クラス のメソッドgeologger.saints.com.geologger.activities.PoiConfirmationActivity_

displayOptions - クラス のstatic変数geologger.saints.com.geologger.R.attr

Must be one or more (separated by '|') of the following constant values.

distance - クラス のstatic変数geologger.saints.com.geologger.R.array

distance_values - クラス のstatic変数geologger.saints.com.geologger.R.array

divider - クラス のstatic変数geologger.saints.com.geologger.R.attr

Must be a reference to another resource, in the form "@[+][package:]type:name"
or to a theme attribute in the form "?

dividerHorizontal - クラス のstatic変数geologger.saints.com.geologger.R.attr

Must be a reference to another resource, in the form "@[+][package:]type:name"
or to a theme attribute in the form "?

dividerPadding - クラス のstatic変数geologger.saints.com.geologger.R.attr

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp".

dividerVertical - クラス のstatic変数geologger.saints.com.geologger.R.attr

Must be a reference to another resource, in the form "@[+][package:]type:name"
or to a theme attribute in the form "?

donate_with_google - クラス のstatic変数geologger.saints.com.geologger.R.id

drawableSize - クラス のstatic変数geologger.saints.com.geologger.R.attr

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp".

drawerArrowStyle - クラス のstatic変数geologger.saints.com.geologger.R.attr

Must be a reference to another resource, in the form "@[+][package:]type:name"
or to a theme attribute in the form "?

DrawerArrowToggle - クラス のstatic変数geologger.saints.com.geologger.R.styleable

Attributes that can be used with a DrawerArrowToggle.

DrawerArrowToggle_barSize - クラス のstatic変数geologger.saints.com.geologger.R.styleable

This symbol is the offset where the R.attr.barSize
          attribute's value can be found in the R.styleable.DrawerArrowToggle array.

DrawerArrowToggle_color - クラス のstatic変数geologger.saints.com.geologger.R.styleable

This symbol is the offset where the R.attr.color
          attribute's value can be found in the R.styleable.DrawerArrowToggle array.

DrawerArrowToggle_drawableSize - クラス のstatic変数geologger.saints.com.geologger.R.styleable

This symbol is the offset where the R.attr.drawableSize
          attribute's value can be found in the R.styleable.DrawerArrowToggle array.

DrawerArrowToggle_gapBetweenBars - クラス のstatic変数geologger.saints.com.geologger.R.styleable

This symbol is the offset where the R.attr.gapBetweenBars
          attribute's value can be found in the R.styleable.DrawerArrowToggle array.

DrawerArrowToggle_middleBarArrowSize - クラス のstatic変数geologger.saints.com.geologger.R.styleable

This symbol is the offset where the R.attr.middleBarArrowSize
          attribute's value can be found in the R.styleable.DrawerArrowToggle array.

DrawerArrowToggle_spinBars - クラス のstatic変数geologger.saints.com.geologger.R.styleable

This symbol is the offset where the R.attr.spinBars
          attribute's value can be found in the R.styleable.DrawerArrowToggle array.

DrawerArrowToggle_thickness - クラス のstatic変数geologger.saints.com.geologger.R.styleable

This symbol is the offset where the R.attr.thickness
          attribute's value can be found in the R.styleable.DrawerArrowToggle array.

DrawerArrowToggle_topBottomBarArrowSize - クラス のstatic変数geologger.saints.com.geologger.R.styleable

This symbol is the offset where the R.attr.topBottomBarArrowSize
          attribute's value can be found in the R.styleable.DrawerArrowToggle array.

drawLine(LatLng, LatLng) - クラス のメソッドgeologger.saints.com.geologger.map.BaseMapWorker

Draw blue line between two designated points

drawLine(float, float, float, float) - クラス のメソッドgeologger.saints.com.geologger.map.BaseMapWorker

Draw blue line between two designated points

drawLine(List<LatLng>) - クラス のメソッドgeologger.saints.com.geologger.map.BaseMapWorker

Draw blue line connecting LatLngs in disignated list

dropdown - クラス のstatic変数geologger.saints.com.geologger.R.id

dropdownListPreferredItemHeight - クラス のstatic変数geologger.saints.com.geologger.R.attr

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp".

dropDownListViewStyle - クラス のstatic変数geologger.saints.com.geologger.R.attr

Must be a reference to another resource, in the form "@[+][package:]type:name"
or to a theme attribute in the form "?

dropTable(SQLiteDatabase) - クラス のメソッドgeologger.saints.com.geologger.database.BaseSQLiteOpenHelper

A B C D E F G H I L M N O P Q R S T U V W Y Z

概要

パッケージ

クラス

階層ツリー

非推奨

索引

ヘルプ

前の文字

次の文字

フレーム

フレームなし

すべてのクラス

redpajama_set_name: RedPajamaGithub


text:
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import AnonymousUserMixin

from webapp.extensions import bcrypt

db = SQLAlchemy()

tags = db.Table(
    'post_tags',
    db.Column('post_id', db.Integer, db.ForeignKey('post.id')),
    db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))
)

roles = db.Table(
    'role_users',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('role_id', db.Integer, db.ForeignKey('role.id'))
)

class User(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    username = db.Column(db.String(255), unique=True)
    password = db.Column(db.String(255))
    posts = db.relationship('Post', backref='user', lazy='dynamic')
    roles = db.relationship(
        'Role',
        secondary=roles,
        backref=db.backref('users', lazy='dynamic')
    )

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

        default = Role.query.filter_by(name="default").one()
        self.roles.append(default)

    def __repr__(self):
        return '<User {}>'.format(self.username)

    def set_password(self, password):
        self.password = bcrypt.generate_password_hash(password)

    def check_password(self, password):
        return bcrypt.check_password_hash(self.password, password)

    def is_authenticated(self):
        if isinstance(self, AnonymousUserMixin):
            return False
        else:
            return True

    def is_active(self):
        return True

    def is_anonymous(self):
        if isinstance(self, AnonymousUserMixin):
            return True
        else:
            return False

    def get_id(self):
        return unicode(self.id)

class Role(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(80), unique=True)
    description = db.Column(db.String(255))

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

    def __repr__(self):
        return '<Role {}>'.format(self.name)

class Post(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    title = db.Column(db.String(255))
    text = db.Column(db.Text())
    publish_date = db.Column(db.DateTime())
    user_id = db.Column(db.Integer(), db.ForeignKey('user.id'))
    comments = db.relationship(
        'Comment',
        backref='post',
        lazy='dynamic'
    )
    tags = db.relationship(
        'Tag',
        secondary=tags,
        backref=db.backref('posts', lazy='dynamic')
    )

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

    def __repr__(self):
        return "<Post '{}'>".format(self.title)

class Comment(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(255))
    text = db.Column(db.Text())
    date = db.Column(db.DateTime())
    post_id = db.Column(db.Integer(), db.ForeignKey('post.id'))

    def __repr__(self):
        return "<Comment '{}'>".format(self.text[:15])

class Tag(db.Model):
    id = db.Column(db.Integer(), primary_key=True)
    title = db.Column(db.String(255))

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

    def __repr__(self):
        return "<Tag '{}'>".format(self.title)


text:
/* $Id: ClpHelperFunctions.hpp 1817 2011-11-03 09:26:23Z forrest $ */
// Copyright (C) 2003, International Business Machines
// Corporation and others.  All Rights Reserved.
// This code is licensed under the terms of the Eclipse Public License (EPL).

#ifndef ClpHelperFunctions_H
#define ClpHelperFunctions_H

#include "ClpConfig.h"
#ifdef HAVE_CMATH
# include <cmath>
#else
# ifdef HAVE_MATH_H
#  include <math.h>
# else
#  error "don't have header file for math"
# endif
#endif

/**
    Note (JJF) I have added some operations on arrays even though they may
    duplicate CoinDenseVector.  I think the use of templates was a mistake
    as I don't think inline generic code can take as much advantage of
    parallelism or machine architectures or memory hierarchies.

*/

double maximumAbsElement(const double * region, int size);
void setElements(double * region, int size, double value);
void multiplyAdd(const double * region1, int size, double multiplier1,
                 double * region2, double multiplier2);
double innerProduct(const double * region1, int size, const double * region2);
void getNorms(const double * region, int size, double & norm1, double & norm2);
#if COIN_LONG_WORK
// For long double versions
CoinWorkDouble maximumAbsElement(const CoinWorkDouble * region, int size);
void setElements(CoinWorkDouble * region, int size, CoinWorkDouble value);
void multiplyAdd(const CoinWorkDouble * region1, int size, CoinWorkDouble multiplier1,
                 CoinWorkDouble * region2, CoinWorkDouble multiplier2);
CoinWorkDouble innerProduct(const CoinWorkDouble * region1, int size, const CoinWorkDouble * region2);
void getNorms(const CoinWorkDouble * region, int size, CoinWorkDouble & norm1, CoinWorkDouble & norm2);
inline void
CoinMemcpyN(const double * from, const int size, CoinWorkDouble * to)
{
     for (int i = 0; i < size; i++)
          to[i] = from[i];
}
inline void
CoinMemcpyN(const CoinWorkDouble * from, const int size, double * to)
{
     for (int i = 0; i < size; i++)
          to[i] = static_cast<double>(from[i]);
}
inline CoinWorkDouble
CoinMax(const CoinWorkDouble x1, const double x2)
{
     return (x1 > x2) ? x1 : x2;
}
inline CoinWorkDouble
CoinMax(double x1, const CoinWorkDouble x2)
{
     return (x1 > x2) ? x1 : x2;
}
inline CoinWorkDouble
CoinMin(const CoinWorkDouble x1, const double x2)
{
     return (x1 < x2) ? x1 : x2;
}
inline CoinWorkDouble
CoinMin(double x1, const CoinWorkDouble x2)
{
     return (x1 < x2) ? x1 : x2;
}
inline CoinWorkDouble CoinSqrt(CoinWorkDouble x)
{
     return sqrtl(x);
}
#else
inline double CoinSqrt(double x)
{
     return sqrt(x);
}
#endif
/// Trace
#   ifdef NDEBUG
#      define ClpTraceDebug(expression)		{}
#   else
void ClpTracePrint(std::string fileName, std::string message, int line);
#      define ClpTraceDebug(expression) { \
       if (!(expression)) { ClpTracePrint(__FILE__,__STRING(expression),__LINE__); } \
  }
#   endif
/// Following only included if ClpPdco defined
#ifdef ClpPdco_H

inline double pdxxxmerit(int nlow, int nupp, int *low, int *upp, CoinDenseVector <double> &r1,
                         CoinDenseVector <double> &r2, CoinDenseVector <double> &rL,
                         CoinDenseVector <double> &rU, CoinDenseVector <double> &cL,
                         CoinDenseVector <double> &cU )
{

// Evaluate the merit function for Newton's method.
// It is the 2-norm of the three sets of residuals.
     double sum1, sum2;
     CoinDenseVector <double> f(6);
     f[0] = r1.twoNorm();
     f[1] = r2.twoNorm();
     sum1 = sum2 = 0.0;
     for (int k = 0; k < nlow; k++) {
          sum1 += rL[low[k]] * rL[low[k]];
          sum2 += cL[low[k]] * cL[low[k]];
     }
     f[2] = sqrt(sum1);
     f[4] = sqrt(sum2);
     sum1 = sum2 = 0.0;
     for (int k = 0; k < nupp; k++) {
          sum1 += rL[upp[k]] * rL[upp[k]];
          sum2 += cL[upp[k]] * cL[upp[k]];
     }
     f[3] = sqrt(sum1);
     f[5] = sqrt(sum2);

     return f.twoNorm();
}

//-----------------------------------------------------------------------
// End private function pdxxxmerit
//-----------------------------------------------------------------------

//function [r1,r2,rL,rU,Pinf,Dinf] =    ...
//      pdxxxresid1( Aname,fix,low,upp, ...
//                   b,bl,bu,d1,d2,grad,rL,rU,x,x1,x2,y,z1,z2 )

inline void pdxxxresid1(ClpPdco *model, const int nlow, const int nupp, const int nfix,
                        int *low, int *upp, int *fix,
                        CoinDenseVector <double> &b, double *bl, double *bu, double d1, double d2,
                        CoinDenseVector <double> &grad, CoinDenseVector <double> &rL,
                        CoinDenseVector <double> &rU, CoinDenseVector <double> &x,
                        CoinDenseVector <double> &x1, CoinDenseVector <double> &x2,
                        CoinDenseVector <double> &y,  CoinDenseVector <double> &z1,
                        CoinDenseVector <double> &z2, CoinDenseVector <double> &r1,
                        CoinDenseVector <double> &r2, double *Pinf, double *Dinf)
{

// Form residuals for the primal and dual equations.
// rL, rU are output, but we input them as full vectors
// initialized (permanently) with any relevant zeros.

// Get some element pointers for efficiency
     double *x_elts  = x.getElements();
     double *r2_elts = r2.getElements();

     for (int k = 0; k < nfix; k++)
          x_elts[fix[k]]  = 0;

     r1.clear();
     r2.clear();
     model->matVecMult( 1, r1, x );
     model->matVecMult( 2, r2, y );
     for (int k = 0; k < nfix; k++)
          r2_elts[fix[k]]  = 0;

     r1      = b    - r1 - d2 * d2 * y;
     r2      = grad - r2 - z1;              // grad includes d1*d1*x
     if (nupp > 0)
          r2    = r2 + z2;

     for (int k = 0; k < nlow; k++)
          rL[low[k]] = bl[low[k]] - x[low[k]] + x1[low[k]];
     for (int k = 0; k < nupp; k++)
          rU[upp[k]] = - bu[upp[k]] + x[upp[k]] + x2[upp[k]];

     double normL = 0.0;
     double normU = 0.0;
     for (int k = 0; k < nlow; k++)
          if (rL[low[k]] > normL) normL = rL[low[k]];
     for (int k = 0; k < nupp; k++)
          if (rU[upp[k]] > normU) normU = rU[upp[k]];

     *Pinf    = CoinMax(normL, normU);
     *Pinf    = CoinMax( r1.infNorm() , *Pinf );
     *Dinf    = r2.infNorm();
     *Pinf    = CoinMax( *Pinf, 1e-99 );
     *Dinf    = CoinMax( *Dinf, 1e-99 );
}

//-----------------------------------------------------------------------
// End private function pdxxxresid1
//-----------------------------------------------------------------------

//function [cL,cU,center,Cinf,Cinf0] = ...
//      pdxxxresid2( mu,low,upp,cL,cU,x1,x2,z1,z2 )

inline void pdxxxresid2(double mu, int nlow, int nupp, int *low, int *upp,
                        CoinDenseVector <double> &cL, CoinDenseVector <double> &cU,
                        CoinDenseVector <double> &x1, CoinDenseVector <double> &x2,
                        CoinDenseVector <double> &z1, CoinDenseVector <double> &z2,
                        double *center, double *Cinf, double *Cinf0)
{

// Form residuals for the complementarity equations.
// cL, cU are output, but we input them as full vectors
// initialized (permanently) with any relevant zeros.
// Cinf  is the complementarity residual for X1 z1 = mu e, etc.
// Cinf0 is the same for mu=0 (i.e., for the original problem).

     double maxXz = -1e20;
     double minXz = 1e20;

     double *x1_elts = x1.getElements();
     double *z1_elts = z1.getElements();
     double *cL_elts = cL.getElements();
     for (int k = 0; k < nlow; k++) {
          double x1z1    = x1_elts[low[k]] * z1_elts[low[k]];
          cL_elts[low[k]] = mu - x1z1;
          if (x1z1 > maxXz) maxXz = x1z1;
          if (x1z1 < minXz) minXz = x1z1;
     }

     double *x2_elts = x2.getElements();
     double *z2_elts = z2.getElements();
     double *cU_elts = cU.getElements();
     for (int k = 0; k < nupp; k++) {
          double x2z2    = x2_elts[upp[k]] * z2_elts[upp[k]];
          cU_elts[upp[k]] = mu - x2z2;
          if (x2z2 > maxXz) maxXz = x2z2;
          if (x2z2 < minXz) minXz = x2z2;
     }

     maxXz   = CoinMax( maxXz, 1e-99 );
     minXz   = CoinMax( minXz, 1e-99 );
     *center  = maxXz / minXz;

     double normL = 0.0;
     double normU = 0.0;
     for (int k = 0; k < nlow; k++)
          if (cL_elts[low[k]] > normL) normL = cL_elts[low[k]];
     for (int k = 0; k < nupp; k++)
          if (cU_elts[upp[k]] > normU) normU = cU_elts[upp[k]];
     *Cinf    = CoinMax( normL, normU);
     *Cinf0   = maxXz;
}
//-----------------------------------------------------------------------
// End private function pdxxxresid2
//-----------------------------------------------------------------------

inline double  pdxxxstep( CoinDenseVector <double> &x, CoinDenseVector <double> &dx )
{

// Assumes x > 0.
// Finds the maximum step such that x + step*dx >= 0.

     double step     = 1e+20;

     int n = x.size();
     double *x_elts = x.getElements();
     double *dx_elts = dx.getElements();
     for (int k = 0; k < n; k++)
          if (dx_elts[k] < 0)
               if ((x_elts[k] / (-dx_elts[k])) < step)
                    step = x_elts[k] / (-dx_elts[k]);
     return step;
}
//-----------------------------------------------------------------------
// End private function pdxxxstep
//-----------------------------------------------------------------------

inline double  pdxxxstep(int nset, int *set, CoinDenseVector <double> &x, CoinDenseVector <double> &dx )
{

// Assumes x > 0.
// Finds the maximum step such that x + step*dx >= 0.

     double step     = 1e+20;

     int n = x.size();
     double *x_elts = x.getElements();
     double *dx_elts = dx.getElements();
     for (int k = 0; k < n; k++)
          if (dx_elts[k] < 0)
               if ((x_elts[k] / (-dx_elts[k])) < step)
                    step = x_elts[k] / (-dx_elts[k]);
     return step;
}
//-----------------------------------------------------------------------
// End private function pdxxxstep
//-----------------------------------------------------------------------
#endif
#endif


text:
//
//  DevAccessor.js
//
//   Created by Eric  .
//
// ---------------------------------
// Common device accessor for all communication channels
// ---------------------------------

'use strict'

import DLog from '../common/DLog';
import { getDevAdminInstance} from './DevAdmin';
import AExecutor from '../common/AsyncExecutorObj';
import { DeviceEvents } from './DevServiceMgr';
import { getUtilsInstance} from '../common/utils/Utils';
import { getBLECommMgrInstance} from '../comm_admins/ble/BLECommMgr';

var instanceDevAccessor = null;
var nDevAccessorObjCnt = 0;

/**
 * @private
 */
export function getDevAccessorInstance()
{

    DLog.printDebugMsg("entered getDevAccessorInstance");

    if(nDevAccessorObjCnt > 0 )
    {
        DLog.printDebugMsg("It's a singleton class, returning existing instance of DevAccessor class ");

        return instanceDevAccessor;
    }

    nDevAccessorObjCnt++;
    DLog.printDebugMsg("DevAccessor Object Count is " + nDevAccessorObjCnt);

    instanceDevAccessor = new DevAccessor();
    return instanceDevAccessor;
}

/**
 * @private
 * This class provide interface to device access services like connect, disconnect, connection status
 * and other device specific access functions.
 */

class DevAccessor {

    constructor(){

        this.deviceScanner = null;
        this.deviceAccessor =  null;
        this.connectedPeripheralID = null;

    }

    handleReadEvent(args)
    {

        DLog.printDebug(this,"handleReadEvent");

        DLog.printDebug(this,'read RSSI for peripheral ' + args.peripheral + ' rssi_value = ' + args.value);
        this.emit(DeviceEvents.kRSSIValue, args.peripheral, args.value);

    }

    getBleDeviceRSSI() {

    }

    getConnectedPeripheralID() {
        return this.connectedPeripheralID;
    }

    connectToDevice(deviceId, autoReleasableListener) {

        DLog.printDebug(this,"   connectToDevice ");
        let objCommMgr = null;

        if(autoReleasableListener != undefined)
        {

           // this.once(DeviceEvents.kConnected,autoReleasableListener);

            let lstnCnt = this.listenerCount(DeviceEvents.kConnected);
            DLog.printDebug(this,"get_volume_level : kConnected listener added, listener count =  " + lstnCnt);
        }

        objCommMgr = getBLECommMgrInstance();
        if(objCommMgr == null )
        {
            return AExecutor.throwAsyncException("Exception: BLE channel not available");
        }

        var functToExecuteThatReturnsPromise = ()=>{return objCommMgr.connectToDevice(deviceId)};

        var onSuccess = ()=>
        {
            DLog.printDebug(this,'Connected to ' + deviceId);
             this.connectedPeripheralID = deviceId;
        }

        var onFailure = (error)=>
        {
            DLog.printDebug(this,'connect error = '  + error);
             this.connectedPeripheralID = null;
        }

        return AExecutor.runAsyncWithCompletionBlock(functToExecuteThatReturnsPromise,onSuccess,onFailure);

    }

    disconnectDevice(deviceId) {
        let objCommMgr = null;
        DLog.printDebug(this,"   disconnectDevice ");

        objCommMgr = getBLECommMgrInstance();
        if(objCommMgr == null )
        {
            return AExecutor.throwAsyncException("Exception: BLE channel not available");
        }
        var functToExecuteThatReturnsPromise = ()=>{return objCommMgr.disconnectDevice(deviceId)};

        var onSuccess = (disconnectedPeripheralId)=>
        {
            DLog.printDebug(this,'disconnected ' + disconnectedPeripheralId);

        }

        var onFailure = (error)=>
        {
            DLog.printDebug(this,'disconnect error = '  + error);

        }

        return AExecutor.runAsyncWithCompletionBlock(functToExecuteThatReturnsPromise,onSuccess,onFailure);

    }

    isDeviceConnnected(deviceId) {
        let objCommMgr = null;
        DLog.printDebug(this,"   isDeviceConnnected ");

        objCommMgr = getBLECommMgrInstance();
        if(objCommMgr == null )
        {
            return AExecutor.throwAsyncException("Exception: BLE channel not available");
        }

        var functToExecuteThatReturnsPromise = ()=>{return objCommMgr.isDeviceConnnected(deviceId)};

        if(deviceId != null)
        {
            return AExecutor.runAsyncWithoutCompletionBlock(functToExecuteThatReturnsPromise);
        }
        else
        {
            return AExecutor.throwAsyncException("Exception: There are no connected peripherals");

        }

    }

    getBleDeviceRSSI(deviceId, autoReleasableListener) { //
        let objCommMgr = null;
        DLog.printDebug(this,"   getBleDeviceRSSI ");

        if(autoReleasableListener != undefined)
        {

             this.once(DeviceEvents.kRSSIValue,autoReleasableListener);

            let lstnCnt = this.listenerCount(DeviceEvents.kRSSIValue);
            DLog.printDebug(this,"getBleDeviceRSSI : kRSSIValue listener added, listener count =  " + lstnCnt);
        }

        objCommMgr = getBLECommMgrInstance();
        if(objCommMgr == null )
        {
            return AExecutor.throwAsyncException("Exception: BLE channel not available");
        }

        var functToExecuteThatReturnsPromise = ()=>{return objCommMgr.getBleDeviceRSSI(deviceId)};

        var onSuccess = (rssi_value)=>
        {
            DLog.printDebug(this,'   getBleDeviceRSSI rssi_value = ' + rssi_value);

        }

        var onFailure = (error)=>
        {
            DLog.printDebug(this,'   getBleDeviceRSSI error = '  + error);

        }

        return AExecutor.runAsyncWithCompletionBlock(functToExecuteThatReturnsPromise,onSuccess,onFailure);

    }

}


text:
using System;

namespace Azure.ResourceManager.Datadog.Models
{
    /// <summary> Terms properties. </summary>
    public partial class DatadogAgreementProperties
    {
        /// <summary> Initializes a new instance of DatadogAgreementProperties. </summary>
        public DatadogAgreementProperties()
        {
        }

        /// <summary> Initializes a new instance of DatadogAgreementProperties. </summary>
        /// <param name="publisher"> Publisher identifier string. </param>
        /// <param name="product"> Product identifier string. </param>
        /// <param name="plan"> Plan identifier string. </param>
        /// <param name="licenseTextLink"> Link to HTML with Microsoft and Publisher terms. </param>
        /// <param name="privacyPolicyLink"> Link to the privacy policy of the publisher. </param>
        /// <param name="retrieveDatetime"> Date and time in UTC of when the terms were accepted. This is empty if Accepted is false. </param>
        /// <param name="signature"> Terms signature. </param>
        /// <param name="accepted"> If any version of the terms have been accepted, otherwise false. </param>
        internal DatadogAgreementProperties(string publisher, string product, string plan, string licenseTextLink, string privacyPolicyLink, DateTimeOffset? retrieveDatetime, string signature, bool? accepted)
        {
            Publisher = publisher;
            Product = product;
            Plan = plan;
            LicenseTextLink = licenseTextLink;
            PrivacyPolicyLink = privacyPolicyLink;
            RetrieveDatetime = retrieveDatetime;
            Signature = signature;
            Accepted = accepted;
        }

        /// <summary> Publisher identifier string. </summary>
        public string Publisher { get; set; }
        /// <summary> Product identifier string. </summary>
        public string Product { get; set; }
        /// <summary> Plan identifier string. </summary>
        public string Plan { get; set; }
        /// <summary> Link to HTML with Microsoft and Publisher terms. </summary>
        public string LicenseTextLink { get; set; }
        /// <summary> Link to the privacy policy of the publisher. </summary>
        public string PrivacyPolicyLink { get; set; }
        /// <summary> Date and time in UTC of when the terms were accepted. This is empty if Accepted is false. </summary>
        public DateTimeOffset? RetrieveDatetime { get; set; }
        /// <summary> Terms signature. </summary>
        public string Signature { get; set; }
        /// <summary> If any version of the terms have been accepted, otherwise false. </summary>
        public bool? Accepted { get; set; }
    }
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />

$for(author-meta)$
<meta name="author" content="$author-meta$" />
$endfor$

$if(date-meta)$
<meta name="date" content="$date-meta$" />
$endif$

<title>$if(title-prefix)$$title-prefix$ - $endif$$pagetitle$</title>

$for(header-includes)$
$header-includes$
$endfor$

$if(mmhighlight-js)$
<link rel="stylesheet" href="$mmhighlight-css$" />

$endif$

$for(css)$
<link rel="stylesheet" href="$css$" />
$endfor$

$if(mathjax)$

$endif$

$if(theme)$

$endif$

$for(include-before)$
$include-before$
$endfor$

$if(title)$

$title$

$if(subtitle)$

$subtitle$

$endif$
$for(author)$
$if(author.name)$

$author.name$

$if(author.affiliation)$
<address class="author_afil">
$author.affiliation$
$endif$
$if(author.email)$
$author.email$
</address>
$endif$
$else$

$author$

$endif$
$endfor$
$if(date)$

$date$

$endif$

$endif$

$if(toc)$

$toc$

$endif$

$body$

$for(include-after)$
$include-after$
$endfor$

$if(theme)$

$endif$

$if(mathjax-url)$

$endif$


text:
var Alloy = require("alloy"), _ = Alloy._, Backbone = Alloy.Backbone;

Alloy.Globals.NAME_PAGE = "LiveOnStage";

Alloy.Globals.DOMAIN = "http://www.liveonstage.com/";

Alloy.Globals.URL_BASE = "index.php?option=com_mobile";

Alloy.Globals.URL_VIDEO = "index.php?option=com_mobile&task=video";

Alloy.Globals.URL_PROFILE = "index.php?option=com_mobile&task=profile";

Alloy.Globals.URL_EVENT = "index.php?option=com_mobile&task=event";

Alloy.Globals.URL_CAMPAIGN = "index.php?option=com_mobile&task=campaign";

Alloy.Globals.URL_CATEGORIES = "index.php?option=com_mobile&task=categories";

Alloy.Globals.URL_LOGIN = "index.php?option=com_mobile&task=startSessionUser";

Alloy.Globals.URL_START_STREAMING = "index.php?option=com_mobile&task=startLiveStreaming";

Alloy.Globals.URL_STOP_STREAMING = "index.php?option=com_mobile&task=stopLiveStreaming";

Alloy.Globals.URL_VALIDATE_STREAMING = "index.php?option=com_mobile&task=validateToStartLive";

Alloy.Globals.LIMIT = 5;

Alloy.Globals.TOP_LIMIT = 50;

Alloy.Globals.IMAGE_EVENT_DEFAULT = "components/com_community/assets/event.png";

Alloy.Globals.IMAGE_USER_DEFAULT = "images/crowd-small.jpg";

Alloy.Globals.USER = "mobile";

Alloy.Globals.PASS = "LiveXenn2013!@coNNectApp";

Alloy.Globals.USER_MOBILE = Ti.Utils.base64encode(Alloy.Globals.USER + "-" + Alloy.Globals.PASS);

Alloy.Globals.TITLE_SIZE = 30;

Alloy.Globals.DESCRIPTION_SIZE = 160;

Alloy.Globals.ABOUT = 100;

Alloy.Globals.CONNECTION_ERROR = "You must be connected to the internet to be able to see this. Please connect and try again!";

Alloy.Globals.USER_RTSP = "liveon";

Alloy.Globals.USER_PASSWORD_RTSP = "NewLive1M";

Alloy.Globals.RESOLUTION_RTSP = "HIGH";

Alloy.createController("index");


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Editing;
using ArcGIS.Core.Data;
using ArcGIS.Core.CIM;
using ArcGIS.Desktop.Editing.Attributes;

namespace AnnoTools
{
  /// <summary>
  /// Illustrates how to add a line callout with a leader line to an annotation feature. This involves interacting with the CIMTextGraphic of the
  /// annotation feature directly.
  /// </summary>
  /// <remarks>
  /// First use the <see cref="Inspector.GetAnnotationProperties"/> method to obtain the AnnotationProperties object.  Obtain the CIMTextGraphic via the
  /// <see cref="AnnotationProperties.TextGraphic"/> property.  Add leader lines and callouts to the CIMTextGraphic then call
  /// <see cref="AnnotationProperties.LoadFromTextGraphic(CIMTextGraphic)"/> to set the new CIMTextGraphic onto the annotation properties. Finally call
  /// <see cref="Inspector.SetAnnotationProperties(AnnotationProperties)"/> to update the Inspector object.
  /// <para></para>
  /// </remarks>
  internal class SimpleLineCallout : MapTool
  {
    public SimpleLineCallout()
    {
      IsSketchTool = true;
      SketchType = SketchGeometryType.Rectangle;
      SketchOutputMode = SketchOutputMode.Map;
    }

    protected override Task OnToolActivateAsync(bool active)
    {
      return base.OnToolActivateAsync(active);
    }

    /// <summary>
    /// Called when the sketch finishes. This is where we will create the edit operation and then execute it.
    /// </summary>
    /// <param name="geometry">The geometry created by the sketch.</param>
    /// <returns>A Task returning a Boolean indicating if the sketch complete event was successfully handled.</returns>
    protected override Task<bool> OnSketchCompleteAsync(Geometry geometry)
    {
      // execute on the MCT
      return QueuedTask.Run(() =>
      {
        // find features under the sketch
        var features = MapView.Active.GetFeatures(geometry);
        if (features.Count == 0)
          return false;

        EditOperation op = null;
        foreach (var annoLayer in features.ToDictionary().Keys.OfType<AnnotationLayer>())
        {
          // are there features?
          var featOids = features[annoLayer];
          if (featOids.Count == 0)
            continue;

          var insp = new Inspector();

          // for each feature
          foreach (var oid in featOids)
          {
            // load an inspector
            insp.Load(annoLayer, oid);

            // get the annotation properties
            var annoProperties = insp.GetAnnotationProperties();

            // get the text graphic
            var cimTextGraphic = annoProperties.TextGraphic;
            if (cimTextGraphic != null)
                      {
                        //
                        // add a leader point to the text graphic
                        //

                        // get the feature shape
              var textExtent = insp.Shape;

                        // find the lower left of the text extent
                        var extent = textExtent.Extent;
                        var lowerLeft = MapPointBuilderEx.CreateMapPoint(extent.XMin, extent.YMin, textExtent.SpatialReference);
                        // move it a little to the left and down
                        var newPoint = GeometryEngine.Instance.Move(lowerLeft, -40, -40);

                        // create a leader point
                        CIMLeaderPoint leaderPt = new CIMLeaderPoint();
                        leaderPt.Point = newPoint as MapPoint;

                        // add to a list
                        List<CIMLeader> leaderArray = new List<CIMLeader>();
                        leaderArray.Add(leaderPt);

                        // assign to the textGraphic
              cimTextGraphic.Leaders = leaderArray.ToArray();

                        //
                        // add the simpleLineCallout
                        //

                        CIMSimpleLineCallout lineCallout = new CIMSimpleLineCallout();
                        lineCallout.LineSymbol = SymbolFactory.Instance.ConstructLineSymbol(ColorFactory.Instance.GreyRGB, 1, SimpleLineStyle.Dash);

                        // asign it to the textSymbol
              var symbol = cimTextGraphic.Symbol.Symbol;
                        var textSymbol = symbol as CIMTextSymbol;

                        textSymbol.Callout = lineCallout;

              // assign the text graphic back to the annotation properties
              annoProperties.LoadFromTextGraphic(cimTextGraphic);

              // assign the annotation properties back to the inspector
              insp.SetAnnotationProperties(annoProperties);
                        }

            // create the edit operation
            if (op == null)
                        {
              op = new EditOperation();
              op.Name = "Alter symbol to simple line callout";
              op.SelectModifiedFeatures = true;
              op.SelectNewFeatures = false;
                    }

            // modify the feature
            op.Modify(insp);
          }
        }

        if ((op != null) && !op.IsEmpty)
        {
          bool result = op.Execute();
          return result;
        }
        return
          false;
      });

    }

  }
}


text:
"""Provides bash tab completions for running unit/functional/integration tests.

Add the following command to your .bashrc file:
export complete -o nospace -C scripts/test_completions.py test.sh

When running ./scripts/test.sh, you may wish to run an individual sub-section,
file, or individual test.  This file implements a command completion utility
used by bash to help users fill out command lines that name items to test.
"""

__author__ = 'Mike Gainer (mgainer@google.com)'

import os
import re
import sys

CLASS_REGEX = re.compile(r'^class (\w+)\(([^)]+)\):')
TEST_REGEX = re.compile(r'^    def (test_\w+)')

def enumerate_tests(filename, all_test_names):
    """List all test functions within a file."""

    with open(filename) as fp:
        lines = fp.readlines()

    cleaned_filename = filename.replace('.py', '').replace('/', '.')
    current_class = None
    for line in lines:
        matches = CLASS_REGEX.match(line)
        if matches:
            test_class, base_class = matches.groups()
            if 'Base' not in test_class and 'Test' in base_class:
                current_class = test_class
        matches = TEST_REGEX.match(line)
        if matches:
            all_test_names.append(
                '%s.%s.%s' %
                (cleaned_filename, current_class, matches.group(1)))

def enumerate_files(path, filenames):
    """Recursively build up a list of all files under a directory."""

    for item in os.listdir(path):
        fullname = os.path.join(path, item)
        if os.path.isdir(fullname):
            enumerate_files(fullname, filenames)
        elif os.path.isfile(fullname):
            filenames.append(fullname)

def prune_completions(prefix, all_test_names):
    """Filter returning only items that will complete the current prefix."""

    completions = set()
    for test_name in all_test_names:
        if test_name.startswith(prefix):
            next_break = test_name.find('.', len(prefix) + 1)
            if next_break >= 0:
                # Add only enough to complete this level; don't drown
                # the user with all the possible completions from
                # here.
                completions.add(test_name[:next_break])
            else:
                # If there are no more levels, then add the full name
                # of the leaf.
                completions.add(test_name)
    return completions

def get_completions(prefix, tests_root):
    """Identify all completions, providng only those matching the prefix."""

    filenames = []
    enumerate_files(tests_root, filenames)

    all_test_names = []
    for filename in filenames:
        enumerate_tests(filename, all_test_names)

    return prune_completions(prefix, all_test_names)

def main():
    """Interface to outside world using sys.argv, stdout."""

    for item in get_completions(sys.argv[2], 'tests'):
        print item

if __name__ == '__main__':
    main()


text:
package com.mercateo.common.rest.schemagen;

import java.util.List;

import com.mercateo.common.rest.schemagen.types.PaginatedList;

public class TestPaginatedResponse extends PaginatedList<TestRto> {
    public TestPaginatedResponse(int total, int offset, int limit, List<TestRto> members) {
        super(total, offset, limit, members);
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
 * Date: September 1st 2014
 * Author: Yagnesh Shah
 * Twitter handle: @YagneshHShah
 * Organization: Moolya Software Testing Pvt Ltd
 * License Type: MIT
-->

<project name="projectName" default="clean" basedir="./../../"> <!-- 2 directories back from child build.xml's current directory which is pointing to root directory -->

	<!-- ========== Initialize Properties =================================== -->
	<!-- Include your properties in your build script -->
	<property file="config.properties" prefix="configfile"/>

    <property name="ws.home" value="${basedir}" />
	<property name="ws.jars" value="${configfile.allJarsPath}" />
	<property name="test.dest" value="${ws.home}/build"/>
    <property name="test.src" value="${ws.home}/src"/>
	<property name="ng.result" value="test-output"/>

	<echo> value of base dir = ${basedir} </echo>

	<!-- properties for copying the results -->
	 <tstamp>
		<format property="year" pattern="yyyy" />
		<format property="DSTAMP" pattern="yyyy-MM-dd" />
		<format property="TSTAMP" pattern="HH:mm:ss" />
		<format property="dateversion" pattern="yyyy.MM.dd.HH:mm:ss" />
		<format property="time.stamp" pattern="yyyy-MM-dd_HH-mm-ss aa_"/>
	</tstamp>

	<property name="testng.report.dir" value="${ws.home}/testngReports/${time.stamp}"/>
	<property name="testngXslt.report.dir" value="${ws.home}/testngXsltReports/${time.stamp}"/>

	<!-- ====== For setting the classpath ====  -->
    <target name="setClassPath" unless="test.classpath">
        <path id="classpath_jars">
            <fileset dir="${ws.jars}" includes = "*.jar"/>
        </path>
        <pathconvert pathsep=":"
        	property="test.classpath"
        	refid="classpath_jars" />

    </target>

	<!-- ============ Initializing other stuff ===========  -->
    <target name="init" depends="setClassPath">
        <tstamp>
            <format property="start.time" pattern="MM-dd-yyyy (HH-mm-ss)"/>
        </tstamp>
    	<condition property="ANT"
    		value="$(env.ANT_HOME)/bin/ant.bat"
    		else="$(env.ANT_HOME)/bin/ant">
    		<!-- os family="windows" /-->
    		<os family="mac" />
    	</condition>

	    <!-- Copy ant-contrib-0.3.jar to the lib directory of your Ant installation. If you want to use one of the tasks in your own project, add the lines
    	<taskdef resource="net/sf/antcontrib/antcontrib.properties"/>
    	to your build file.
    	website reference :: http://ant-contrib.sourceforge.net/
    	-->
    	<taskdef resource="net/sf/antcontrib/antcontrib.properties"/>

    	<taskdef name="testng" classpath="${configfile.testngJarPath}" classname="org.testng.TestNGAntTask" />
    	<!--
    	<!- use direct path for classpath if you don't prefer to use 'lib' directory:    classpath="/Users/yash/Documents/Jar Files/testng-6.8.jar"   ->
    	<taskdef name="testng" classname="org.testng.TestNGAntTask">
    		<classpath>
    	    	<pathelement location="./lib/testng.jar"/>
    	    </classpath>
    	</taskdef>
    	-->

    </target>

	<target name="all">
	</target>

	<!-- cleaning the destination folders -->
	<target name="clean">
        <echo message="deleting existing build directory"/>
        <delete dir="${test.dest}"/>
    </target>

	<!-- target for compiling the java files -->
    <target name="compile" depends="init, clean">
    	<delete includeemptydirs="true" quiet="true">
    		<fileset dir="${test.dest}" includes="**/*"/>
    	</delete>
    	<echo message="making directory....."/>
    	<mkdir dir="${test.dest}"/>
    	<echo message="classpath-------: ${test.classpath}"/>
    	<echo message="compiling....."/>
        <javac
        	debug="true"
        	destdir="${test.dest}"
        	srcdir="${test.src}"
        	classpath="${test.classpath}"
        	includeantruntime="true"/>
    </target>

	<!-- build -->
	<target name="build" depends="init">
	</target>

	<!--  ========== Test executions & Generating reports using Testng utility for multiple suites ==============    -->
	<!-- run -->
	<target name="run" depends="compile">
		<!--suite 1 begin -->
		<property name="suite.web.Suite1_RegressionLoginLogout" value="Suite1_RegressionLoginLogout" />
		<testng classpath="${test.classpath}:${test.dest}" suitename="Suite1_RegressionLoginLogout" outputDir="test-output" >
			<xmlfileset dir="." includes="suites/webSuites/Suite1_RegressionLoginLogout.xml" />
		</testng>
	    <antcall target="testngReportCopyAndReportParserAndEmailReport">
	    	<param name="testngDir" value="${testng.report.dir}${suite.web.Suite1_RegressionLoginLogout}"/>
		</antcall>

		<!--suite 2 begin -->
		<property name="suite.web.Suite2_AnnotationInvalidLoginTests" value="Suite2_AnnotationInvalidLoginTests" />
		<testng classpath="${test.classpath}:${test.dest}" suitename="Suite2_AnnotationInvalidLoginTests" outputDir="test-output" >
			<xmlfileset dir="." includes="suites/webSuites/Suite2_AnnotationInvalidLoginTests.xml" />
		</testng>
	    <antcall target="testngReportCopyAndReportParserAndEmailReport">
	    	<param name="testngDir" value="${testng.report.dir}${suite.web.Suite2_AnnotationInvalidLoginTests}"/>
		</antcall>
	</target>

	<target name="testngReportCopyAndReportParserAndEmailReport">
		<!-- to copy previous suite result from test-output to TestngReports directory -->
		<mkdir dir="${testngDir}">
		</mkdir>

		<copy todir="${testngDir}">
			<fileset dir="test-output"/>
		</copy> <!-- end of Testng Report -->

		<!-- Execute ReportParseAndGoogleDocUpdate -->
		<testng classpath="${test.classpath}:${test.dest}" suitename="ReportParseAndGoogleDocUpdate" outputDir="test-output-GoogleParserReport" >
			<xmlfileset dir="." includes="suites/webSuites/ReportParseAndGoogleDocUpdate.xml" />
		</testng>

		<!-- Email current suite report from test-output dir -->
		<testng classpath="${test.classpath}:${test.dest}" suitename="SuiteEmail" outputDir="test-output-EmailReport" >
			<xmlfileset dir="." includes="suites/webSuites/SuiteEmail.xml" />
		</testng>
	</target>

	<!--  ========== Test executions & Generating reports using XSLT utility for multiple suites ==============    -->
	<!-- run -->
		<target name="runAsTestngXslt" depends="compile">

			<!--suite 1 begin -->
			<property name="suite.web.Suite1_RegressionLoginLogout" value="Suite1_RegressionLoginLogout" />
			<testng classpath="${test.classpath}:${test.dest}" suitename="Suite1_RegressionLoginLogout" outputDir="test-output" >
				<xmlfileset dir="." includes="suites/webSuites/Suite1_RegressionLoginLogout.xml" />
			</testng>
		    <antcall target="testngXsltReportCopyAndReportParserAndEmailReport">
		    	<param name="testngXsltDir" value="${testngXslt.report.dir}${suite.web.Suite1_RegressionLoginLogout}"/>
			</antcall>

			<!--suite 2 begin -->
			<property name="suite.web.Suite2_AnnotationInvalidLoginTests" value="Suite2_AnnotationInvalidLoginTests" />
			<testng classpath="${test.classpath}:${test.dest}" suitename="Suite2_AnnotationInvalidLoginTests" outputDir="test-output" >
				<xmlfileset dir="." includes="suites/webSuites/Suite2_AnnotationInvalidLoginTests.xml" />
			</testng>
		    <antcall target="testngXsltReportCopyAndReportParserAndEmailReport">
		    	<param name="testngXsltDir" value="${testngXslt.report.dir}${suite.web.Suite2_AnnotationInvalidLoginTests}"/>
			</antcall>

		</target>

		<target name="testngXsltReportCopyAndReportParserAndEmailReport">
			<!-- to copy previous suite result from test-output to TestngXSLTReports directory -->
			<mkdir dir="${testngXsltDir}">
			</mkdir>

	        <xslt in="${ws.home}/test-output/testng-results.xml" style="src/xslt/testng-results.xsl"
	        	out="${testngXsltDir}/index.html" classpathref="test.c" processor="SaxonLiaison">

	        	<param name="testNgXslt.outputDir" expression="${testngXsltDir}" />
	            <param name="testNgXslt.showRuntimeTotals" expression="true" />
	            <param name="testNgXslt.sortTestCaseLinks" expression="true"  />
	            <param name="testNgXslt.testDetailsFilter" expression="FAIL,SKIP,PASS,CONF,BY_CLASS" />
	        </xslt>  <!-- end of TestngXslt Report -->

			<!-- Execute ReportParseAndGoogleDocUpdate -->
			<testng classpath="${test.classpath}:${test.dest}" suitename="ReportParseAndGoogleDocUpdate" outputDir="test-output-GoogleParserReport" >
				<xmlfileset dir="." includes="suites/webSuites/ReportParseAndGoogleDocUpdate.xml" />
			</testng>

			<!-- Email current suite report from test-output dir -->
			<testng classpath="${test.classpath}:${test.dest}" suitename="SuiteEmail" outputDir="test-output-EmailReport" >
				<xmlfileset dir="." includes="suites/webSuites/SuiteEmail.xml" />
			</testng>
		</target>

	<path id="test.c">
			<fileset dir="${ws.jars}" includes="*.jar">
				<include name="mail.jar"/>
				<include name="activation-1.0.2.jar"/>
			</fileset>
	</path>

	<!--  ========== Generating reports using Testng XSLT utility for single suite only ==============   -->
    <target name="report" depends="run">
    	<!-- TestngXslt report -->
    	<mkdir dir="${testngXslt.report.dir}">
    	</mkdir>

    	<!-- to copy previous suite result to TestngXslt report folder -->
        <xslt in="${ws.home}/test-output/testng-results.xml" style="src/xslt/testng-results.xsl"
        	out="${testngXslt.report.dir}/index.html" classpathref="test.c" processor="SaxonLiaison">

        	<param name="testNgXslt.outputDir" expression="${testngXslt.report.dir}" />
            <param name="testNgXslt.showRuntimeTotals" expression="true" />
            <param name="testNgXslt.sortTestCaseLinks" expression="true"  />
            <param name="testNgXslt.testDetailsFilter" expression="FAIL,SKIP,PASS,CONF,BY_CLASS" />
        </xslt>  <!-- end of TestngXslt Report -->
    </target>

	<target name="RunAndViewReport" depends="report">
	        <exec executable="${browser}" spawn="yes">
	       <arg line="'file:///${testngXslt.report.dir}/index.html'" />
	      </exec>
	     </target>

	<target name="sendMail" depends="RunAndViewReport">
	        <zip destfile="${testngXslt.report.dir}/Report.zip" basedir="${testngXslt.report.dir}"/>
	        <mail mailhost="smtp.gmail.com" mailport="465" subject="Notification of TESTNG build result" ssl="false" user="abc@gmail.com" password="abc">
	            <from address="abc@gmail.com"/>
	            <to address="xyz@gmail.com"/>
	            <message>The build has finished. A details report of this build is attached</message>
	            <attachments>
	                <fileset dir="testngXslt.report.dir">
	                    <include name="**/*.zip"/>
	                </fileset>
	            </attachments>
	        </mail>
	    </target>

	  <target name="install-jars" description="Install ANT optional jars">
	        <get dest="${ws.home}/lib/mail.jar" src="file:///${ws.home}/lib/mail.jar"/>
			<fileset dir="${ws.jars}" includes="*.jar">
				<include name="mail.jar"/>
				<include name="activation-1.0.2.jar"/>
			</fileset>
	  </target>

</project>


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Rulingia parviflora Endl.

### Remarks
null


text:
import {html, render} from 'lit';
import {customElement} from 'lit/decorators.js';

import {Environment} from '../testing/environment.js';

import {NavigationTabHarness} from './harness.js';
import {MdNavigationTab} from './navigation-tab.js';

@customElement('md-test-navigation-tab')
class TestNavigationTab extends MdNavigationTab {
}

declare global {
  interface HTMLElementTagNameMap {
    'md-test-navigation-tab': TestNavigationTab;
  }
}

describe('mwc-navigation-tab', () => {
  const env = new Environment();

  async function setupTest() {
    // Variant type does not matter for shared tests
    const element =
        env.render(html`<md-test-navigation-tab></md-test-navigation-tab>`)
            .querySelector('md-test-navigation-tab');
    if (!element) {
      throw new Error('Could not query rendered <md-test-navigation-tab>.');
    }

    await env.waitForStability();
    const button = element.renderRoot.querySelector('button');
    if (!button) {
      throw new Error('Could not query rendered <button>.');
    }

    const navTab = element.renderRoot.querySelector('.md3-navigation-tab');
    if (!navTab) {
      throw new Error('Could not query rendered .md3-navigation-tab.');
    }

    const focusRing = element.renderRoot.querySelector('md-focus-ring');
    if (!focusRing) {
      throw new Error('Could not query rendered <md-focus-ring>.');
    }

    return {
      button,
      navTab,
      focusRing,
      harness: new NavigationTabHarness(element),
    };
  }

  describe('basic', () => {
    it('initializes as an md-navigation-tab', async () => {
      const {harness} = await setupTest();
      expect(harness.element).toBeInstanceOf(MdNavigationTab);
      expect(harness.element.active).toBeFalse();
      expect(harness.element.hideInactiveLabel).toBeFalse();
      expect(harness.element.label).toBeUndefined();
      expect(harness.element.badgeValue).toEqual('');
      expect(harness.element.showBadge).toBeFalse();
    });

    it('emits interaction event on click', async () => {
      const {harness} = await setupTest();
      const interactionHandler = jasmine.createSpy();
      harness.element.addEventListener(
          'navigation-tab-interaction', interactionHandler);
      await harness.clickWithMouse();
      expect(interactionHandler).toHaveBeenCalled();
    });

    it('focus() sets focus on button element', async () => {
      const {harness, button} = await setupTest();
      harness.element.focus();
      expect(button.matches(':focus')).toBeTrue();
    });
  });

  it('on render navigation-tab-rendered event fires', async () => {
    const element = document.createElement('md-test-navigation-tab');
    const renderedHandler = jasmine.createSpy();
    element.addEventListener('navigation-tab-rendered', renderedHandler);
    env.render(html`${element}`);
    await env.waitForStability();
    expect(renderedHandler).toHaveBeenCalled();
  });

  describe('active', () => {
    it('affects `aria-selected` of native button', async () => {
      const {harness, button} = await setupTest();
      harness.element.active = true;
      await env.waitForStability();

      expect(button.getAttribute('aria-selected')).toEqual('true');

      harness.element.active = false;
      await env.waitForStability();
      expect(button.getAttribute('aria-selected')).toEqual('false');
    });

    it('affects `tabindex` of native button', async () => {
      const {harness, button} = await setupTest();
      harness.element.active = true;
      await env.waitForStability();

      expect(button.getAttribute('tabindex')).toEqual('0');

      harness.element.active = false;
      await env.waitForStability();
      expect(button.getAttribute('tabindex')).toEqual('-1');
    });

    it('sets the correct classes', async () => {
      const {harness, navTab} = await setupTest();
      harness.element.active = true;
      await env.waitForStability();

      expect(navTab.classList.contains('md3-navigation-tab--active'))
          .toBeTrue();
    });
  });

  describe('hideInactiveLabel', () => {
    it('sets the correct classes', async () => {
      const {harness, navTab} = await setupTest();
      harness.element.hideInactiveLabel = true;
      await env.waitForStability();

      expect(
          navTab.classList.contains('md3-navigation-tab--hide-inactive-label'))
          .toBeTrue();
    });
  });

  describe('label', () => {
    it('displays label text', async () => {
      const {harness} = await setupTest();
      harness.element.label = 'foo';
      await env.waitForStability();

      const content = harness.element.shadowRoot!.querySelector(
          '.md3-navigation-tab__label-text')!;
      expect(content.textContent!.trim()).toEqual('foo');
    });
  });

  describe('ariaLabel', () => {
    it('affects `aria-label` of native button', async () => {
      const {harness, button} = await setupTest();
      harness.element.label = 'foo';
      harness.element.ariaLabel = 'bar';
      await env.waitForStability();

      expect(button.getAttribute('aria-label')).toEqual('bar');
    });
  });

  describe('showBadge', () => {
    it('displays badge', async () => {
      const {harness} = await setupTest();
      harness.element.showBadge = true;
      await env.waitForStability();

      const badge = harness.element.renderRoot.querySelector('md-badge');
      expect(badge).toBeDefined();
    });

    it('does not display badge if showBadge is false', async () => {
      const {harness} = await setupTest();
      harness.element.showBadge = false;
      await env.waitForStability();

      const badge = harness.element.renderRoot.querySelector('md-badge');
      expect(badge).toEqual(null);
    });
  });

  describe('badgeValue', () => {
    it('displays badge value', async () => {
      const {harness} = await setupTest();
      harness.element.showBadge = true;
      harness.element.badgeValue = '9';
      await env.waitForStability();

      const badge = harness.element.renderRoot.querySelector('md-badge');
      expect(badge?.value).toEqual('9');
    });
  });

  describe('icons', () => {
    it('nodes with `slot=activeIcon` will serve as the active icon',
       async () => {
         const {harness} = await setupTest();
         const icons = html`
           star
           star_border
         `;
         render(icons, harness.element);

         const icon =
             harness.element.querySelector<HTMLElement>('[slot="activeIcon"]')!;
         expect(icon.textContent!.trim()).toEqual('star');
       });

    it('nodes with `slot=inactiveIcon` will serve as the inactive icon',
       async () => {
         const {harness} = await setupTest();
         const icons = html`
           star
           star_border
         `;
         render(icons, harness.element);

         const icon = harness.element.querySelector<HTMLElement>(
             '[slot="inactiveIcon"]')!;
         expect(icon.textContent!.trim()).toEqual('star_border');
       });
  });

  describe('focus ring', () => {
    it('hidden on non-keyboard focus', async () => {
      const {harness, focusRing} = await setupTest();
      await harness.clickWithMouse();
      expect(focusRing.visible).toBeFalse();
    });

    it('visible on keyboard focus and hides on blur', async () => {
      const {harness, focusRing} = await setupTest();
      await harness.focusWithKeyboard();
      expect(focusRing.visible).toBeTrue();
      await harness.blur();
      expect(focusRing.visible).toBeFalse();
    });

    it('hidden after pointer interaction', async () => {
      const {harness, focusRing} = await setupTest();
      await harness.focusWithKeyboard();
      expect(focusRing.visible).toBeTrue();
      await harness.clickWithMouse();
      expect(focusRing.visible).toBeFalse();
    });
  });
});


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2016-2020 Couchbase, Inc.
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

#include "contrib/lcb-jsoncpp/lcb-jsoncpp.h"
#include "placeholders.h"
#include <algorithm>
#include <memory>
#include <stdexcept>

namespace Pillowfight
{

#define JSON_VALUE_SIZE 16

/**
 * Per-thread mutable state to generate the document. The populateIov()
 * method is called to populate IOVs suitable for passing to the storage
 * functions.
 */
class GeneratorState
{
  public:
    /**
     * Populate an IOV array
     * @param seq The sequence number (used as a 'selector')
     * @param[out] iov IOV containing pointers to buffers
     *
     * The buffers pointed to in the IOV array remain valid so long as
     * the populateIov() function is not called again on this state
     */
    virtual void populateIov(uint32_t seq, std::vector< lcb_IOV > &iov) = 0;
    virtual ~GeneratorState() {}
};

class SubdocSpec
{
  public:
    std::string path;
    std::string value;
    bool mutate;

    SubdocSpec() : path(""), value(""), mutate(false) {}
};

class SubdocGeneratorState
{
  public:
    /**
     * Populates subdocument command specifications
     * @param seq the sequence number of the current command
     * @param[in,out] specs container to hold the actual spec array.
     *  The spec array must have already been properly pre-sized.
     */
    virtual void populateLookup(uint32_t seq, std::vector< SubdocSpec > &specs) = 0;
    virtual void populateMutate(uint32_t seq, std::vector< SubdocSpec > &specs) = 0;
    virtual ~SubdocGeneratorState() {}
};

class DocGeneratorBase
{
  public:
    /**
     * Create the per-thread state for generating documents
     * @param total_gens Number of total generator threads
     * @param cur_gen The index of the current generator thread
     * @return An opaque state object. This should be deleted by the caller
     */
    virtual std::unique_ptr<GeneratorState> createState(int total_gens, int cur_gen) const = 0;
    virtual std::unique_ptr<SubdocGeneratorState> createSubdocState(int, int) const
    {
        return NULL;
    }
    virtual ~DocGeneratorBase() {}
};

static const char alphabet[] = "0123456789 abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

static void random_fill(std::string &str, int level)
{
    if (level > 1) {
        for (size_t ii = 0; ii < str.size(); ii++) {
            str[ii] = rand() % (0x7e - 0x20) + 0x20; // printable
            switch (str[ii]) {
                case 0x5c: // backslash
                case 0x22: // double quote
                    str[ii]++;
                    break;
            }
        }
    } else if (level > 0) {
        for (size_t ii = 0; ii < str.size(); ii++) {
            str[ii] = alphabet[rand() % (sizeof(alphabet) - 1)];
        }
    }
}

/**
 * Generator class for raw objects. This contains a fixed buffer and will
 * simply vary in how 'long' the buffer is
 */
class RawDocGenerator : public DocGeneratorBase
{
  public:
    /**
     * Generate graded sizes based on a min,max specification. This allows us
     * to be more efficient by cutting corners on how 'random' the sizes
     * actually are. Rather than generating a 'random' size each time we need
     * a document, we split the range into a set of potential sizes (which are
     * also evenly distributed) and cycle between them.
     *
     * @param minsz Smallest desired size
     * @param maxsz Largest desired size
     * @param granularity How many grades to produce
     * @return A vector of sizes which fall between the range
     */
    static std::vector< size_t > gen_graded_sizes(uint32_t minsz, uint32_t maxsz, int grades = 10)
    {
        std::vector< size_t > ret;

        size_t diff = maxsz - minsz;
        size_t factor = diff / grades;
        if (factor == 0 || minsz == maxsz) {
            ret.push_back(maxsz);
        } else {
            for (int ii = 0; ii < grades + 1; ii++) {
                size_t size = minsz + (factor * ii);
                ret.push_back(size);
            }
        }
        return ret;
    }

    RawDocGenerator(uint32_t minsz, uint32_t maxsz, int rnd) : m_sizes(gen_graded_sizes(minsz, maxsz))
    {
        // Populate the buffer to its capacity
        m_buf.insert(0, maxsz, '#');
        if (rnd) {
            random_fill(m_buf, rnd);
        }
    }

    class MyState : public GeneratorState
    {
      public:
        MyState(const RawDocGenerator *parent) : m_parent(parent) {}

        const RawDocGenerator *m_parent;
        void populateIov(uint32_t seq, std::vector< lcb_IOV > &iov_out)
        {
            m_parent->populateIov(seq, iov_out);
        }
    };

    std::unique_ptr<GeneratorState> createState(int, int) const
    {
        return std::unique_ptr<GeneratorState>(new MyState(this));
    }

  private:
    void populateIov(uint32_t seq, std::vector< lcb_IOV > &iov_out) const
    {
        iov_out.resize(1);
        size_t cursz = m_sizes[seq % m_sizes.size()];
        iov_out[0].iov_base = const_cast< char * >(m_buf.c_str());
        iov_out[0].iov_len = cursz;
    }
    std::string m_buf;
    std::vector< size_t > m_sizes;
};

/**
 * This 'generator' ignores sizes and generates documents as they are received
 * from premade buffers
 */
class PresetDocGenerator : public DocGeneratorBase
{
  public:
    /**
     * @param inputs List of fixed inputs to use
     */
    PresetDocGenerator(const std::vector< std::string > &inputs) : m_bufs(inputs) {}

    class MyState : public GeneratorState
    {
      public:
        MyState(const PresetDocGenerator *parent) : m_parent(parent) {}

        void populateIov(uint32_t seq, std::vector< lcb_IOV > &iov_out)
        {
            m_parent->populateIov(seq, iov_out);
        }

      private:
        const PresetDocGenerator *m_parent;
    };

    std::unique_ptr<GeneratorState> createState(int, int) const
    {
        return std::unique_ptr<GeneratorState>(new MyState(this));
    }

  protected:
    PresetDocGenerator() {}

    void populateIov(uint32_t seq, std::vector< lcb_IOV > &iov_out) const
    {
        iov_out.resize(1);
        const std::string &s = m_bufs[seq % m_bufs.size()];
        iov_out[0].iov_base = const_cast< char * >(s.c_str());
        iov_out[0].iov_len = s.size();
    }
    std::vector< std::string > m_bufs;
};

// This is the same as the normal document generator, except we generate
// the JSON first
class JsonDocGenerator : public PresetDocGenerator
{
  private:
    struct Doc {
        std::string m_doc;
        class Field
        {
          public:
            Field(const std::string &n, std::string &v) : m_name(n), m_value(v) {}
            const std::string &name() const
            {
                return m_name;
            }
            const std::string &value() const
            {
                return m_value;
            }

          private:
            std::string m_name;
            std::string m_value;
        };
        std::vector< Field > m_fields;
    };
    std::vector< Doc > m_docs;

  public:
    /**
     * @param minsz Minimum JSON document size
     * @param maxsz Maximum JSON document size
     */
    JsonDocGenerator(uint32_t minsz, uint32_t maxsz, int rnd)
    {
        genDocuments(minsz, maxsz, m_docs, rnd);
        for (size_t ii = 0; ii < m_docs.size(); ++ii) {
            m_bufs.push_back(m_docs[ii].m_doc);
        }
    }

    static void genDocuments(uint32_t minsz, uint32_t maxsz, std::vector< std::string > &out, int rnd)
    {
        std::vector< Doc > docs;
        genDocuments(minsz, maxsz, docs, rnd);
        for (size_t ii = 0; ii < docs.size(); ++ii) {
            out.push_back(docs[ii].m_doc);
        }
    }

  private:
    /**
     * Helper method to decrease the original size by a given amount.
     *
     * This also ensures the number never reaches below 0.
     *
     * @param[out] orig Pointer to original size
     * @param toDecr number by which to decrement
     */
    static void decrSize(int *orig, size_t toDecr)
    {
        *orig = std::max(0, *orig - static_cast< int >(toDecr));
    }

    static void genDocuments(uint32_t minsz, uint32_t maxsz, std::vector< Doc > &out, int rnd)
    {
        std::vector< size_t > sizes = RawDocGenerator::gen_graded_sizes(minsz, maxsz);
        for (std::vector< size_t >::iterator ii = sizes.begin(); ii != sizes.end(); ++ii) {
            out.push_back(generate(*ii, rnd));
        }
    }

    /**
     * Generates a "JSON" document of a given size. In order to remain
     * more or less in-tune with common document sizes, field names will be
     * "Field_$incr" and values will be evenly distributed as fixed 16 byte
     * strings. (See JSON_VALUE_SIZE)
     */
    static Doc generate(int docsize, int rnd)
    {
        int counter = 0;
        char keybuf[128] = {0};
        Json::Value root(Json::objectValue);
        Json::FastWriter writer;
        Doc ret;

        while (docsize > 0) {
            decrSize(&docsize, sprintf(keybuf, "Field_%d", ++counter) + 3);
            size_t valsize = std::min(JSON_VALUE_SIZE, docsize);
            if (!valsize) {
                valsize = 1;
            }
            std::string value(valsize, '*');
            if (rnd) {
                random_fill(value, rnd);
            }
            decrSize(&docsize, valsize + 3);
            root[keybuf] = value;
            value = '"' + value;
            value += '"';
            ret.m_fields.push_back(Doc::Field(keybuf, value));
        }
        ret.m_doc = writer.write(root);
        return ret;
    }

    class SDGenstate : public SubdocGeneratorState
    {
      public:
        SDGenstate(const std::vector< Doc > &docs) : m_pathix(0), m_docs(docs) {}

        void populateLookup(uint32_t seq, std::vector< SubdocSpec > &specs)
        {
            populate(seq, specs, false);
        }
        void populateMutate(uint32_t seq, std::vector< SubdocSpec > &specs)
        {
            populate(seq, specs, true);
        }

      private:
        void populate(uint32_t seq, std::vector< SubdocSpec > &specs, bool mutate)
        {
            const Doc &d = doc(seq);
            specs.resize(std::min(d.m_fields.size(), specs.size()));
            for (size_t ii = 0; ii < d.m_fields.size() && ii < specs.size(); ++ii) {
                const Doc::Field &f = d.m_fields[m_pathix++ % d.m_fields.size()];
                SubdocSpec &cur_spec = specs[ii];
                cur_spec.path = f.name();
                cur_spec.mutate = false;
                if (mutate) {
                    cur_spec.value = f.value();
                    cur_spec.mutate = true;
                }
            }
        }

        const Doc &doc(uint32_t seq) const
        {
            return m_docs[seq % m_docs.size()];
        }
        size_t m_pathix;
        const std::vector< Doc > &m_docs;
    };

  public:
    virtual std::unique_ptr<SubdocGeneratorState> createSubdocState(int, int) const
    {
        return std::unique_ptr<SubdocGeneratorState>(new SDGenstate(m_docs));
    }
};

struct TemplateSpec {
    std::string term;
    unsigned minval;
    unsigned maxval;
    bool sequential;
};

/**
 * Generate documents based on placeholder values. Each document (JSON or not)
 * may have one or more special replacement texts which can be substituted
 * with a random number
 */
class PlaceholderDocGenerator : public DocGeneratorBase
{
  public:
    /**
     * @param specs Placeholder specifications
     * @param inputs Documents to use for replacements
     */
    PlaceholderDocGenerator(const std::vector< std::string > &inputs, const std::vector< TemplateSpec > &specs)
    {

        initMatches(specs, inputs);
    }

  protected:
    PlaceholderDocGenerator() {}

    /**
     * Really belongs in constructor, but is decoupled for subclasses
     */
    void initMatches(const std::vector< TemplateSpec > &specs, const std::vector< std::string > &inputs)
    {

        using namespace Placeholders;

        for (std::vector< TemplateSpec >::const_iterator ii = specs.begin(); ii != specs.end(); ++ii) {
            Placeholders::Spec cur(ii->term, ii->minval, ii->maxval, ii->sequential);
            pl_specs.push_back(cur);
        }

        for (std::vector< std::string >::const_iterator ii = inputs.begin(); ii != inputs.end(); ++ii) {
            matches.push_back(new DocumentMatches(*ii, pl_specs));
        }
    }

  public:
    std::unique_ptr<GeneratorState> createState(int total, int cur) const
    {
        return std::unique_ptr<GeneratorState>(new MyState(this, total, cur));
    }

  private:
    class MyState : public GeneratorState
    {
      public:
        MyState(const PlaceholderDocGenerator *parent, int total, int cur) : m_parent(parent)
        {
            using namespace Placeholders;
            for (size_t ii = 0; ii < parent->matches.size(); ii++) {
                m_substs.push_back(Substitutions(parent->matches[ii], total, cur));
            }
            m_bufs.resize(m_substs.size());
        }

        void populateIov(uint32_t seq, std::vector< lcb_IOV > &iov_out)
        {
            using namespace Placeholders;
            size_t ix = seq % m_substs.size();
            Substitutions &subst = m_substs[ix];
            Substitutions::Backbuffer &buf = m_bufs[ix];
            subst.makeIovs(iov_out, buf);
        }

        std::vector< Placeholders::Substitutions::Backbuffer > m_bufs;
        std::vector< Placeholders::Substitutions > m_substs;
        const PlaceholderDocGenerator *m_parent;
    };

    // Match object for each doc
    std::vector< Placeholders::DocumentMatches * > matches;
    std::vector< Placeholders::Spec > pl_specs;
};

/**
 * Generate documents based on JSON fields. This adds on top of the normal
 * document generator in that JSON paths are used and explicit placeholders
 * are not required
 */
class PlaceholderJsonGenerator : public PlaceholderDocGenerator
{
  public:
    /**
     * @param specs List of specs. The term in the spec refers to the field
     * which is to be replaced, not the placeholder text
     * @param documents The documents to operate on
     */
    PlaceholderJsonGenerator(const std::vector< std::string > &documents, const std::vector< TemplateSpec > &specs)
    {

        initJsonPlaceholders(specs, documents);
    }

    /**
     * Generate the documents, and then generate specs for them
     * @param specs The specs to use
     * @param minsz Minimum document size
     * @param maxsz Maximum document size
     */
    PlaceholderJsonGenerator(uint32_t minsz, uint32_t maxsz, const std::vector< TemplateSpec > &specs, int rnd)
    {

        std::vector< std::string > jsondocs;
        JsonDocGenerator::genDocuments(minsz, maxsz, jsondocs, rnd);
        initJsonPlaceholders(specs, jsondocs);
    }

  private:
    void initJsonPlaceholders(const std::vector< TemplateSpec > &specs, const std::vector< std::string > &documents)
    {

        int serial = 0;
        Json::Reader reader;
        Json::FastWriter writer;
        std::vector< TemplateSpec > new_specs;
        std::vector< std::string > new_docs;

        for (size_t ii = 0; ii < documents.size(); ii++) {
            Json::Value root;
            if (!reader.parse(documents[ii], root)) {
                throw std::runtime_error("Couldn't parse one or more documents!");
            }

            for (size_t jj = 0; jj < specs.size(); ++jj) {
                char buf[64];
                const TemplateSpec &spec = specs[jj];
                sprintf(buf, "$__pillowfight_%d", serial++);
                root[spec.term] = buf;
                TemplateSpec new_spec = spec;

                std::string replace_term(buf);
                replace_term = '"' + replace_term + '"';
                new_spec.term = replace_term;
                new_specs.push_back(new_spec);
            }
            new_docs.push_back(writer.write(root));
        }
        initMatches(new_specs, new_docs);
    }
};

} // namespace Pillowfight


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
Pixel
</TITLE>

<META NAME="date" CONTENT="2015-04-25">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

Class Pixel

java.lang.Object
  Pixel

public class Pixel
extends java.lang.Object

Pixel - this class represents a Pixel object and contains sattic methods to manipulate Pixels

Version:

1.0

Author:

Dillon Hammond

Constructor Summary

Pixel(java.awt.Color color)

          Class constructor defines the Color of a new Pixel object

Method Summary

static void
convertToBlackAndWhite(java.util.ArrayList<java.util.ArrayList<Pixel>> image)

          convertToBlackAndWhite - A method to convert an image to Black and White

static boolean
equals(Pixel pxA,
       Pixel pxB)

          equals = A method to determine if two Pixels are equal

static java.util.ArrayList<java.util.ArrayList<java.util.ArrayList<Pixel>>>
extractCharacters(java.util.ArrayList<java.util.ArrayList<java.util.ArrayList<Pixel>>> lines)

          extractCharacters - A method to extract individual characters from lines of text

static int
getBlue(Pixel px)

          getBlue - gets the Blue value form a Pixel's color

static java.awt.Color
getColor(Pixel px)

          getColor - A method to get the Color of a pixel

static int
getGreen(Pixel px)

          getGreen - gets the Green value form a Pixel's color

static int
getHeight(java.util.ArrayList<java.util.ArrayList<Pixel>> image)

          getHeight - A method to return the height of an image

static int
getRed(Pixel px)

          getRed - gets the Red value form a Pixel's color

static int
getSize(java.util.ArrayList<java.util.ArrayList<Pixel>> image)

          getSize - A method to return the total size (length*width) of an image

static int
getWidth(java.util.ArrayList<java.util.ArrayList<Pixel>> image)

          getWidth - A method to return the width of an image

static java.util.ArrayList<java.util.ArrayList<java.util.ArrayList<Pixel>>>
normalizeCharacters(java.util.ArrayList<java.util.ArrayList<java.util.ArrayList<Pixel>>> characters)

          normalizeCharacters - A method to convert ever character to a new image of specific dimensions

static java.util.ArrayList<java.util.ArrayList<java.util.ArrayList<Pixel>>>
seperateByLines(java.util.ArrayList<java.util.ArrayList<Pixel>> image)

          seperateByLines - A method to seperate an image into several, smaller images that are a line of text form image

static void
setColor(Pixel px,
         java.awt.Color newColor)

          setColor - Set a new Color object for a Pixel

 java.lang.String
toString()

          toString - A method to define how a Pixel object is printed as String output

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

Pixel

public Pixel(java.awt.Color color)

Class constructor defines the Color of a new Pixel object

Parameters:
color - the color to set the Pixel to

Method Detail

convertToBlackAndWhite

public static void convertToBlackAndWhite(java.util.ArrayList<java.util.ArrayList<Pixel>> image)

convertToBlackAndWhite - A method to convert an image to Black and White

Parameters:
image - the image to be converted to black and white

equals

public static boolean equals(Pixel pxA,
                             Pixel pxB)

equals = A method to determine if two Pixels are equal

Parameters:
pxA - - The first Pixel
pxB - - The second Pixel

Returns:
boolean True if the Color of pxA matches the Color of pxB, false otherwise

extractCharacters

public static java.util.ArrayList<java.util.ArrayList<java.util.ArrayList<Pixel>>> extractCharacters(java.util.ArrayList<java.util.ArrayList<java.util.ArrayList<Pixel>>> lines)

extractCharacters - A method to extract individual characters from lines of text

Parameters:
lines - An ArrayList of images that are lines of text

Returns:
ArrayList<ArrayList<ArrayList<Pixel>>> An ArrayList of images that are single characters

getBlue

public static int getBlue(Pixel px)

getBlue - gets the Blue value form a Pixel's color

Parameters:
px - The Pixel to inspect

Returns:
int the value of px's blue channel

getColor

public static java.awt.Color getColor(Pixel px)

getColor - A method to get the Color of a pixel

Parameters:
px - The Pixel to get the color of

Returns:
Color the Color object associated with px

getGreen

public static int getGreen(Pixel px)

getGreen - gets the Green value form a Pixel's color

Parameters:
px - The Pixel to inspect

Returns:
int the value of px's green channel

getHeight

public static int getHeight(java.util.ArrayList<java.util.ArrayList<Pixel>> image)

getHeight - A method to return the height of an image

Parameters:
ArrayList<ArrayList<Pixel>> - The image to get the height of

Returns:
int The height of image

getRed

public static int getRed(Pixel px)

getRed - gets the Red value form a Pixel's color

Parameters:
px - The Pixel to inspect

Returns:
int the value of px's red channel

getSize

public static int getSize(java.util.ArrayList<java.util.ArrayList<Pixel>> image)

getSize - A method to return the total size (length*width) of an image

Parameters:
ArrayList<ArrayList<Pixel>> - The image to get the size of

Returns:
int The total size of image

getWidth

public static int getWidth(java.util.ArrayList<java.util.ArrayList<Pixel>> image)

getWidth - A method to return the width of an image

Parameters:
ArrayList<ArrayList<Pixel>> - The image to get the width of

Returns:
int The width of image

normalizeCharacters

public static java.util.ArrayList<java.util.ArrayList<java.util.ArrayList<Pixel>>> normalizeCharacters(java.util.ArrayList<java.util.ArrayList<java.util.ArrayList<Pixel>>> characters)

normalizeCharacters - A method to convert ever character to a new image of specific dimensions

Parameters:
characters - An ArrayList of images that are characters

Returns:
ArrayList<ArrayList<ArrayList<Pixel>>> An ArrayList of images that are now uniform sized characters

seperateByLines

public static java.util.ArrayList<java.util.ArrayList<java.util.ArrayList<Pixel>>> seperateByLines(java.util.ArrayList<java.util.ArrayList<Pixel>> image)

seperateByLines - A method to seperate an image into several, smaller images that are a line of text form image

Parameters:
image - - The original, entire image to extract lines of text from

Returns:
ArrayList<ArrayList<ArrayList<Pixel>>> An ArrayList of images, each of which is a line of black text

setColor

public static void setColor(Pixel px,
                            java.awt.Color newColor)

setColor - Set a new Color object for a Pixel

Parameters:
px - the Pixel to change
newColor - the new Color that px will have

toString

public java.lang.String toString()

toString - A method to define how a Pixel object is printed as String output

Overrides:
toString in class java.lang.Object

Returns:
String The String indicating the Color of a Pixel


text:
using System;
using System.Data;

namespace Catnap.Database
{
    public interface IDbAdapter
    {
        IDbConnection CreateConnection(string connectionString);
        IDbCommand CreateLastInsertIdCommand(string tableName, IDbCommandFactory commandFactory);
        IDbCommand CreateGetTableMetadataCommand(string tableName, IDbCommandFactory commandFactory);
        object ConvertToDb(object value);
        object ConvertFromDb(object value, Type toType);
        string FormatParameterName(string name);
        string Quote(string name);
        string GetGeneralStringType();
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<imageIndex>
  <image>
    <originalFileName>IMG_2085.JPG</originalFileName>
    <size>1448750</size>
    <dateLastModified>Tue, 19 Nov 2013 06:01:11 GMT</dateLastModified>
    <width>3888</width>
    <height>2592</height>
    <cachedImage>
      <fileName>4zmeuhzv.jpeg</fileName>
      <dateCreated>Tue, 19 Nov 2013 06:08:43 GMT</dateCreated>
      <dateLastAccessed>Tue, 10 Mar 2015 05:04:20 GMT</dateLastAccessed>
      <imageFormat>jpeg</imageFormat>
      <compression>90</compression>
      <width>100</width>
      <height>67</height>
      <bgColor>#FFFFFF</bgColor>
      <transparent>True</transparent>
      <border>0</border>
      <borderColor>#000000</borderColor>
      <constrain>True</constrain>
      <pad>False</pad>
    </cachedImage>
    <cachedImage>
      <fileName>lxwshdjz.jpeg</fileName>
      <dateCreated>Tue, 19 Nov 2013 09:32:36 GMT</dateCreated>
      <dateLastAccessed>Mon, 16 Mar 2015 14:49:34 GMT</dateLastAccessed>
      <imageFormat>jpeg</imageFormat>
      <compression>90</compression>
      <width>600</width>
      <height>400</height>
      <bgColor>#FFFFFF</bgColor>
      <transparent>True</transparent>
      <border>0</border>
      <borderColor>#000000</borderColor>
      <constrain>True</constrain>
      <pad>False</pad>
    </cachedImage>
    <cachedImage>
      <fileName>ak3oqhtb.jpeg</fileName>
      <dateCreated>Wed, 12 Mar 2014 13:33:46 GMT</dateCreated>
      <dateLastAccessed>Tue, 13 Jan 2015 20:52:24 GMT</dateLastAccessed>
      <imageFormat>jpeg</imageFormat>
      <compression>90</compression>
      <width>3888</width>
      <height>2592</height>
      <bgColor>#FFFFFF</bgColor>
      <transparent>True</transparent>
      <border>0</border>
      <borderColor>#000000</borderColor>
      <constrain>False</constrain>
      <pad>False</pad>
    </cachedImage>
  </image>
</imageIndex>


text:
<?xml version="1.0"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->

<metainfo>
  <schemaVersion>2.0</schemaVersion>
  <services>
    <service>
      <name>ELASTICSEARCH</name>
      <displayName>ElasticSearch</displayName>
      <comment>A distributed, highly available, RESTful search engine</comment>
      <version>1.7.5</version>
      <components>

        <component>
          <name>ELASTICSEARCH</name>
          <displayName>ElasticSearch</displayName>
          <category>MASTER</category>
          <cardinality>1+</cardinality>
          <commandScript>
            <script>scripts/es_handler.py</script>
            <scriptType>PYTHON</scriptType>
            <timeout>600</timeout>
          </commandScript>
        </component>

        <component>
          <name>ELASTICSEARCH_INDEXER</name>
          <displayName>es_indexer</displayName>
          <category>SLAVE</category>
          <cardinality>1+</cardinality>
          <commandScript>
            <script>scripts/es_handler_slave.py</script>
            <scriptType>PYTHON</scriptType>
            <timeout>600</timeout>
          </commandScript>
        </component>
      </components>

      <configFile>
        <type>xml</type>
        <fileName>elasticsearch.xml</fileName>
        <dictionaryName>elasticsearch</dictionaryName>
      </configFile>

      <osSpecifics>
        <osSpecific>
          <osFamily>any</osFamily>
          <packages>
            <package>
              <name>elasticsearch</name>
            </package>
            <package>
              <name>python-requests</name>
            </package>
          </packages>
        </osSpecific>
      </osSpecifics>

      <commandScript>
        <script>scripts/service_check.py</script>
        <scriptType>PYTHON</scriptType>
        <timeout>600</timeout>
      </commandScript>

    </service>

    <configuration-dependencies>
      <config-type>elasticsearch</config-type>
    </configuration-dependencies>
  </services>
</metainfo>


text:
namespace Azure.ResourceManager.HealthcareApis.Models
{
    /// <summary> An Open Container Initiative (OCI) artifact. </summary>
    public partial class HealthcareApisServiceOciArtifactEntry
    {
        /// <summary> Initializes a new instance of HealthcareApisServiceOciArtifactEntry. </summary>
        public HealthcareApisServiceOciArtifactEntry()
        {
        }

        /// <summary> Initializes a new instance of HealthcareApisServiceOciArtifactEntry. </summary>
        /// <param name="loginServer"> The Azure Container Registry login server. </param>
        /// <param name="imageName"> The artifact name. </param>
        /// <param name="digest"> The artifact digest. </param>
        internal HealthcareApisServiceOciArtifactEntry(string loginServer, string imageName, string digest)
        {
            LoginServer = loginServer;
            ImageName = imageName;
            Digest = digest;
        }

        /// <summary> The Azure Container Registry login server. </summary>
        public string LoginServer { get; set; }
        /// <summary> The artifact name. </summary>
        public string ImageName { get; set; }
        /// <summary> The artifact digest. </summary>
        public string Digest { get; set; }
    }
}


text:
export function extractLineDescription(comment: string): string {
	let description = comment.trim();

	// Remove unicode version
	description = description.replace(/^V?([\d.]+)/, '');

	// Remove range
	description = description.replace(/\[\d+]/, '');

	// Remove example emojis
	description = description.replace(/\(*.+\)/, '');

	return description.toLowerCase().trim();
}


text:
package com.nukesz.mariobros.screens;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.nukesz.mariobros.MarioBros;

public class GameOverScreen implements Screen {

    private final Viewport viewport;
    private final Stage stage;
    private final Game game;

    public GameOverScreen(final Game game) {
        this.game = game;
        viewport = new FitViewport(MarioBros.V_WIDTH, MarioBros.V_HEIGHT, new OrthographicCamera());
        stage = new Stage(viewport, ((MarioBros) game).batch);

        final LabelStyle font = new Label.LabelStyle(new BitmapFont(), Color.WHITE);

        final Table table = new Table();
        table.center();
        table.setFillParent(true);

        final Label gameOverLabel = new Label("GAME OVER", font);
        final Label playAgainLabel = new Label("Click to Play again", font);

        table.add(gameOverLabel).expandX();
        table.row();
        table.add(playAgainLabel).expandX().padTop(10f);

        stage.addActor(table);
    }

    @Override
    public void show() {

    }

    @Override
    public void render(final float delta) {
        if (Gdx.input.justTouched()) {
            game.setScreen(new PlayScreen((MarioBros) game));
            dispose();
        }
        Gdx.gl.glClearColor(0, 0, 0, 1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        stage.draw();
    }

    @Override
    public void resize(final int width, final int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        stage.dispose();
    }

}


text: Your comment has been held for moderation. Thank you.