text:
import React from 'react';
import {Container, Row, Col, Card} from '../../src/Grid';
import styles from './ExampleGrid.scss';

import TextField from '../../src/TextField';
import Input from '../../src/Input';
import Label from '../../src/Label';
import ToggleSwitch from '../../src/ToggleSwitch';
import {Animator} from 'wix-animations';

function renderStandardInput() {
  return (
    <TextField>

        Text Field

      <Input
        id="textField"
        placeholder="Default text goes"
        />
    </TextField>
  );
}

class ExampleGridAnimation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {show: true};
  }

  render() {
    return (

        <ToggleSwitch checked={this.state.show} onChange={() => this.setState({show: !this.state.show})}/> Show/Hide
        grid container

      <Container>
        <Animator
          opacity
          sequence
          show={this.state.show}
          translate={{enter: {direction: 'top', size: '10%'}, exit: {direction: 'bottom', size: '10%'}}}
          timing="large"
          >
          <Row>
            <Col span={4}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
            <Col span={4}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
            <Col span={4}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
          </Row>
          <Row>
            <Col span={3}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
            <Col span={3}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
            <Col span={3}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
            <Col span={3}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
          </Row>
          <Row>
            <Col span={4}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
            <Col span={4}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
            <Col span={4}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
          </Row>
          <Row>
            <Col span={3}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
            <Col span={3}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
            <Col span={3}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
            <Col span={3}>
              <Card>
                <Card.LinkHeader linkTo="http://www.wix.com/" linkTitle="Link to Wix" title="Card with link"/>
                <Card.Content>
                  <Row>
                    <Col span={12}>
                      {renderStandardInput()}
                    </Col>
                  </Row>
                </Card.Content>
              </Card>
            </Col>
          </Row>
        </Animator>
      </Container>

);
  }
}

export default () =>
  <ExampleGridAnimation/>;


text:
#ifndef MIKUS_LUCIA_MAIGUI_H
#define MIKUS_LUCIA_MAIGUI_H
#include <Lucia/Collider/Collider.h>
#include <Lucia/Collider/Manager.h>

#include <Lucia/Collider/Shape/Ray.h>
#include <Lucia/Maths/Vec2.h>

namespace Lucia {
namespace Maigui
{
    typedef unsigned int uint;
    // here we have a multiple inheritance:
    /*
    *                   Item [Abstract base class]
    *                    |
    *           +--------+-------+
    *           |        |       |
    *       Container  Widget   Abstract
    *           |        |           |
    *     --+---+-      -+----+     -+ Tooltip
    *       |   |        |    |
    *     Frame Plate  Button Slider
    */
    using Collider::Shape;

    using namespace Maths;
    enum mouseButton{
        left,
        right,
        middle
    };
    class Skin;

    class Manager;
    class Item; // abstract class for internal use only.

    class Container;
    class Widget;
    class Abstract;

    class Button;

    namespace Widgets
    {
        class Button;
        class Slider;
    };
    namespace Containers
    {
        class Frame;
        class Plate;
    };
    namespace Internal
    {
        class Tooltip;
    };
    namespace Default
    {
        extern shared_ptr<Skin> Skin;
        extern bool formed;
        void form();
    }
    //settings
    namespace Sizes
    {
        extern float FrameBorder;
    }
};
}
#endif // MIKUS_MAIGUI_H

redpajama_set_name: RedPajamaGithub


text:
CLOC_LABEL = "Gitlab"
CODE_PATH = "/data/gitlab/git-data/repositories"
CODE_EXPORT = "/data/code_export/"
# JSON_REPORT = "{0}{1}.json".format(CODE_EXPORT,CLOC_LABEL)
JSON_REPORT = 'Gitlab.json'
CLOC_RUN_PATH = "/data/cloc-1.66.pl"

from deploy_config import *


text:
(function($){
	$.fn.makePlayersList = function(options) {
		// Merge passed options with defaults
	    var opts = $.extend({}, $.fn.makePlayersList.defaults, options);

		var context = {options:opts, element:this};

		return this.each(function() {
			if (opts.gameName != ""){
				var gameManager = opts.gameManager;

				if (gameManager == null){
					gameManager = new TLVIVI.Pacman.GameManager();
				}

				gameManager.getGamePlayers(opts.gameName, $.proxy(_onGetDataBack, context));
			}
		 });
	 };

	 function _onGetDataBack(response){
		 var itemTemplate = "

";
		 var listContainer = this.element;
		 listContainer.empty();

		 $.each(response, function(index, value){
			 var currPlayer = $(itemTemplate);

			 if (value.Role == 1){
				 $("img", currPlayer).attr("src", "/images/pacman.gif");
			 }
			 else if (value.Role == 2){
				 $("img", currPlayer).attr("src", "/images/monster.gif");
			 }

			 $("span", currPlayer).text(value.Name);

			 if (value.Role == 1 || value.Role == 2){
				 listContainer.append(currPlayer);
			 }
		 });
	 }

	// makeBigAppList plugin default options
	  $.fn.makePlayersList.defaults = {
		gameManager: null,
	    gameName: "",
	    selfId: -1,
	    showSelf: false
	  };

})(jQuery);


text:
try:
  import oauth2 as oauth
except:
  oauth = None

import cgi
import logging
import urllib
from datetime import datetime

from axes.decorators import watch_login
import django.contrib.auth.views
from django.core import urlresolvers
from django.core.exceptions import SuspiciousOperation
from django.contrib.auth import login, get_backends, authenticate
from django.contrib.auth.models import User
from django.contrib.sessions.models import Session
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext as _

from desktop.auth import forms as auth_forms
from desktop.lib.django_util import render
from desktop.lib.django_util import login_notrequired
from desktop.lib.django_util import JsonResponse
from desktop.log.access import access_warn, last_access_map
from desktop.conf import LDAP, OAUTH, DEMO_ENABLED

from hadoop.fs.exceptions import WebHdfsException
from useradmin.models import get_profile
from useradmin.views import ensure_home_directory, require_change_password

LOG = logging.getLogger(__name__)

def get_current_users():
  """Return dictionary of User objects and
  a dictionary of the user's IP address and last access time"""
  current_users = { }
  for session in Session.objects.all():
    try:
      uid = session.get_decoded().get(django.contrib.auth.SESSION_KEY)
    except SuspiciousOperation:
      # If secret_key changed, this resolution won't work.
      uid = None

    if uid is not None:
      try:
        userobj = User.objects.get(pk=uid)
        current_users[userobj] = last_access_map.get(userobj.username, { })
      except User.DoesNotExist:
        LOG.debug("User with id=%d does not exist" % uid)

  return current_users

def first_login_ever():
  backends = get_backends()
  for backend in backends:
    if hasattr(backend, 'is_first_login_ever') and backend.is_first_login_ever():
      return True
  return False

def get_backend_names():
  return get_backends and [backend.__class__.__name__ for backend in get_backends()]

@login_notrequired
@watch_login
def dt_login(request, from_modal=False):
  redirect_to = request.REQUEST.get('next', '/')
  is_first_login_ever = first_login_ever()
  backend_names = get_backend_names()
  is_active_directory = 'LdapBackend' in backend_names and ( bool(LDAP.NT_DOMAIN.get()) or bool(LDAP.LDAP_SERVERS.get()) )

  if is_active_directory:
    UserCreationForm = auth_forms.LdapUserCreationForm
    AuthenticationForm = auth_forms.LdapAuthenticationForm
  else:
    UserCreationForm = auth_forms.UserCreationForm
    AuthenticationForm = auth_forms.AuthenticationForm

  if request.method == 'POST':
    request.audit = {
      'operation': 'USER_LOGIN',
      'username': request.POST.get('username')
    }

    # For first login, need to validate user info!
    first_user_form = is_first_login_ever and UserCreationForm(data=request.POST) or None
    first_user = first_user_form and first_user_form.is_valid()

    if first_user or not is_first_login_ever:
      auth_form = AuthenticationForm(data=request.POST)

      if auth_form.is_valid():
        # Must login by using the AuthenticationForm.
        # It provides 'backends' on the User object.
        user = auth_form.get_user()
        userprofile = get_profile(user)

        login(request, user)

        if request.session.test_cookie_worked():
          request.session.delete_test_cookie()

        auto_create_home_backends = ['AllowAllBackend', 'LdapBackend', 'SpnegoDjangoBackend']
        if is_first_login_ever or any(backend in backend_names for backend in auto_create_home_backends):
          # Create home directory for first user.
          try:
            ensure_home_directory(request.fs, user.username)
          except (IOError, WebHdfsException), e:
            LOG.error(_('Could not create home directory.'), exc_info=e)
            request.error(_('Could not create home directory.'))

        if require_change_password(userprofile):
          return HttpResponseRedirect(urlresolvers.reverse('useradmin.views.edit_user', kwargs={'username': user.username}))

        userprofile.first_login = False
        userprofile.last_activity = datetime.now()
        userprofile.save()

        msg = 'Successful login for user: %s' % user.username
        request.audit['operationText'] = msg
        access_warn(request, msg)
        if from_modal or request.REQUEST.get('fromModal', 'false') == 'true':
          return JsonResponse({'auth': True})
        else:
          return HttpResponseRedirect(redirect_to)
      else:
        request.audit['allowed'] = False
        msg = 'Failed login for user: %s' % request.POST.get('username')
        request.audit['operationText'] = msg
        access_warn(request, msg)
        if from_modal or request.REQUEST.get('fromModal', 'false') == 'true':
          return JsonResponse({'auth': False})

  else:
    first_user_form = None
    auth_form = AuthenticationForm()

  if DEMO_ENABLED.get() and not 'admin' in request.REQUEST:
    user = authenticate(username=request.user.username, password='HueRocks')
    login(request, user)
    ensure_home_directory(request.fs, user.username)
    return HttpResponseRedirect(redirect_to)

  if not from_modal:
    request.session.set_test_cookie()

  renderable_path = 'login.mako'
  if from_modal:
    renderable_path = 'login_modal.mako'

  return render(renderable_path, request, {
    'action': urlresolvers.reverse('desktop.auth.views.dt_login'),
    'form': first_user_form or auth_form,
    'next': redirect_to,
    'first_login_ever': is_first_login_ever,
    'login_errors': request.method == 'POST',
    'backend_names': backend_names,
    'active_directory': is_active_directory
  })

def dt_logout(request, next_page=None):
  """Log out the user"""
  username = request.user.get_username()
  request.audit = {
    'username': username,
    'operation': 'USER_LOGOUT',
    'operationText': 'Logged out user: %s' % username
  }
  backends = get_backends()
  if backends:
    for backend in backends:
      if hasattr(backend, 'logout'):
        response = backend.logout(request, next_page)
        if response:
          return response

  return django.contrib.auth.views.logout(request, next_page)

def profile(request):
  """
  Dumps JSON for user-profile information.
  """
  return render(None, request, _profile_dict(request.user))

def _profile_dict(user):
  return dict(
    username=user.username,
    first_name=user.first_name,
    last_name=user.last_name,
    last_login=str(user.last_login), # datetime object needs to be converted
    email=user.email)

# OAuth is based on Twitter as example.

@login_notrequired
def oauth_login(request):
  assert oauth is not None

  consumer = oauth.Consumer(OAUTH.CONSUMER_KEY.get(), OAUTH.CONSUMER_SECRET.get())
  client = oauth.Client(consumer)
  resp, content = client.request(OAUTH.REQUEST_TOKEN_URL.get(), "POST", body=urllib.urlencode({
                      'oauth_callback': 'http://' + request.get_host() + '/login/oauth_authenticated/'
                  }))

  if resp['status'] != '200':
    raise Exception(_("Invalid response from OAuth provider: %s") % resp)

  request.session['request_token'] = dict(cgi.parse_qsl(content))

  url = "%s?oauth_token=%s" % (OAUTH.AUTHENTICATE_URL.get(), request.session['request_token']['oauth_token'])

  return HttpResponseRedirect(url)

@login_notrequired
def oauth_authenticated(request):
  consumer = oauth.Consumer(OAUTH.CONSUMER_KEY.get(), OAUTH.CONSUMER_SECRET.get())
  token = oauth.Token(request.session['request_token']['oauth_token'], request.session['request_token']['oauth_token_secret'])
  client = oauth.Client(consumer, token)

  resp, content = client.request(OAUTH.ACCESS_TOKEN_URL.get(), "GET")
  if resp['status'] != '200':
      raise Exception(_("Invalid response from OAuth provider: %s") % resp)

  access_token = dict(cgi.parse_qsl(content))

  user = authenticate(access_token=access_token)
  login(request, user)

  redirect_to = request.REQUEST.get('next', '/')
  return HttpResponseRedirect(redirect_to)


text:
FROM debian:10

RUN apt-get update && apt-get install -y curl nginx

RUN mkdir -p -m 777 /var/log/kraken/kraken-build-index
RUN mkdir -p -m 777 /var/cache/kraken/kraken-build-index
RUN mkdir -p -m 777 /var/run/kraken

ARG USERNAME="root"
ARG USERID="0"
RUN if [ ${USERID} != "0" ]; then useradd --uid ${USERID} ${USERNAME}; fi

COPY ./docker/setup_nginx.sh /tmp/setup_nginx.sh
RUN /tmp/setup_nginx.sh ${USERNAME}

USER ${USERNAME}

COPY ./build-index/build-index /usr/bin/kraken-build-index
COPY ./config /etc/kraken/config
COPY ./nginx/config /etc/kraken-build-index/nginx/config
COPY ./localdb/migrations /etc/kraken-build-index/localdb/migrations
COPY ./test/tls /etc/kraken/tls

WORKDIR /etc/kraken-build-index


text:
/**
 * Поисковое поле по названию.
 *
 * @author dew1983@mail.ru <Suvorov Andrey M.>
 */

Ext.define(
	'FBEditor.view.form.desc.sequence.search.name.Name',
	{
		extend: 'FBEditor.view.form.desc.searchField.SearchField',
		requires: [
			'FBEditor.view.form.desc.sequence.search.name.NameController',
			'FBEditor.view.form.desc.sequence.search.name.window.Window'
		],
		controller: 'form.desc.sequence.search.name',
		xtype: 'form-desc-sequence-searchName',

		createWindow: function ()
		{
			var me = this,
				win;

			win = Ext.create(
				{
					xtype: 'form-desc-sequence-searchName-window',
					alignTarget: me.getId()
				}
			);

			return win;
		},

		search: function ()
		{
			var me = this,
				val = me.getValue(),
				win = me.getWindow(),
				params = me.getParams();

			if (val.length > 1)
			{
				win.fireEvent('loadData', params);
			}
			else
			{
				me.abortSearch();
			}
		},

		getParams: function ()
		{
			var me = this,
				val = me.getValue(),
				params;

			// параметры запроса зависят от введенного значения

			if (/^[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$/.test(val))
			{
				params = {
					uuid: val
				};
			}
			else if (/^[0-9]{2,}$/.test(val))
			{
				params = {
					series: val
				};
			}
			else
			{
				params = {
					q: val
				};
			}

			return params;
		},

		updateData: function (data)
		{
			var me = this,
				descManager = FBEditor.desc.Manager,
				btn,
				d,
				container;

			container = me.up('[name=plugin-fieldcontainerreplicator]');
			d = {
				'sequence-id': data.uuid,
				'sequence-title-main': data['name'] ? data['name'] : ''
			};

			// заполняем форму ручного ввода
			descManager.loadingProcess = true;
			container.updateData(d);
			descManager.loadingProcess = false;

			// убираем редактируемость полей
			container.fireEvent('editable', false);

			// восстанавливаем редактируемость поля номера
			container.down('numberfield').setEditable(true);

			// скрываем поля поиска и показываем данные
			btn = me.up('desc-fieldcontainer').down('form-desc-sequence-customBtn');
			btn.switchContainers();
		},

		getFirstSearch: function ()
		{
			var me = this,
				searchField;

			searchField = me.up('form-desc-sequence').down('form-desc-sequence-searchName');

			return searchField;
		},

		getNextSearch: function ()
		{
			var me = this,
				searchField,
				next;

			next = me.up('[plugins]').nextSibling();
			searchField = next ? next.down('form-desc-sequence-searchName') : null;

			return searchField;
		}
	}
);


text:
<TITLE>Review for Flatliners (1990)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Flatliners (1990)

reviewed by
Mark R. Leeper

                                  FLATLINERS
                       A film review by Mark R. Leeper
                        Copyright 1990 Mark R. Leeper

          Capsule review:  An original and hypnotic horror film.
     The music, the acting, the photography, and the script all
     get very high marks.  It is a horror film with intelligent
     characters who do things rather than have things done to
     them.  Strong on atmosphere and intriguing in ideas.  Rating:
     high +2.

     Horror films tend to be very derivative.  They take many of the same
themes and rework them over and over.  How different is FRIGHT NIGHT from
DRACULA really?  It is very rare for me to come out of a horror film feeling
I had seen something really new for the horror film.  And, be warned,
usually when I feel have seen something new, most audiences do not like the
films.  In the last ten years there have been five horror films I have liked
in this way.  They are SOMETHING WICKED THIS WAY COMES, LIFEFORCE, PRINCE OF
DARKNESS, LADY IN WHITE, and now FLATLINERS.  FLATLINERS is a mesmerizing
horror thriller about life and death and redemption.  From about two minutes
into the film I was constantly anxious to find out what happens next.  And
when it did happen, I was never disappointed but still never appeased.

     A group of medical students are fascinated by the  brink-of-death
experience that some of their patients have had.  But their curiosity
certainly goes beyond just collecting other peoples' accounts second-hand.
As long as they have the ability to induce death and to bring people back,
why wait for it to happen by chance and to other people.  Why not go off
exploring the undiscovered country for themselves.  As one student says of
the quest to know what is beyond death, "Philosophy failed.  Religion
failed.  Now it's time for medical science to try."  So one tries it and is
brought back  But now things seem different to him and reality is not quite
the same.

     At least in theme FLATLINERS is reminiscent of some of the classic old
Karloff films like Michael Curtiz's THE WALKING DEAD, and where that film
was a little pat in its description of life after death (Karloff just had
time to describe it as "peace" before dying a second time, and more
permanently), this film is only a little less pat in other ways in its
"meaning of death."  However, it is not concentrating so much on what the
other side looks like as on what it is like to have been there and be back.

     This is a movie to see in a theater; it will lose a lot of its visual
impact on the small screen.  Almost the entire film is shot in either
twilight half-tones or at night.  The medical school has got to be the most
baroque in the world.  It would have done credit to any 1930s
expressionistic horror film.  Its architecture is almost gothic with immense
vaulting rooms; dark, dismal corridors; labs with immense statue heads as if
gods were looking on.  Director Joel Schumacher's previous THE LOST BOYS had
little to recommend it but atmosphere.  This time he has better atmosphere
and a far more compelling story to tell.

     Kiefer Sutherland (of LOST BOYS) plays Nelson, who is exploring death
partially for curiosity and partially for glory.  Julia Roberts is Rachel,
who has her own private demons to face.  Roberts has the best developed
character.  Keith Bacon is Davis, who is just a little too good to be true.
Alec Baldwin's younger brother William plays Joe, whose story is somewhat
less interesting than the others and could by itself have been an episode of
"The Hitchhiker."

     FLATLINERS is intelligently filmed and written.  It has irony but
happily not apparently tongue-in-cheek.  In short, it deserves to be a
classic horror film and may well make it.  I rate it a high +2 on the -4 to
+4 scale.

                                        Mark R. Leeper
                                        att!mtgzx!leeper
                                        leeper@mtgzx.att.com
.

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
namespace favicon_base {

// Styling specifications of a fallback icon. The icon is composed of a solid
// rounded square containing a single letter. The specification excludes the
// icon URL and size, which are given when the icon is rendered.
struct FallbackIconStyle {
  FallbackIconStyle();
  ~FallbackIconStyle();

  // If any member changes, also update FallbackIconStyleBuilder.

  // Icon background fill color.
  SkColor background_color;

  // Icon text color.
  SkColor text_color;

  // Ratio in [0.0, 1.0] of the text font size (pixels) to the icon size.
  double font_size_ratio;

  // The roundness of the icon's corners. 0 => square icon, 1 => circle icon.
  double roundness;

  bool operator==(const FallbackIconStyle& other) const;
};

// Reassigns |style|'s |text_color| to matches well against |background_color|.
void MatchFallbackIconTextColorAgainstBackgroundColor(FallbackIconStyle* style);

// Returns whether |style| values are within bounds.
bool ValidateFallbackIconStyle(const FallbackIconStyle& style);

// Set |style|'s background color to the dominant color of |bitmap_data|,
// clamping luminance down to a reasonable maximum value so that light text is
// readable.
void SetDominantColorAsBackground(
    const scoped_refptr<base::RefCountedMemory>& bitmap_data,
    FallbackIconStyle* style);

}  // namespace favicon_base

#endif  // COMPONENTS_FAVICON_BASE_FALLBACK_ICON_STYLE_H_


text:
package org.springframework.session.web.http;

import java.util.Collections;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionContext;

import org.springframework.session.ExpiringSession;

/**
 * Adapts Spring Session's {@link ExpiringSession} to an {@link HttpSession}.
 *
 * @param <S> the {@link ExpiringSession} type
 * @author Rob Winch
 * @since 1.1
 */
@SuppressWarnings("deprecation")
class ExpiringSessionHttpSession<S extends ExpiringSession> implements HttpSession {
	private S session;
	private final ServletContext servletContext;
	private boolean invalidated;
	private boolean old;

	ExpiringSessionHttpSession(S session, ServletContext servletContext) {
		this.session = session;
		this.servletContext = servletContext;
	}

	public void setSession(S session) {
		this.session = session;
	}

	public S getSession() {
		return this.session;
	}

	public long getCreationTime() {
		checkState();
		return this.session.getCreationTime();
	}

	public String getId() {
		return this.session.getId();
	}

	public long getLastAccessedTime() {
		checkState();
		return this.session.getLastAccessedTime();
	}

	public ServletContext getServletContext() {
		return this.servletContext;
	}

	public void setMaxInactiveInterval(int interval) {
		this.session.setMaxInactiveIntervalInSeconds(interval);
	}

	public int getMaxInactiveInterval() {
		return this.session.getMaxInactiveIntervalInSeconds();
	}

	public HttpSessionContext getSessionContext() {
		return NOOP_SESSION_CONTEXT;
	}

	public Object getAttribute(String name) {
		checkState();
		return this.session.getAttribute(name);
	}

	public Object getValue(String name) {
		return getAttribute(name);
	}

	public Enumeration<String> getAttributeNames() {
		checkState();
		return Collections.enumeration(this.session.getAttributeNames());
	}

	public String[] getValueNames() {
		checkState();
		Set<String> attrs = this.session.getAttributeNames();
		return attrs.toArray(new String[0]);
	}

	public void setAttribute(String name, Object value) {
		checkState();
		this.session.setAttribute(name, value);
	}

	public void putValue(String name, Object value) {
		setAttribute(name, value);
	}

	public void removeAttribute(String name) {
		checkState();
		this.session.removeAttribute(name);
	}

	public void removeValue(String name) {
		removeAttribute(name);
	}

	public void invalidate() {
		checkState();
		this.invalidated = true;
	}

	public void setNew(boolean isNew) {
		this.old = !isNew;
	}

	public boolean isNew() {
		checkState();
		return !this.old;
	}

	private void checkState() {
		if (this.invalidated) {
			throw new IllegalStateException(
					"The HttpSession has already be invalidated.");
		}
	}

	private static final HttpSessionContext NOOP_SESSION_CONTEXT = new HttpSessionContext() {
		public HttpSession getSession(String sessionId) {
			return null;
		}

		public Enumeration<String> getIds() {
			return EMPTY_ENUMERATION;
		}
	};

	private static final Enumeration<String> EMPTY_ENUMERATION = new Enumeration<String>() {
		public boolean hasMoreElements() {
			return false;
		}

		public String nextElement() {
			throw new NoSuchElementException("a");
		}
	};
}


text:
set -e
set -o pipefail
set -o xtrace

readonly aptGetCmd="sudo -E apt-get -y -qq"
readonly aptGetInstallCmd="${aptGetCmd} --no-install-suggests --no-install-recommends install"

#Before Install
if [ -z ${NIM_BRANCH+x} ]; then
	export NIM_BRANCH=master
fi
if [ -z ${USE_GCC+x} ]; then
	export USE_GCC=4.8
fi
if [ -z ${NIM_VERBOSITY+x} ]; then
	export NIM_VERBOSITY=0
fi
sudo -E add-apt-repository -y ppa:ubuntu-toolchain-r/test
${aptGetCmd} update
${aptGetInstallCmd} "gcc-${USE_GCC}" "g++-${USE_GCC}" git
sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-${USE_GCC} 10
sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-${USE_GCC} 10
sudo update-alternatives --set gcc "/usr/bin/gcc-${USE_GCC}"
sudo update-alternatives --set g++ "/usr/bin/g++-${USE_GCC}"
${aptGetCmd} autoremove
gcc --version

#Install
pushd .
mkdir -p toCache
readonly lDownloadPath=dl
mkdir -p ${lDownloadPath}

pushd ${lDownloadPath}

#Install UPX
readonly lUPXVersion=$(git ls-remote --tags "https://github.com/upx/upx.git" | awk '{print $2}' | grep -v '{}' | awk -F"/" '{print $3}' | tail -1 | sed "s/v//g")
curl -z upx.txz -o upx.txz -L https://github.com/upx/upx/releases/download/v${lUPXVersion}/upx-${lUPXVersion}-amd64_linux.tar.xz
tar -xvf upx.txz
export PATH
PATH="$(pwd)/upx-${lUPXVersion}-amd64_linux${PATH:+:$PATH}" || true

popd

compile() {
	./bin/nim c koch
	./koch boot -d:release
	./koch tools -d:release
}

readonly lNimAppPath=toCache/nim-${NIM_BRANCH}-${USE_GCC}
if [ ! -x ${lNimAppPath}/bin/nim ]; then
	git clone -b ${NIM_BRANCH} --depth 1 git://github.com/nim-lang/nim ${lNimAppPath}/
	pushd ${lNimAppPath}
	git clone --depth 1 git://github.com/nim-lang/csources csources/
	pushd csources
	sh build.sh
	popd
	rm -rf csources
	compile
	popd
else
	pushd ${lNimAppPath}
	git fetch origin
	if ! git merge FETCH_HEAD | grep "Already up-to-date"; then
		compile
	fi
	popd
fi
popd
rm -f nim.cfg
if [ "${NIM_TARGET_OS}" = "windows" ]; then
	echo "------------------------------------------------------------ targetOS: ${NIM_TARGET_OS}"
	rm -rdf ~/.wine
	${aptGetInstallCmd} mingw-w64 wine
	if [ "${NIM_TARGET_CPU}" = "i386" ]; then
		echo "------------------------------------------------------------ targetCPU: ${NIM_TARGET_CPU}"
		export WINEARCH=win32
		{
			echo i386.windows.gcc.path = \"/usr/bin\"
			echo i386.windows.gcc.exe = \"i686-w64-mingw32-gcc\"
			echo i386.windows.gcc.linkerexe = \"i686-w64-mingw32-gcc\"
			echo gcc.options.linker = \"\"
		} >nim.cfg
	else
		echo "------------------------------------------------------------ targetCPU: ${NIM_TARGET_CPU}"
		export WINEARCH=win64
		if [ "${NIM_TARGET_CPU}" = "amd64" ]; then
			{
				echo amd64.windows.gcc.path = \"/usr/bin\"
				echo amd64.windows.gcc.exe = \"x86_64-w64-mingw32-gcc\"
				echo amd64.windows.gcc.linkerexe = \"x86_64-w64-mingw32-gcc\"
				echo gcc.options.linker = \"\"
			} >nim.cfg
		fi
	fi
	wine hostname
else
	if [ "${NIM_TARGET_OS}" = "linux" ]; then
		echo "------------------------------------------------------------ targetOS: ${NIM_TARGET_OS}"
		if [ "${NIM_TARGET_CPU}" = "i386" ]; then
			echo "------------------------------------------------------------ targetCPU: ${NIM_TARGET_CPU}"
			${aptGetInstallCmd} gcc-${USE_GCC}-multilib g++-${USE_GCC}-multilib gcc-multilib g++-multilib
		fi
	fi
fi

#Before Script
export PATH
PATH="$(pwd)/${lNimAppPath}/bin${PATH:+:$PATH}" || true

#Script
nim Settings
nim CTest release


text:
#import <Foundation/Foundation.h>

@interface FRepoInfo : NSObject <NSCopying>

@property (nonatomic, readonly, strong) NSString* host;
@property (nonatomic, readonly, strong) NSString* namespace;
@property (nonatomic, strong) NSString* internalHost;
@property (nonatomic, readonly) bool secure;

- (id) initWithHost:(NSString*)host isSecure:(bool)secure withNamespace:(NSString*)namespace;

- (NSString *) connectionURLWithLastSessionID:(NSString*)lastSessionID;
- (NSString *) connectionURL;
- (void) clearInternalHostCache;
- (BOOL) isDemoHost;
- (BOOL) isCustomHost;

- (id)copyWithZone:(NSZone *)zone;
- (NSUInteger)hash;
- (BOOL)isEqual:(id)anObject;

@end


text:
define([
        'Cesium/Core/Cartesian3',
        'Cesium/Core/createWorldTerrain',
        'Cesium/Core/defined',
        'Cesium/Core/formatError',
        'Cesium/Core/Math',
        'Cesium/Core/objectToQuery',
        'Cesium/Core/queryToObject',
        'Cesium/DataSources/CzmlDataSource',
        'Cesium/DataSources/GeoJsonDataSource',
        'Cesium/DataSources/KmlDataSource',
        'Cesium/Scene/createTileMapServiceImageryProvider',
        'Cesium/Widgets/Viewer/Viewer',
        'Cesium/Widgets/Viewer/viewerCesiumInspectorMixin',
        'Cesium/Widgets/Viewer/viewerDragDropMixin',
        'domReady!'
    ], function(
        Cartesian3,
        createWorldTerrain,
        defined,
        formatError,
        CesiumMath,
        objectToQuery,
        queryToObject,
        CzmlDataSource,
        GeoJsonDataSource,
        KmlDataSource,
        createTileMapServiceImageryProvider,
        Viewer,
        viewerCesiumInspectorMixin,
        viewerDragDropMixin) {
    'use strict';

    /*
     Options parsed from query string:
       source=url          The URL of a CZML/GeoJSON/KML data source to load at startup.
                           Automatic data type detection uses file extension.
       sourceType=czml/geojson/kml
                           Override data type detection for source.
       flyTo=false         Don't automatically fly to the loaded source.
       tmsImageryUrl=url   Automatically use a TMS imagery provider.
       lookAt=id           The ID of the entity to track at startup.
       stats=true          Enable the FPS performance display.
       inspector=true      Enable the inspector widget.
       debug=true          Full WebGL error reporting at substantial performance cost.
       theme=lighter       Use the dark-text-on-light-background theme.
       scene3DOnly=true    Enable 3D only mode.
       view=longitude,latitude,[height,heading,pitch,roll]
                           Automatically set a camera view. Values in degrees and meters.
                           [height,heading,pitch,roll] default is looking straight down, [300,0,-90,0]
       saveCamera=false    Don't automatically update the camera view in the URL when it changes.
     */
    var endUserOptions = queryToObject(window.location.search.substring(1));

    var imageryProvider;
    if (defined(endUserOptions.tmsImageryUrl)) {
        imageryProvider = createTileMapServiceImageryProvider({
            url : endUserOptions.tmsImageryUrl
        });
    }

    var loadingIndicator = document.getElementById('loadingIndicator');
    var viewer;
    try {
        var hasBaseLayerPicker = !defined(imageryProvider);
        viewer = new Viewer('cesiumContainer', {
            imageryProvider : imageryProvider,
            baseLayerPicker : hasBaseLayerPicker,
            scene3DOnly : endUserOptions.scene3DOnly,
            requestRenderMode : true
        });

        if (hasBaseLayerPicker) {
            var viewModel = viewer.baseLayerPicker.viewModel;
            viewModel.selectedTerrain = viewModel.terrainProviderViewModels[1];
        } else {
            viewer.terrainProvider = createWorldTerrain({
                requestWaterMask: true,
                requestVertexNormals: true
            });
        }
    } catch (exception) {
        loadingIndicator.style.display = 'none';
        var message = formatError(exception);
        console.error(message);
        if (!document.querySelector('.cesium-widget-errorPanel')) {
            window.alert(message); //eslint-disable-line no-alert
        }
        return;
    }

    viewer.extend(viewerDragDropMixin);
    if (endUserOptions.inspector) {
        viewer.extend(viewerCesiumInspectorMixin);
    }

    var showLoadError = function(name, error) {
        var title = 'An error occurred while loading the file: ' + name;
        var message = 'An error occurred while loading the file, which may indicate that it is invalid.  A detailed error report is below:';
        viewer.cesiumWidget.showErrorPanel(title, message, error);
    };

    viewer.dropError.addEventListener(function(viewerArg, name, error) {
        showLoadError(name, error);
    });

    var scene = viewer.scene;
    var context = scene.context;
    if (endUserOptions.debug) {
        context.validateShaderProgram = true;
        context.validateFramebuffer = true;
        context.logShaderCompilation = true;
        context.throwOnWebGLError = true;
    }

    var view = endUserOptions.view;
    var source = endUserOptions.source;
    if (defined(source)) {
        var sourceType = endUserOptions.sourceType;
        if (!defined(sourceType)) {
            // autodetect using file extension if not specified
            if (/\.czml$/i.test(source)) {
                sourceType = 'czml';
            } else if (/\.geojson$/i.test(source) || /\.json$/i.test(source) || /\.topojson$/i.test(source)) {
                sourceType = 'geojson';
            } else if (/\.kml$/i.test(source) || /\.kmz$/i.test(source)) {
                sourceType = 'kml';
            }
        }

        var loadPromise;
        if (sourceType === 'czml') {
            loadPromise = CzmlDataSource.load(source);
        } else if (sourceType === 'geojson') {
            loadPromise = GeoJsonDataSource.load(source);
        } else if (sourceType === 'kml') {
            loadPromise = KmlDataSource.load(source, {
                camera: scene.camera,
                canvas: scene.canvas
            });
        } else {
            showLoadError(source, 'Unknown format.');
        }

        if (defined(loadPromise)) {
            viewer.dataSources.add(loadPromise).then(function(dataSource) {
                var lookAt = endUserOptions.lookAt;
                if (defined(lookAt)) {
                    var entity = dataSource.entities.getById(lookAt);
                    if (defined(entity)) {
                        viewer.trackedEntity = entity;
                    } else {
                        var error = 'No entity with id "' + lookAt + '" exists in the provided data source.';
                        showLoadError(source, error);
                    }
                } else if (!defined(view) && endUserOptions.flyTo !== 'false') {
                    viewer.flyTo(dataSource);
                }
            }).otherwise(function(error) {
                showLoadError(source, error);
            });
        }
    }

    if (endUserOptions.stats) {
        scene.debugShowFramesPerSecond = true;
    }

    var theme = endUserOptions.theme;
    if (defined(theme)) {
        if (endUserOptions.theme === 'lighter') {
            document.body.classList.add('cesium-lighter');
            viewer.animation.applyThemeChanges();
        } else {
            var error = 'Unknown theme: ' + theme;
            viewer.cesiumWidget.showErrorPanel(error, '');
        }
    }

    if (defined(view)) {
        var splitQuery = view.split(/[ ,]+/);
        if (splitQuery.length > 1) {
            var longitude = !isNaN(+splitQuery[0]) ? +splitQuery[0] : 0.0;
            var latitude = !isNaN(+splitQuery[1]) ? +splitQuery[1] : 0.0;
            var height = ((splitQuery.length > 2) && (!isNaN(+splitQuery[2]))) ? +splitQuery[2] : 300.0;
            var heading = ((splitQuery.length > 3) && (!isNaN(+splitQuery[3]))) ? CesiumMath.toRadians(+splitQuery[3]) : undefined;
            var pitch = ((splitQuery.length > 4) && (!isNaN(+splitQuery[4]))) ? CesiumMath.toRadians(+splitQuery[4]) : undefined;
            var roll = ((splitQuery.length > 5) && (!isNaN(+splitQuery[5]))) ? CesiumMath.toRadians(+splitQuery[5]) : undefined;

            viewer.camera.setView({
                destination: Cartesian3.fromDegrees(longitude, latitude, height),
                orientation: {
                    heading: heading,
                    pitch: pitch,
                    roll: roll
                }
            });
        }
    }

    var camera = viewer.camera;
    function saveCamera() {
        var position = camera.positionCartographic;
        var hpr = '';
        if (defined(camera.heading)) {
            hpr = ',' + CesiumMath.toDegrees(camera.heading) + ',' + CesiumMath.toDegrees(camera.pitch) + ',' + CesiumMath.toDegrees(camera.roll);
        }
        endUserOptions.view = CesiumMath.toDegrees(position.longitude) + ',' + CesiumMath.toDegrees(position.latitude) + ',' + position.height + hpr;
        history.replaceState(undefined, '', '?' + objectToQuery(endUserOptions));
    }

    var timeout;
    if (endUserOptions.saveCamera !== 'false') {
        camera.changed.addEventListener(function() {
            window.clearTimeout(timeout);
            timeout = window.setTimeout(saveCamera, 1000);
        });
    }

    loadingIndicator.style.display = 'none';
});


text:
[A toggle switch](https://www.sparkfun.com/products/11310) which sends a JSON string message to the server via HTTP POST when it is turned on and every 30 seconds while it is on.

The purpose of the switch is to inform when there is some food to be grabbed on the kitchen table. A Raspberry Pi client that is connected to a webcam then reacts to the message sent by the switch and takes a picture of the food on the table.

The switch has a signal output which is set to HIGH when the switch is on and LOW when the switch is off. The LED on the tip of the switch lights up when the when the switch is on.

## Wiring example

<img src="food_bb.png" width="320">

## Code example

```cpp
#include <Bridge.h>
#include <YunClient.h>

#include "HttpClient.h"
#include "vor_env.h"

#include "vor_led.h"
#include "vor_switch.h"

#define INTERVAL 30000

#define PAYLOAD "{\"id\":\"button-food\",\"type\":\"button\"}"

#define SWITCH_PIN 2

YunClient client;
HttpClient http(client, SERVER_URL, SERVER_PATH, CLIENT_USERAGENT);

VorLed led;
VorSwitch vorSwitch(SWITCH_PIN);
int switchValue = LOW;
uint64_t intervalTime = 0;

void setup() {
    Serial.begin(9600);

    led.turnOn();
    Bridge.begin();
    led.turnOff();

    http.setClientId("button-food");
}

void loop() {
    int value = vorSwitch.read();
    uint64_t now = millis();

    if (switchValue != value || now - intervalTime > INTERVAL) {
        switchValue = value;
        intervalTime = now;

        if (HIGH == switchValue) {
            http.post(PAYLOAD);
        }
    }

    http.postKeepAlive();
}
```


text:
Библиотека позволяет управлять данными, используемыми для тестирования.

Данные хранятся в обычных Ruby-файлах (имя файла зависит от названия модели) в виде переменных экземпляра, ссылающихся на ассоциативные массивы. Массивы содержат набор свойств для отдельных экземпляров модели.

## Installation

Add this line to your application's Gemfile:

    gem 'smeltery', git: 'http://github.com/Krugloff/smeltery.git'

And then execute:

    $ bundle

## Usage

### Условия использования

+ добавление модуля;
+ определение каталога, в котором хранятся тестовые данные;
+ инициализация тестовых данных в виде ассоциативных массивов или моделей;
+ использование тестовых данных с помощью предоставленных методов доступа.

Если вы используете Rails, то все эти действия уже выполнены по умолчанию для класса ActiveSupport::TestCase.

```ruby
  class ActiveSupport::TestCase
    include Smeltery
  end
  ActiveSupport::TestCase.fixture_path = 'test/fixtures/'
```

#### Каталог

Для совместимости с rails fixtures, по умолчанию, тестовые данные находятся в каталоге test/fixtures приложения.

Чтобы изменить поведение по умолчанию могут быть использованы свойства класса `fixture_path` и `ingots_path`.

#### Инициализация

`::models(*names)`
Синонимы: fixtures
Объявление тестовых данных, которые будут представлены экземплярами моделей.

`::ingots(*names)`
Объявление тестовых данных, которые будут представлены ассоциативными массивами.

+ В качестве аргументов, методы принимают нормализованные имена файлов, содержащих тестовые данные: 'users', 'user_admins' и т.д.;

+ Чтобы использовать все тестовые данные методам передается `:all`:
`models :all`;

+ Чтобы удалить все модели или вообще все тестовые данные в качестве аргумента передается nil;

+ Вместо методов класса, влияющих на выполнение всех тестов, могут использоваться методы экземпляров, влияющие на выполнение только текущего теста.

##### Сохранение моделей

При сохранении моделей выполняется только проверка сохраняемых данных. Для данных, не прошедших проверку, экземпляры моделей создаются, но не сохраняются.

#### Методы доступа

Любые тестовые данные могут быть получены с помощью методов экземпляров вида: `.name(label)`, где name зависит от расположения файла с тестовыми данными, а label от имени переменной экземпляра.

```ruby
  class UserTest < ActiveSupport::TestCase
    models 'users'

    test 'update' do
      assert users('mike').update_attribute name: 'Mikky'
    end

    test 'create' do
      ingots 'users'
      assert User.create users('mike')
    end
  end
```

### Формат тестовых данных

Для каждой модели создается отдельный файл (*.rb) с тестовыми данными. Имя и расположение файла взаимосвязаны с названием модели.

Пример файла с описанием экземпляров модели User:
```ruby
  # test/ingots/users.rb
  @krugloff = { name: 'Krugloff',
                password: 'a11ri9ht' }
  @mike     = @krugloff.merge name: 'Mike'
  @john     = @krugloff.merge name: 'John'
  @hacker   = @krugloff.merge password: 'fail'
```

#### Связь с другими моделями

Для присоединения ассоциируемых объектов могут использоваться тестовые данные (с помощью методов доступа). В этом случае всегда будет создан экземпляр модели (даже для тестовых данных представленных в виде ассоциативного массива).

```ruby
  # test/ingots/comments.rb
  @welcome = { title: 'Welcome',
               body: 'Welcome to my blog!',
               user: users('krugloff') }
```

Осторожно! Преобразование тестовых данных в ассоциативные массивы может привести к удалению ассоциируемой модели. В этом случае для модели будет существовать только внешний ключ (например user_id).
```ruby
  # Тестовые данные
  @valid =  { title: 'Welcome',
              body: 'Welcome to my blog!',
              user: users('krugloff') }

  # Тест
  class CommentTest < ActiveSupport::TestCase
    models('comments')

    test "belongs to user" do
      assert respond_to?('comments'), Comment.count.to_s
      assert !respond_to?('users')
      assert comments('valid').user.persisted?
    end

    test 'user must be persisted' do
      ingots :users
      assert_nil comments('valid').user # -> true
      assert comments('valid').user_id # -> true
    end
  end
```

Осторожно! Рекурсивный вызов тестовых данных может привести к бесконечному циклу.

### Транзакции

По умолчанию тесты выполняются в составе отдельных транзакций. Тесты, реализующие транзакции самостоятельно, должны быть объявлены в явной форме с помощью `::uses_transaction(*methods)`.

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request


text:
package org.apache.hadoop.fs;

import org.apache.hadoop.conf.Configuration;

import java.io.IOException;
import java.net.URL;
import java.util.ServiceConfigurationError;

import org.junit.Test;
import static org.junit.Assert.*;

public class TestFileSystemInitialization {

 /**
   * Check if FileSystem can be properly initialized if URLStreamHandlerFactory
   * is registered.
   */
  @Test
  public void testInitializationWithRegisteredStreamFactory() {
    Configuration conf = new Configuration();
    URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory(conf));
    try {
      FileSystem.getFileSystemClass("file", conf);
    }
    catch (IOException ok) {
      // we might get an exception but this not related to infinite loop problem
      assertFalse(false);
    }
  }

  @Test
  public void testMissingLibraries() {
    try {
      Configuration conf = new Configuration();
      Class<? extends FileSystem> fs = FileSystem.getFileSystemClass("s3a",
          conf);
      fail("Expected an exception, got a filesystem: " + fs);
    } catch (Exception | ServiceConfigurationError expected) {
    }
  }
}


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.runtime.commands;

import com.google.devtools.build.lib.actions.ExecException;
import com.google.devtools.build.lib.analysis.NoBuildEvent;
import com.google.devtools.build.lib.buildtool.BuildRequest;
import com.google.devtools.build.lib.buildtool.OutputDirectoryLinksUtils;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.runtime.BlazeCommand;
import com.google.devtools.build.lib.runtime.BlazeCommandDispatcher.ShutdownBlazeServerException;
import com.google.devtools.build.lib.runtime.Command;
import com.google.devtools.build.lib.runtime.CommandEnvironment;
import com.google.devtools.build.lib.shell.CommandException;
import com.google.devtools.build.lib.util.CommandBuilder;
import com.google.devtools.build.lib.util.ExitCode;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.util.ProcessUtils;
import com.google.devtools.build.lib.util.ShellEscaper;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionDocumentationCategory;
import com.google.devtools.common.options.OptionEffectTag;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsParser;
import com.google.devtools.common.options.OptionsProvider;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.LogManager;
import java.util.logging.Logger;

/** Implements 'blaze clean'. */
@Command(
  name = "clean",
  builds = true, // Does not, but people expect build options to be there
  writeCommandLog = false, // Do not create a command.log, otherwise we couldn't delete it.
  options = {CleanCommand.Options.class},
  help = "resource:clean.txt",
  shortDescription = "Removes output files and optionally stops the server.",
  // TODO(bazel-team): Remove this - we inherit a huge number of unused options.
  inherits = {BuildCommand.class}
)
public final class CleanCommand implements BlazeCommand {
  /**
   * An interface for special options for the clean command.
   */
  public static class Options extends OptionsBase {
    @Option(
      name = "clean_style",
      defaultValue = "",
      category = "clean",
      documentationCategory = OptionDocumentationCategory.OUTPUT_SELECTION,
      effectTags = {OptionEffectTag.HOST_MACHINE_RESOURCE_OPTIMIZATIONS},
      help = "Can be 'expunge', 'expunge_async', or 'async'."
    )
    public String cleanStyle;

    @Option(
      name = "expunge",
      defaultValue = "null",
      category = "clean",
      expansion = "--clean_style=expunge",
        documentationCategory = OptionDocumentationCategory.OUTPUT_SELECTION,
      effectTags = {OptionEffectTag.HOST_MACHINE_RESOURCE_OPTIMIZATIONS},
      help =
          "If specified, clean removes the entire working tree for this %{product} "
              + "instance, which includes all %{product}-created temporary and build output "
              + "files, and stops the %{product} server if it is running."
    )
    public Void expunge;

    @Option(
      name = "expunge_async",
      defaultValue = "null",
      category = "clean",
      expansion = "--clean_style=expunge_async",
        documentationCategory = OptionDocumentationCategory.OUTPUT_SELECTION,
      effectTags = {OptionEffectTag.HOST_MACHINE_RESOURCE_OPTIMIZATIONS},
      help =
          "If specified, clean asynchronously removes the entire working tree for "
              + "this %{product} instance, which includes all %{product}-created temporary and "
              + "build output files, and stops the %{product} server if it is running. When "
              + "this command completes, it will be safe to execute new commands in the same "
              + "client, even though the deletion may continue in the background."
    )
    public Void expungeAsync;

    @Option(
      name = "async",
      defaultValue = "null",
      category = "clean",
      expansion = "--clean_style=async",
        documentationCategory = OptionDocumentationCategory.OUTPUT_SELECTION,
      effectTags = {OptionEffectTag.HOST_MACHINE_RESOURCE_OPTIMIZATIONS},
      help =
          "If specified, clean asynchronously removes the entire working tree for "
              + "this %{product} instance, which includes all %{product}-created temporary and "
              + "build output files. When this command completes, it will be safe to execute new "
              + "commands in the same client, even though the deletion may continue in the "
              + "background."
    )
    public Void async;
  }

  /**
   * Posted on the public event stream to announce that a clean is happening.
   */
  public static class CleanStartingEvent {
    private final OptionsProvider optionsProvider;

    public CleanStartingEvent(OptionsProvider optionsProvider) {
      this.optionsProvider = optionsProvider;
    }

    public OptionsProvider getOptionsProvider() {
      return optionsProvider;
    }
  }

  private static final Logger logger = Logger.getLogger(CleanCommand.class.getName());

  @Override
  public ExitCode exec(CommandEnvironment env, OptionsProvider options)
      throws ShutdownBlazeServerException {
    Options cleanOptions = options.getOptions(Options.class);
    boolean expungeAsync = cleanOptions.cleanStyle.equals("expunge_async");
    boolean expunge = cleanOptions.cleanStyle.equals("expunge");
    boolean async = cleanOptions.cleanStyle.equals("async");

    env.getEventBus().post(new NoBuildEvent());

    if (!expunge && !expungeAsync && !async && !cleanOptions.cleanStyle.isEmpty()) {
      env.getReporter().handle(Event.error(
          null, "Invalid clean_style value '" + cleanOptions.cleanStyle + "'"));
      return ExitCode.COMMAND_LINE_ERROR;
    }

    String asyncName = (expunge || expungeAsync) ? "--expunge_async" : "--async";

    // TODO(dmarting): Deactivate expunge_async on non-Linux platform until we completely fix it
    // for non-Linux platforms (https://github.com/bazelbuild/bazel/issues/1906).
    // MacOS and FreeBSD support setsid(2) but don't have /usr/bin/setsid, so if we wanted to
    // support --expunge_async on these platforms, we'd have to write a wrapper that calls setsid(2)
    // and exec(2).
    if ((expungeAsync || async) && OS.getCurrent() != OS.LINUX) {
      String fallbackName = expungeAsync ? "--expunge" : "synchronous clean";
      env.getReporter()
          .handle(
              Event.info(
                  null /*location*/,
                  asyncName
                      + " cannot be used on non-Linux platforms, falling back to "
                      + fallbackName));
      expunge = expungeAsync;
      expungeAsync = false;
      async = false;
      cleanOptions.cleanStyle = expunge ? "expunge" : "";
    }

    String cleanBanner =
        (expungeAsync || async)
            ? "Starting clean."
            : "Starting clean (this may take a while). "
                + "Consider using "
                + asyncName
                + " if the clean takes more than several minutes.";

    env.getEventBus().post(new CleanStartingEvent(options));
    env.getReporter().handle(Event.info(null/*location*/, cleanBanner));

    try {
      String symlinkPrefix = options.getOptions(BuildRequest.BuildRequestOptions.class)
          .getSymlinkPrefix(env.getRuntime().getProductName());
      actuallyClean(env, env.getOutputBase(), expunge, expungeAsync, async, symlinkPrefix);
      return ExitCode.SUCCESS;
    } catch (IOException e) {
      env.getReporter().handle(Event.error(e.getMessage()));
      return ExitCode.LOCAL_ENVIRONMENTAL_ERROR;
    } catch (CommandException | ExecException e) {
      env.getReporter().handle(Event.error(e.getMessage()));
      return ExitCode.RUN_FAILURE;
    } catch (InterruptedException e) {
      env.getReporter().handle(Event.error("clean interrupted"));
      return ExitCode.INTERRUPTED;
    }
  }

  private static void asyncClean(CommandEnvironment env, Path path, String pathItemName)
      throws IOException, CommandException {
    String tempBaseName = path.getBaseName() + "_tmp_" + ProcessUtils.getpid();

    // Keeping tempOutputBase in the same directory ensures it remains in the
    // same file system, and therefore the mv will be atomic and fast.
    Path tempPath = path.getParentDirectory().getChild(tempBaseName);
    path.renameTo(tempPath);
    env.getReporter()
        .handle(Event.info(null, pathItemName + " moved to " + tempPath + " for deletion"));

    // Daemonize the shell and use the double-fork idiom to ensure that the shell
    // exits even while the "rm -rf" command continues.
    String command =
        String.format(
            "exec >&- 2>&- <&- && (/usr/bin/setsid /bin/rm -rf %s &)&",
            ShellEscaper.escapeString(tempPath.getPathString()));

    logger.info("Executing shell commmand " + ShellEscaper.escapeString(command));

    // Doesn't throw iff command exited and was successful.
    new CommandBuilder()
        .addArg(command)
        .useShell(true)
        .setWorkingDir(tempPath.getParentDirectory())
        .build()
        .execute();
  }

  private void actuallyClean(
      CommandEnvironment env,
      Path outputBase,
      boolean expunge,
      boolean expungeAsync,
      boolean async,
      String symlinkPrefix)
      throws IOException, ShutdownBlazeServerException, CommandException, ExecException,
          InterruptedException {
    String workspaceDirectory = env.getWorkspace().getBaseName();
    if (env.getOutputService() != null) {
      env.getOutputService().clean();
    }
    env.getBlazeWorkspace().clearCaches();
    if (expunge) {
      logger.info("Expunging...");
      env.getRuntime().prepareForAbruptShutdown();
      // Close java.log.
      LogManager.getLogManager().reset();
      // Close the default stdout/stderr.
      if (FileDescriptor.out.valid()) {
        new FileOutputStream(FileDescriptor.out).close();
      }
      if (FileDescriptor.err.valid()) {
        new FileOutputStream(FileDescriptor.err).close();
      }
      // Close the redirected stdout/stderr.
      System.out.close();
      System.err.close();
      // Delete the big subdirectories with the important content first--this
      // will take the most time. Then quickly delete the little locks, logs
      // and links right before we exit. Once the lock file is gone there will
      // be a small possibility of a server race if a client is waiting, but
      // all significant files will be gone by then.
      FileSystemUtils.deleteTreesBelow(outputBase);
      FileSystemUtils.deleteTree(outputBase);
    } else if (expungeAsync) {
      logger.info("Expunging asynchronously...");
      env.getRuntime().prepareForAbruptShutdown();
      asyncClean(env, outputBase, "Output base");
    } else {
      logger.info("Output cleaning...");
      env.getBlazeWorkspace().resetEvaluator();
      Path execroot = outputBase.getRelative("execroot");
      if (execroot.exists()) {
        logger.finest("Cleaning " + execroot + (async ? " asynchronously..." : ""));
        if (async) {
          asyncClean(env, execroot, "Output tree");
        } else {
          FileSystemUtils.deleteTreesBelow(execroot);
        }
      }
    }
    // remove convenience links
    OutputDirectoryLinksUtils.removeOutputDirectoryLinks(
        workspaceDirectory, env.getWorkspace(), env.getReporter(),
        symlinkPrefix, env.getRuntime().getProductName());
    // shutdown on expunge cleans
    if (expunge || expungeAsync) {
      throw new ShutdownBlazeServerException(0);
    }
    System.gc();
  }

  @Override
  public void editOptions(OptionsParser optionsParser) {}
}


text:
package org.kuali.kfs.gl.businessobject.options;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.kuali.kfs.gl.service.OriginEntryGroupService;
import org.kuali.kfs.gl.web.util.OriginEntryFileComparator;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.rice.core.api.datetime.DateTimeService;
import org.kuali.rice.core.api.util.ConcreteKeyValue;
import org.kuali.rice.krad.keyvalues.KeyValuesBase;

/**
 * Returns list of GL origin entry filenames
 */
public class CorrectionGroupEntriesFinder extends KeyValuesBase {

    /**
     * Returns a list of key/value pairs to display correction groups that can be used in a Correction Document
     *
     * @return a List of key/value pairs for correction groups
     * @see org.kuali.rice.kns.lookup.keyvalues.KeyValuesFinder#getKeyValues()
     */
    public List getKeyValues() {
        List activeLabels = new ArrayList();

        OriginEntryGroupService originEntryGroupService = SpringContext.getBean(OriginEntryGroupService.class);
        File[] fileList = originEntryGroupService.getAllFileInBatchDirectory();

        List<File> sortedFileList = Arrays.asList(fileList);
        Collections.sort(sortedFileList, new OriginEntryFileComparator());

        for (File file : sortedFileList) {
            String fileName = file.getName();

            // build display file name with date and size
            Date date = new Date(file.lastModified());
            String timeInfo = "(" + SpringContext.getBean(DateTimeService.class).toDateTimeString(date) + ")";
            String sizeInfo = "(" + (new Long(file.length())).toString() + ")";

            activeLabels.add(new ConcreteKeyValue(fileName, timeInfo + " " + fileName + " " + sizeInfo));
        }

        return activeLabels;
    }

}


text:
/*************************************************************************/
/*  label.cpp                                                            */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                    http://www.godotengine.org                         */
/*************************************************************************/
/* Copyright (c) 2007-2015 Juan Linietsky, Ariel Manzur.                 */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/
#include "label.h"
#include "print_string.h"
#include "globals.h"
#include "translation.h"

void Label::set_autowrap(bool p_autowrap) {

	autowrap=p_autowrap;
	word_cache_dirty=true;
	minimum_size_changed();
	update();

}
bool Label::has_autowrap() const {

	return autowrap;
}

void Label::set_uppercase(bool p_uppercase) {

	uppercase=p_uppercase;
	word_cache_dirty=true;
	minimum_size_changed();
	update();
}
bool Label::is_uppercase() const {

	return uppercase;
}

int Label::get_line_height() const {

	return get_font("font")->get_height();

}

void Label::_notification(int p_what) {

	if (p_what==NOTIFICATION_DRAW) {

		if (clip || autowrap)
			VisualServer::get_singleton()->canvas_item_set_clip(get_canvas_item(),true);

		if (word_cache_dirty)
			regenerate_word_cache();

		RID ci = get_canvas_item();

		Size2 string_size;
		Size2 size=get_size();

		Ref<Font> font = get_font("font");
		Color font_color = get_color("font_color");
		Color font_color_shadow = get_color("font_color_shadow");
		bool use_outlinde = get_constant("shadow_as_outline");
		Point2 shadow_ofs(get_constant("shadow_offset_x"),get_constant("shadow_offset_y"));

		VisualServer::get_singleton()->canvas_item_set_distance_field_mode(get_canvas_item(),font.is_valid() && font->is_distance_field_hint());

		int font_h = font->get_height();
		int lines_visible = size.y/font_h;
		int space_w=font->get_char_size(' ').width;
		int chars_total=0;

		int vbegin=0,vsep=0;

		if (lines_visible > line_count) {
			lines_visible = line_count;

		}

		if (max_lines_visible >= 0 && lines_visible > max_lines_visible) {
			lines_visible = max_lines_visible;

		}

		if (lines_visible > 0) {

			switch(valign) {

				case VALIGN_TOP: {
					//nothing
				} break;
				case VALIGN_CENTER: {
					vbegin=(size.y - lines_visible * font_h) / 2;
					vsep=0;

				} break;
				case VALIGN_BOTTOM: {
					vbegin=size.y - lines_visible * font_h;
					vsep=0;

				} break;
				case VALIGN_FILL: {
					vbegin=0;
					if (lines_visible>1) {
						vsep=(size.y - lines_visible * font_h) / (lines_visible - 1);
					} else {
						vsep=0;
					}

				} break;
			}
		}

		WordCache *wc = word_cache;
		if (!wc)
			return;

		int c = 0;
		int line=0;
		int line_to=lines_skipped + (lines_visible>0?lines_visible:1);
		while(wc) {
		/* handle lines not meant to be drawn quickly */
			if  (line>=line_to)
				break;
			if  (line<lines_skipped) {

				while (wc && wc->char_pos>=0)
					wc=wc->next;
				if (wc)
					wc=wc->next;
				line++;
				continue;
			}

		/* handle lines normally */

			if (wc->char_pos<0) {
			//empty line
				wc=wc->next;
				line++;
				continue;
			}

			WordCache *from=wc;
			WordCache *to=wc;

			int taken=0;
			int spaces=0;
			while(to && to->char_pos>=0) {

				taken+=to->pixel_width;
				if (to!=from && to->space_count) {
					spaces+=to->space_count;
				}
				to=to->next;
			}

			bool can_fill = to && to->char_pos==WordCache::CHAR_WRAPLINE;

			float x_ofs=0;

			switch (align) {

				case ALIGN_FILL:
				case ALIGN_LEFT: {

					x_ofs=0;
				} break;
				case ALIGN_CENTER: {

					x_ofs=int(size.width-(taken+spaces*space_w))/2;;

				} break;
				case ALIGN_RIGHT: {

					x_ofs=int(size.width-(taken+spaces*space_w));

				} break;
				}

			int y_ofs=(line-lines_skipped)*font_h + font->get_ascent();
			y_ofs+=vbegin + line*vsep;

			while(from!=to) {

			// draw a word
				int pos = from->char_pos;
				if (from->char_pos<0) {

					ERR_PRINT("BUG");
					return;
				}
				if (from->space_count) {
				/* spacing */
					x_ofs+=space_w*from->space_count;
					if (can_fill && align==ALIGN_FILL && spaces) {

						x_ofs+=int((size.width-(taken+space_w*spaces))/spaces);
					}

				}

				if (font_color_shadow.a>0) {

					int chars_total_shadow = chars_total; //save chars drawn
					float x_ofs_shadow=x_ofs;
					for (int i=0;i<from->word_len;i++) {

						if (visible_chars < 0 || chars_total_shadow<visible_chars) {
							CharType c = text[i+pos];
							CharType n = text[i+pos+1];
							if (uppercase) {
								c=String::char_uppercase(c);
								n=String::char_uppercase(c);
							}

							float move=font->draw_char(ci, Point2( x_ofs_shadow, y_ofs )+shadow_ofs, c, n,font_color_shadow );
							if (use_outlinde) {
								font->draw_char(ci, Point2( x_ofs_shadow, y_ofs )+Vector2(-shadow_ofs.x,shadow_ofs.y), c, n,font_color_shadow );
								font->draw_char(ci, Point2( x_ofs_shadow, y_ofs )+Vector2(shadow_ofs.x,-shadow_ofs.y), c, n,font_color_shadow );
								font->draw_char(ci, Point2( x_ofs_shadow, y_ofs )+Vector2(-shadow_ofs.x,-shadow_ofs.y), c, n,font_color_shadow );
							}
							x_ofs_shadow+=move;
							chars_total_shadow++;
						}
					}

				}
				for (int i=0;i<from->word_len;i++) {

					if (visible_chars < 0 || chars_total<visible_chars) {
						CharType c = text[i+pos];
						CharType n = text[i+pos+1];
						if (uppercase) {
							c=String::char_uppercase(c);
							n=String::char_uppercase(c);
						}

						x_ofs+=font->draw_char(ci,Point2( x_ofs, y_ofs ), c, n, font_color );
						chars_total++;
					}

				}
				from=from->next;
			}

			wc=to?to->next:0;
			line++;

		}
	}

	if (p_what==NOTIFICATION_THEME_CHANGED) {

		word_cache_dirty=true;
		update();
	}
	if (p_what==NOTIFICATION_RESIZED) {

		word_cache_dirty=true;
	}

}

Size2 Label::get_minimum_size() const {

	if (autowrap)
		return Size2(1,1);
	else {

		// don't want to mutable everything
		if(word_cache_dirty)
			const_cast<Label*>(this)->regenerate_word_cache();

		Size2 ms=minsize;
		if (clip)
			ms.width=1;
		return ms;
	}
}

int Label::get_longest_line_width() const {

	Ref<Font> font = get_font("font");
	int max_line_width=0;
	int line_width=0;

	for (int i=0;i<text.size();i++) {

		CharType current=text[i];
		if (uppercase)
			current=String::char_uppercase(current);

		if (current<32) {

			if (current=='\n') {

				if (line_width>max_line_width)
					max_line_width=line_width;
				line_width=0;
			}
		} else {

			int char_width=font->get_char_size(current).width;
			line_width+=char_width;
		}

	}

	if (line_width>max_line_width)
		max_line_width=line_width;

	return max_line_width;
}

int Label::get_line_count() const {

	if (!is_inside_tree())
		return 1;
	if (word_cache_dirty)
		const_cast<Label*>(this)->regenerate_word_cache();

	return line_count;
}

void Label::regenerate_word_cache() {

	while (word_cache) {

		WordCache *current=word_cache;
		word_cache=current->next;
		memdelete( current );
	}

	int width=autowrap?get_size().width:get_longest_line_width();
	Ref<Font> font = get_font("font");

	int current_word_size=0;
	int word_pos=0;
	int line_width=0;
	int space_count=0;
	int space_width=font->get_char_size(' ').width;
	line_count=1;
	total_char_cache=0;

	WordCache *last=NULL;

	for (int i=0;i<text.size()+1;i++) {

		CharType current=i<text.length()?text[i]:' '; //always a space at the end, so the algo works

		if (uppercase)
			current=String::char_uppercase(current);

		// ranges taken from http://www.unicodemap.org/
		// if your language is not well supported, consider helping improve
		// the unicode support in Godot.
		bool separatable = (current>=0x2E08 && current<=0xFAFF) || (current>=0xFE30 && current<=0xFE4F);
				//current>=33 && (current < 65||current >90) && (current<97||current>122) && (current<48||current>57);
		bool insert_newline=false;
		int char_width;

		if (current<33) {

			if (current_word_size>0) {
				WordCache *wc = memnew( WordCache );
				if (word_cache) {
					last->next=wc;
				} else {
					word_cache=wc;
				}
				last=wc;

				wc->pixel_width=current_word_size;
				wc->char_pos=word_pos;
				wc->word_len=i-word_pos;
				wc->space_count = space_count;
				current_word_size=0;
				space_count=0;

			}

			if (current=='\n') {
				insert_newline=true;
			} else {
				total_char_cache++;
			}

			if (i<text.length() && text[i] == ' ') {
				total_char_cache--;  // do not count spaces
				if (line_width > 0 || last==NULL || last->char_pos!=WordCache::CHAR_WRAPLINE) {
					space_count++;
					line_width+=space_width;
				}else {
					space_count=0;
				}
			}

		} else {
			// latin characters
			if (current_word_size==0) {
				word_pos=i;
			}

			char_width=font->get_char_size(current).width;
			current_word_size+=char_width;
			line_width+=char_width;
			total_char_cache++;

		}

		if ((autowrap && (line_width >= width) && ((last && last->char_pos >= 0) || separatable)) || insert_newline) {
			if (separatable) {
				if (current_word_size>0) {
					WordCache *wc = memnew( WordCache );
					if (word_cache) {
						last->next=wc;
					} else {
						word_cache=wc;
					}
					last=wc;

					wc->pixel_width=current_word_size-char_width;
					wc->char_pos=word_pos;
					wc->word_len=i-word_pos;
					wc->space_count = space_count;
					current_word_size=char_width;
					space_count=0;
					word_pos=i;
				}
			}

			WordCache *wc = memnew( WordCache );
			if (word_cache) {
				last->next=wc;
			} else {
				word_cache=wc;
			}
			last=wc;

			wc->pixel_width=0;
			wc->char_pos=insert_newline?WordCache::CHAR_NEWLINE:WordCache::CHAR_WRAPLINE;

			line_width=current_word_size;
			line_count++;
			space_count=0;

		}

	}

	if (!autowrap) {
		minsize.width=width;
		if (max_lines_visible > 0 && line_count > max_lines_visible) {
			minsize.height=font->get_height()*max_lines_visible;
		} else {
			minsize.height=font->get_height()*line_count;
		}
	}

	word_cache_dirty=false;

}

void Label::set_align(Align p_align) {

	ERR_FAIL_INDEX(p_align,4);
	align=p_align;
	update();
}

Label::Align Label::get_align() const{

	return align;
}

void Label::set_valign(VAlign p_align) {

	ERR_FAIL_INDEX(p_align,4);
	valign=p_align;
	update();
}

Label::VAlign Label::get_valign() const{

	return valign;
}

void Label::set_text(const String& p_string) {

	String str = XL_MESSAGE(p_string);

	if (text==str)
		return;

	text=str;
	word_cache_dirty=true;
	if (percent_visible<1)
		visible_chars=get_total_character_count()*percent_visible;
	update();
	minimum_size_changed();

}

void Label::set_clip_text(bool p_clip) {

	clip=p_clip;
	update();
	minimum_size_changed();
}

bool Label::is_clipping_text() const {

	return clip;
}

String Label::get_text() const {

	return text;
}

void Label::set_visible_characters(int p_amount) {

	visible_chars=p_amount;
	if (get_total_character_count() > 0) {
		percent_visible=(float)p_amount/(float)total_char_cache;
	}
	update();
}

int Label::get_visible_characters() const {

	return visible_chars;
}

void Label::set_percent_visible(float p_percent) {

	if (p_percent<0 || p_percent>=1) {

		visible_chars=-1;
		percent_visible=1;

	} else {

		visible_chars=get_total_character_count()*p_percent;
		percent_visible=p_percent;

	}
	update();

}

float Label::get_percent_visible() const{

	return percent_visible;
}

void Label::set_lines_skipped(int p_lines) {

	lines_skipped=p_lines;
	update();
}

int Label::get_lines_skipped() const{

	return lines_skipped;
}

void Label::set_max_lines_visible(int p_lines) {

	max_lines_visible=p_lines;
	update();
}

int Label::get_max_lines_visible() const{

	return max_lines_visible;
}

int Label::get_total_character_count() const {

	if (word_cache_dirty)
		const_cast<Label*>(this)->regenerate_word_cache();

	return total_char_cache;
}

void Label::_bind_methods() {

	ObjectTypeDB::bind_method(_MD("set_align","align"),&Label::set_align);
	ObjectTypeDB::bind_method(_MD("get_align"),&Label::get_align);
	ObjectTypeDB::bind_method(_MD("set_valign","valign"),&Label::set_valign);
	ObjectTypeDB::bind_method(_MD("get_valign"),&Label::get_valign);
	ObjectTypeDB::bind_method(_MD("set_text","text"),&Label::set_text);
	ObjectTypeDB::bind_method(_MD("get_text"),&Label::get_text);
	ObjectTypeDB::bind_method(_MD("set_autowrap","enable"),&Label::set_autowrap);
	ObjectTypeDB::bind_method(_MD("has_autowrap"),&Label::has_autowrap);
	ObjectTypeDB::bind_method(_MD("set_clip_text","enable"),&Label::set_clip_text);
	ObjectTypeDB::bind_method(_MD("is_clipping_text"),&Label::is_clipping_text);
	ObjectTypeDB::bind_method(_MD("set_uppercase","enable"),&Label::set_uppercase);
	ObjectTypeDB::bind_method(_MD("is_uppercase"),&Label::is_uppercase);
	ObjectTypeDB::bind_method(_MD("get_line_height"),&Label::get_line_height);
	ObjectTypeDB::bind_method(_MD("get_line_count"),&Label::get_line_count);
	ObjectTypeDB::bind_method(_MD("get_total_character_count"),&Label::get_total_character_count);
	ObjectTypeDB::bind_method(_MD("set_visible_characters","amount"),&Label::set_visible_characters);
	ObjectTypeDB::bind_method(_MD("get_visible_characters"),&Label::get_visible_characters);
	ObjectTypeDB::bind_method(_MD("set_percent_visible","percent_visible"),&Label::set_percent_visible);
	ObjectTypeDB::bind_method(_MD("get_percent_visible"),&Label::get_percent_visible);
	ObjectTypeDB::bind_method(_MD("set_lines_skipped","lines_skipped"),&Label::set_lines_skipped);
	ObjectTypeDB::bind_method(_MD("get_lines_skipped"),&Label::get_lines_skipped);
	ObjectTypeDB::bind_method(_MD("set_max_lines_visible","lines_visible"),&Label::set_max_lines_visible);
	ObjectTypeDB::bind_method(_MD("get_max_lines_visible"),&Label::get_max_lines_visible);

	BIND_CONSTANT( ALIGN_LEFT );
	BIND_CONSTANT( ALIGN_CENTER );
	BIND_CONSTANT( ALIGN_RIGHT );
	BIND_CONSTANT( ALIGN_FILL );

	BIND_CONSTANT( VALIGN_TOP );
	BIND_CONSTANT( VALIGN_CENTER );
	BIND_CONSTANT( VALIGN_BOTTOM );
	BIND_CONSTANT( VALIGN_FILL );

	ADD_PROPERTYNZ( PropertyInfo( Variant::STRING, "text",PROPERTY_HINT_MULTILINE_TEXT,"",PROPERTY_USAGE_DEFAULT_INTL), _SCS("set_text"),_SCS("get_text") );
	ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "align", PROPERTY_HINT_ENUM,"Left,Center,Right,Fill" ),_SCS("set_align"),_SCS("get_align") );
	ADD_PROPERTYNZ( PropertyInfo( Variant::INT, "valign", PROPERTY_HINT_ENUM,"Top,Center,Bottom,Fill" ),_SCS("set_valign"),_SCS("get_valign") );
	ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "autowrap"),_SCS("set_autowrap"),_SCS("has_autowrap") );
	ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "clip_text"),_SCS("set_clip_text"),_SCS("is_clipping_text") );
	ADD_PROPERTYNZ( PropertyInfo( Variant::BOOL, "uppercase"),_SCS("set_uppercase"),_SCS("is_uppercase") );
	ADD_PROPERTY( PropertyInfo( Variant::REAL, "percent_visible", PROPERTY_HINT_RANGE,"0,1,0.001"),_SCS("set_percent_visible"),_SCS("get_percent_visible") );
	ADD_PROPERTY( PropertyInfo( Variant::INT, "lines_skipped", PROPERTY_HINT_RANGE,"0,999,1"),_SCS("set_lines_skipped"),_SCS("get_lines_skipped") );
	ADD_PROPERTY( PropertyInfo( Variant::INT, "max_lines_visible", PROPERTY_HINT_RANGE,"-1,999,1"),_SCS("set_max_lines_visible"),_SCS("get_max_lines_visible") );

}

Label::Label(const String &p_text) {

	align=ALIGN_LEFT;
	valign=VALIGN_TOP;
	text="";
	word_cache=NULL;
	word_cache_dirty=true;
	autowrap=false;
	line_count=0;
	set_v_size_flags(0);
	clip=false;
	set_ignore_mouse(true);
	total_char_cache=0;
	visible_chars=-1;
	percent_visible=1;
	lines_skipped=0;
	max_lines_visible=-1;
	set_text(p_text);
	uppercase=false;
}

Label::~Label() {

	while (word_cache) {

		WordCache *current=word_cache;
		word_cache=current->next;
		memdelete( current );
	}
}


text:
#pragma once

#include "IntermediateVarSpanNode.h"
#include "moses/WordsRange.h"

#include <boost/array.hpp>

#include <map>

#include <vector>

namespace Moses
{

/** @todo what is this?
 */
struct VarSpanNode {
public:
  struct NonTermRange {
    size_t s1;
    size_t s2;
    size_t e1;
    size_t e2;
  };
  typedef std::vector<IntermediateVarSpanNode> NodeVec;
  typedef boost::array<int, 5> KeyType;
  typedef std::map<KeyType, VarSpanNode> MapType;

  VarSpanNode() : m_parent(0), m_label(0), m_rank(0) {}

  VarSpanNode &Insert(const NodeVec &vec) {
    if (vec.empty()) {
      return *this;
    }
    return Insert(vec.begin(), vec.end());
  }

  // Given a span, determine the ranges of possible start and end offsets
  // for each non-terminal.
  void CalculateRanges(int start, int end,
                       std::vector<NonTermRange> &ranges) const {
    ranges.resize(m_rank);
    const VarSpanNode *n = this;
    size_t firstIndex = m_rank;
    while (n->m_parent) {
      const KeyType &key = *(n->m_label);
      assert(key[0] == 0 || key[0] == key[1]);
      assert(key[3] == -1 || key[2] == key[3]);
      const int numSplitPoints = key[4];
      firstIndex -= numSplitPoints+1;
      const int vsn_start = key[0] == 0 ? start : key[0];
      const int vsn_end = key[3] == -1 ? end : key[3];
      // The start position of the first non-terminal is known.
      ranges[firstIndex].s1 = ranges[firstIndex].s2 = vsn_start - start;
      // The end range depends on the number of split points.  If there are
      // no split points then the end position is fixed.
      if (numSplitPoints) {
        ranges[firstIndex].e1 = vsn_start - start;
        ranges[firstIndex].e2 = vsn_end - start - numSplitPoints;
      } else {
        ranges[firstIndex].e1 = ranges[firstIndex].e2 = vsn_end - start;
      }
      // For the remaining non-terminals, the start and end boundaries shift
      // by one position with each split point.
      for (int i = 1; i <= numSplitPoints; ++i) {
        ranges[firstIndex+i].s1 = ranges[firstIndex].s1+i;
        ranges[firstIndex+i].s2 = ranges[firstIndex].e2+i;
        ranges[firstIndex+i].e1 = ranges[firstIndex].s1+i;
        ranges[firstIndex+i].e2 = ranges[firstIndex].e2+i;
      }
      // Except that the end point of the final non-terminal is fixed.
      ranges[firstIndex+numSplitPoints].e1 = vsn_end - start;
      ranges[firstIndex+numSplitPoints].e2 = vsn_end - start;
      n = n->m_parent;
    }
    assert(firstIndex == 0);
  }

  const VarSpanNode *m_parent;
  const KeyType *m_label;
  size_t m_rank;
  MapType m_children;

private:
  VarSpanNode &Insert(NodeVec::const_iterator first,
                      NodeVec::const_iterator last) {
    assert(first != last);

    KeyType key;
    key[0] = first->m_start.first;
    key[1] = first->m_start.second;
    key[2] = first->m_end.first;
    key[3] = first->m_end.second;
    key[4] = first->m_numSplitPoints;

    std::pair<MapType::iterator, bool> result = m_children.insert(
          std::make_pair(key, VarSpanNode()));
    VarSpanNode &child = result.first->second;
    if (result.second) {
      child.m_parent = this;
      child.m_label = &(result.first->first);
      child.m_rank = m_rank + first->m_numSplitPoints + 1;
    }
    if (++first == last) {
      return child;
    }
    return child.Insert(first, last);
  }
};

}