text:
#include "iodevicereader.h"
#include "qasyncreader.h"

#include "mediagraph.h"

#include <phonon/streaminterface.h>

#include <dshow.h>
#include <initguid.h>

QT_BEGIN_NAMESPACE

#ifndef QT_NO_PHONON_ABSTRACTMEDIASTREAM

namespace Phonon
{
    namespace DS9
    {
        //these mediatypes define a stream, its type will be autodetected by DirectShow
        static QVector<AM_MEDIA_TYPE> getMediaTypes()
        {
            //the order here is important because otherwise,
            //directshow might not be able to detect the stream type correctly

            AM_MEDIA_TYPE mt = { MEDIATYPE_Stream, MEDIASUBTYPE_Avi, TRUE, FALSE, 1, GUID_NULL, 0, 0, 0};

            QVector<AM_MEDIA_TYPE> ret;
            //AVI stream
            ret << mt;
            //WAVE stream
            mt.subtype = MEDIASUBTYPE_WAVE;
            ret << mt;
            //normal auto-detect stream (must be at the end!)
            mt.subtype = MEDIASUBTYPE_NULL;
            ret << mt;
            return ret;
        }

        class StreamReader : public QAsyncReader, public Phonon::StreamInterface
        {
        public:
            StreamReader(QBaseFilter *parent, const Phonon::MediaSource &source, const MediaGraph *mg) :
              QAsyncReader(parent, getMediaTypes()),
                  m_seekable(false), m_pos(0), m_size(-1), m_mediaGraph(mg)
              {
                  connectToSource(source);
              }

              //for Phonon::StreamInterface
              void writeData(const QByteArray &data)
              {
                  m_pos += data.size();
                  m_buffer += data;
              }

              void endOfData()
              {
              }

              void setStreamSize(qint64 newSize)
              {
                  QMutexLocker locker(&m_mutex);
                  m_size = newSize;
              }

              void setStreamSeekable(bool s)
              {
                  QMutexLocker locker(&m_mutex);
                  m_seekable = s;
              }

              //virtual pure members

              //implementation from IAsyncReader
              STDMETHODIMP Length(LONGLONG *total, LONGLONG *available)
              {
                  QMutexLocker locker(&m_mutex);
                  if (total) {
                      *total = m_size;
                  }

                  if (available) {
                      *available = m_size;
                  }

                  return S_OK;
              }

              HRESULT read(LONGLONG pos, LONG length, BYTE *buffer, LONG *actual)
              {
                  Q_ASSERT(!m_mutex.tryLock());
                  if (m_mediaGraph->isStopping()) {
                      return VFW_E_WRONG_STATE;
                  }

                  if(m_size != 1 && pos + length > m_size) {
                      //it tries to read outside of the boundaries
                      return E_FAIL;
                  }

                  if (m_pos - m_buffer.size() != pos) {
                      if (!m_seekable) {
                          return S_FALSE;
                      }
                      m_pos = pos;
                      seekStream(pos);
                      m_buffer.clear();
                  }

                  int oldSize = m_buffer.size();
                  while (m_buffer.size() < int(length)) {
                      needData();

                      if (oldSize == m_buffer.size()) {
                          break; //we didn't get any data
                      }
                      oldSize = m_buffer.size();
                  }

                  int bytesRead = qMin(m_buffer.size(), int(length));
                  qMemCopy(buffer, m_buffer.data(), bytesRead);
                  //truncate the buffer
                  m_buffer = m_buffer.mid(bytesRead);

                  if (actual) {
                      *actual = bytesRead; //initialization
                  }

                  return bytesRead == length ? S_OK : S_FALSE;
              }

        public:
            //for Phonon::StreamInterface
            QByteArray m_buffer;
            bool m_seekable;
            qint64 m_pos;
            qint64 m_size;

            const MediaGraph *m_mediaGraph;
        };

        IODeviceReader::IODeviceReader(const Phonon::MediaSource &source, const MediaGraph *mg) :
        QBaseFilter(CLSID_NULL)
        {
            //create the output pin
            m_streamReader = new StreamReader(this, source, mg);
        }

        IODeviceReader::~IODeviceReader()
        {
        }
    }
}

#endif //QT_NO_PHONON_ABSTRACTMEDIASTREAM

QT_END_NAMESPACE


text:
This document will walk you through building an HTTP server on top of Spray,
Akka and Cascade. All of the code examples are based on our
[working HTTP server example](/examples/src/main/scala/com/paypal/cascade/examples/http/resource/).

For more details on how Cascade's HTTP support works, see
[HTTP_RESOURCE.md](HTTP_RESOURCE.md).

## Resources
A resource implements handlers for incoming requests. Each resource is a class
that extends `AbstractResourceActor` (which eventually extends Akka `Actor`),
that implements a `resourceReceive` method.

`resourceReceive` is similar to the `receive` in Akka. It's a `PartialFunction`
that can accept multiple messages. Each message represents an individual
request, and all messages will be wrapped in a `ProcessRequest` case class.

Below is an example resource.

```scala
class MyResource(ctx: ResourceContext) extends AbstractResourceActor(ctx) {
  override def resourceReceive = {
    //processing a request that was not parsed at all.
    case ProcessRequest(req: HttpRequest) =>
      completeToJSON(StatusCodes.OK, "hello world!")
    //processing a request that was parsed by the ResourceDriver
    case ProcessRequest(req: GetHelloWorld) =>
      completeToJSON(StatusCodes.OK, "hello world 2!")
  }
}

object MyResource {
  //this is a convenience method used as a a parameter in
  //ResourceDriver.serve, which you'll see later.
  def apply(ctx: ResourceContext): MyResource = {
    new MyResource(ctx)
  }
}
```

A few notes:

- Resources don't define routes to bind to, nor do they couple tightly with
the functionality to parse a request into a Scala type. Cascade makes routes,
parsing and resources orthogonal on purpose. You can take advantage of that
orthogonality in a lot of ways. Here are a few ideas:
  - re-use routes for different servers (e.g. a dev and a prod server)
  - switch parsers at runtime (e.g. for different request body encodings)
  - switch resources at runtime (e.g. to do dependency injection)
- You can create a new resource instance for each incoming request or reuse a
resource across requests. We recommend the former so that a single resource
actor can safely store state for a single request. Also, we only built support
for the first pattern in `ResourceDriver` (see below.)

## Routes & Startup
As mentioned in the last section, your HTTP server has a set of routes that
execute your resources when a request matches a route.

You define your routes and spray server configs at the same time inside a
`SprayConfiguration` class.

As mentioned above, we recommend that you call `ResourceDriver.serve(...)`
inside each route, to create a new resource actor for each request. That
pattern follows what Spray does for HTTP handler actors.

As you'll see in the example below, `ResourceDriver.serve(...)` takes in a
resource construction function and a request parsing function. Your resource
can have multiple handlers, so you can use one resource actor with multiple
different parsers. Your server will still work as long as the resource works
with the different parsed bodies you send to it.

```scala
object MyServer extends CascadeApp {
  val svcName = "sample-service"
  val cfg = SprayConfiguration(serviceName = svcName,
                               interface = "localhost",
                               port = 8080,
                               backlog = 5) {
    //This is where you put your routes. We recommend using spray-routing here,
    //but you can also write your own routing code that returns a
    //spray.routing.Route.
    get {
      path("hello") {
        ResourceDriver.serve(MyResource.apply, parseRequest)
      }
    }
  }
  val sysWrapper = new ActorSystemWrapper(svcName)
  //this is what actually starts your server
  SprayActor.start(sysWrapper, cfg)
}
```

One final note - make sure your `MyServer` object extends `CascadeApp`. Doing
so will set up some global logging and exception handling features that work
best with Spray/Akka servers.

See the [example http server](/examples/src/main/scala/com/paypal/cascade/examples/http/resource/MyHttpServer.scala) for working code.

redpajama_set_name: RedPajamaGithub


text:
from smtplib import SMTP
from email.MIMEText import MIMEText

CX_DIR = '/CineGridExchange/home/rods/CineGridExchange'
FROM_ADDR = ''

def send_mail(from_addr, to_list, subject, body):
  msg = MIMEText(body)
  msg['Subject'] = subject
  msg['From'] = from_addr
  msg['To'] = ", ".join(to_list)
  s = SMTP('localhost')
  s.sendmail(from_addr, to_list, msg.as_string())
  s.quit()


text:
"""
Tests for grdfill.
"""
import os

import numpy as np
import pytest
import xarray as xr
from pygmt import grdfill, grdinfo
from pygmt.datasets import load_earth_relief
from pygmt.exceptions import GMTInvalidInput
from pygmt.helpers import GMTTempFile

@pytest.fixture(scope="module", name="grid")
def fixture_grid():
    """
    Load the grid data from the sample earth_relief file and set value(s) to
    NaN.
    """
    grid = load_earth_relief(registration="pixel", region=[-5, 5, -5, 5])
    grid[3:5, 3:5] = np.nan
    grid[5:7, 5:7] = np.inf
    return grid

def test_grdfill_dataarray_out(grid):
    """
    grdfill with a DataArray output.
    """
    result = grdfill(grid=grid, mode="c20")
    # check information of the output grid
    assert isinstance(result, xr.DataArray)
    assert result[4, 4] == 20
    assert result[5, 5] == np.inf
    assert not result.isnull().all()  # check that no NaN values exists
    assert result.gmt.gtype == 1  # Geographic grid
    assert result.gmt.registration == 1  # Pixel registration

def test_grdfill_file_out(grid):
    """
    grdfill with an outgrid set.
    """
    with GMTTempFile(suffix=".nc") as tmpfile:
        result = grdfill(grid=grid, mode="c20", outgrid=tmpfile.name)
        assert result is None  # return value is None
        assert os.path.exists(path=tmpfile.name)  # check that outgrid exists
        result = grdinfo(tmpfile.name, per_column=True).strip()
        assert result == "-5 5 -5 5 -5130.5 inf 1 1 10 10 1 1"

def test_grdfill_required_args(grid):
    """
    Test that grdfill fails without arguments for `mode` and `L`.
    """
    with pytest.raises(GMTInvalidInput):
        grdfill(grid=grid)


text:
<?php namespace MightyPork\Wrack;

class StructureException extends BaseException {}


text:
Gossip algorithm implementation

# References
Socket programming in C on Linux – tutorial by Silver Moon
http://www.binarytides.com/socket-programming-c-linux-tutorial/

Socket Programming in C/C++: Handling multiple clients on server without multi threading by Akshat Sinha
http://www.geeksforgeeks.org/socket-programming-in-cc-handling-multiple-clients-on-server-without-multi-threading/

C Socket Programming for Linux with a Server and Client Example Code by HIMANSHU ARORA on DECEMBER 19, 2011
http://www.thegeekstuff.com/2011/12/c-socket-programming/?utm_source=feedburner


text:
void VersionManagerDialog::gameDirChanged()
{
    ui->txtGameDir->setEnabled(ui->chkGameDir->isChecked());
    ui->btnSelGameDir->setEnabled(ui->chkGameDir->isChecked());
}

void VersionManagerDialog::javaDirChanged()
{
    ui->txtJavaDir->setEnabled(ui->chkJavaDir->isChecked());
    ui->btnSelJavaDir->setEnabled(ui->chkJavaDir->isChecked());
}

void VersionManagerDialog::javaArgsChanged()
{
    ui->txtJavaArgs->setEnabled(ui->chkJavaArgs->isChecked());
}

void VersionManagerDialog::resolutionChanged()
{
    ui->label->setEnabled(ui->chkResolution->isChecked());
    ui->txtWidth->setEnabled(ui->chkResolution->isChecked());
    ui->txtHeight->setEnabled(ui->chkResolution->isChecked());
}

void VersionManagerDialog::fullscreenChanged()
{
    pro.fullscreen = ui->chkFullscreen->isChecked();
    pro.hasFullScreen = true;
}

VersionManagerDialog::VersionManagerDialog(QString ver, Profile pro, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::VersionManagerDialog)
{
    ui->setupUi(this);

    this->pro = Profile(pro);

    this->setWindowTitle("Minecraft Version: " + ver);
    ui->chkGameDir->setChecked(pro.hasGameDir);
    if(pro.hasGameDir)
        ui->txtGameDir->setText(pro.gameDir);
    ui->chkJavaDir->setChecked(pro.hasJavaDir);
    if(pro.hasJavaDir)
        ui->txtJavaDir->setText(pro.javaDir);
    ui->chkJavaArgs->setChecked(pro.hasJavaArgs);
    if(pro.hasJavaArgs)
        ui->txtJavaArgs->setText(pro.javaArgs);
    ui->chkResolution->setChecked(pro.hasResolution);
    if(pro.hasResolution)
    {
        ui->txtHeight->setText(QString::number(pro.r.height));
        ui->txtWidth->setText(QString::number(pro.r.width));
    }
    ui->chkFullscreen->setChecked(pro.hasFullScreen);

    gameDirChanged();
    javaArgsChanged();
    javaDirChanged();
    resolutionChanged();
    fullscreenChanged();
}

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

void VersionManagerDialog::on_btnSelGameDir_clicked()
{
    pro.gameDir = QFileDialog::getExistingDirectory();
    ui->txtGameDir->setText(pro.gameDir);
}

void VersionManagerDialog::on_btnSelJavaDir_clicked()
{
    pro.javaDir = QFileDialog::getExistingDirectory();
    ui->txtJavaDir->setText(pro.javaDir);
}

void VersionManagerDialog::on_chkFullscreen_clicked()
{
    fullscreenChanged();
}

void VersionManagerDialog::on_chkGameDir_clicked()
{
    gameDirChanged();
}

void VersionManagerDialog::on_chkJavaDir_clicked()
{
    javaDirChanged();
}

void VersionManagerDialog::on_chkJavaArgs_clicked()
{
    javaArgsChanged();
}

void VersionManagerDialog::on_chkResolution_clicked()
{
    resolutionChanged();
}

void VersionManagerDialog::on_buttonBox_accepted()
{
    pro.hasGameDir = ui->chkGameDir->isChecked();
    pro.gameDir = ui->txtGameDir->text();
    pro.hasJavaDir = ui->chkJavaDir->isChecked();
    pro.javaDir = ui->txtJavaDir->text();
    pro.hasJavaArgs = ui->chkJavaArgs->isChecked();
    pro.javaArgs = ui->chkJavaArgs->text();
    pro.hasResolution = ui->chkResolution->isChecked();
    pro.r.width = ui->txtWidth->text().toInt();
    pro.r.height = ui->txtHeight->text().toInt();
    pro.hasFullScreen = pro.fullscreen = ui->chkFullscreen->isChecked();

    ProfilesManager::add(pro);
    ProfilesManager::save();
}


text:
<?php

use Hubzero\Content\Migration\Base;

// No direct access
defined('_HZEXEC_') or die();

/**
 * Migration script for changing 'group_id' into 'scope_id' and adding 'access' field
 **/
class Migration20141029112543ComBlog extends Base
{
	/**
	 * Up
	 **/
	public function up()
	{
		if ($this->db->tableExists('#__blog_entries'))
		{
			if (!$this->db->tableHasField('#__blog_entries', 'access'))
			{
				$query = "ALTER TABLE `#__blog_entries` ADD `access` TINYINT(3)  NOT NULL  DEFAULT '0'";
				$this->db->setQuery($query);
				$this->db->query();
			}

			if (!$this->db->tableHasField('#__blog_entries', 'scope_id'))
			{
				$query = "ALTER TABLE `#__blog_entries` CHANGE `group_id` `scope_id` INT(11)  NOT NULL  DEFAULT '0';";
				$this->db->setQuery($query);
				$this->db->query();

				$query = "UPDATE `#__blog_entries` SET `scope_id`=`created_by` WHERE `scope`='member' AND `scope_id`=0";
				$this->db->setQuery($query);
				$this->db->query();
			}
		}
	}

	/**
	 * Down
	 **/
	public function down()
	{
		if ($this->db->tableExists('#__blog_entries'))
		{
			if ($this->db->tableHasField('#__blog_entries', 'access'))
			{
				$query = "ALTER TABLE `#__blog_entries` DROP `access`";
				$this->db->setQuery($query);
				$this->db->query();
			}

			if ($this->db->tableHasField('#__blog_entries', 'scope_id'))
			{
				$query = "ALTER TABLE `#__blog_entries` CHANGE `scope_id` `group_id` INT(11)  NOT NULL  DEFAULT '0';";
				$this->db->setQuery($query);
				$this->db->query();

				$query = "UPDATE `#__blog_entries` SET `group_id`='0' WHERE `scope`='member' AND `group_id`>0";
				$this->db->setQuery($query);
				$this->db->query();
			}
		}
	}
}


text:
from django.conf import settings
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from django.contrib.auth import authenticate, get_backends
from django.contrib.auth.views import login as django_login_page, \
    logout_then_login as django_logout_then_login
from django.core.urlresolvers import reverse
from zerver.decorator import authenticated_json_post_view, require_post, \
    process_client, do_login
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, \
    HttpResponseNotFound
from django.middleware.csrf import get_token
from django.shortcuts import redirect, render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_GET
from django.utils.translation import ugettext as _
from django.core import signing
from six.moves import urllib
from typing import Any, Dict, List, Optional, Tuple, Text

from confirmation.models import Confirmation, create_confirmation_link
from zerver.context_processors import zulip_default_context
from zerver.forms import HomepageForm, OurAuthenticationForm, \
    WRONG_SUBDOMAIN_ERROR
from zerver.lib.mobile_auth_otp import is_valid_otp, otp_encrypt_api_key
from zerver.lib.request import REQ, has_request_variables, JsonableError
from zerver.lib.response import json_success, json_error
from zerver.lib.utils import get_subdomain, is_subdomain_root_or_alias
from zerver.lib.validator import validate_login_email
from zerver.models import PreregistrationUser, UserProfile, remote_user_to_email, Realm, \
    get_realm
from zerver.views.registration import create_preregistration_user, get_realm_from_request, \
    redirect_and_log_into_subdomain, redirect_to_deactivation_notice
from zerver.signals import email_on_new_login
from zproject.backends import password_auth_enabled, dev_auth_enabled, \
    github_auth_enabled, google_auth_enabled, ldap_auth_enabled, \
    ZulipLDAPConfigurationError, ZulipLDAPAuthBackend
from version import ZULIP_VERSION

import hashlib
import hmac
import jwt
import logging
import requests
import time
import ujson

def maybe_send_to_registration(request, email, full_name='', password_required=True):
    # type: (HttpRequest, Text, Text, bool) -> HttpResponse

    realm = get_realm_from_request(request)
    from_multiuse_invite = False
    multiuse_obj = None
    streams_to_subscribe = None
    multiuse_object_key = request.session.get("multiuse_object_key", None)
    if multiuse_object_key is not None:
        from_multiuse_invite = True
        multiuse_obj = Confirmation.objects.get(confirmation_key=multiuse_object_key).content_object
        realm = multiuse_obj.realm
        streams_to_subscribe = multiuse_obj.streams.all()

    form = HomepageForm({'email': email}, realm=realm, from_multiuse_invite=from_multiuse_invite)
    request.verified_email = None
    if form.is_valid():
        # Construct a PreregistrationUser object and send the user over to
        # the confirmation view.
        prereg_user = None
        if settings.ONLY_SSO:
            try:
                prereg_user = PreregistrationUser.objects.filter(email__iexact=email).latest("invited_at")
            except PreregistrationUser.DoesNotExist:
                prereg_user = create_preregistration_user(email, request,
                                                          password_required=password_required)
        else:
            prereg_user = create_preregistration_user(email, request,
                                                      password_required=password_required)

        if multiuse_object_key is not None:
            del request.session["multiuse_object_key"]
            request.session.modified = True
            if streams_to_subscribe is not None:
                prereg_user.streams = streams_to_subscribe
            prereg_user.save()

        return redirect("".join((
            create_confirmation_link(prereg_user, request.get_host(), Confirmation.USER_REGISTRATION),
            '?full_name=',
            # urllib does not handle Unicode, so coerece to encoded byte string
            # Explanation: http://stackoverflow.com/a/5605354/90777
            urllib.parse.quote_plus(full_name.encode('utf8')))))
    else:
        url = reverse('register')
        return render(request,
                      'zerver/accounts_home.html',
                      context={'form': form, 'current_url': lambda: url,
                               'from_multiuse_invite': from_multiuse_invite},
                      )

def redirect_to_subdomain_login_url():
    # type: () -> HttpResponseRedirect
    login_url = reverse('django.contrib.auth.views.login')
    redirect_url = login_url + '?subdomain=1'
    return HttpResponseRedirect(redirect_url)

def redirect_to_config_error(error_type):
    # type: (str) -> HttpResponseRedirect
    return HttpResponseRedirect("/config-error/%s" % (error_type,))

def login_or_register_remote_user(request, remote_username, user_profile, full_name='',
                                  invalid_subdomain=False, mobile_flow_otp=None,
                                  is_signup=False):
    # type: (HttpRequest, Optional[Text], Optional[UserProfile], Text, bool, Optional[str], bool) -> HttpResponse
    if invalid_subdomain:
        # Show login page with an error message
        return redirect_to_subdomain_login_url()

    if user_profile is None or user_profile.is_mirror_dummy:
        # Since execution has reached here, we have verified the user
        # controls an email address (remote_username) but there's no
        # associated Zulip user account.
        if is_signup:
            # If they're trying to sign up, send them over to the PreregistrationUser flow.
            return maybe_send_to_registration(request, remote_user_to_email(remote_username),
                                              full_name, password_required=False)

        # Otherwise, we send them to a special page that asks if they
        # want to register or provided the wrong email and want to go back.
        try:
            validate_email(remote_username)
            invalid_email = False
        except ValidationError:
            # If email address is invalid, we can't send the user
            # PreregistrationUser flow.
            invalid_email = True
        context = {'full_name': full_name,
                   'email': remote_username,
                   'invalid_email': invalid_email}
        return render(request,
                      'zerver/confirm_continue_registration.html',
                      context=context)

    if mobile_flow_otp is not None:
        # For the mobile Oauth flow, we send the API key and other
        # necessary details in a redirect to a zulip:// URI scheme.
        params = {
            'otp_encrypted_api_key': otp_encrypt_api_key(user_profile, mobile_flow_otp),
            'email': remote_username,
            'realm': user_profile.realm.uri,
        }
        # We can't use HttpResponseRedirect, since it only allows HTTP(S) URLs
        response = HttpResponse(status=302)
        response['Location'] = 'zulip://login?' + urllib.parse.urlencode(params)
        # Maybe sending 'user_logged_in' signal is the better approach:
        #   user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile)
        # Not doing this only because over here we don't add the user information
        # in the session. If the signal receiver assumes that we do then that
        # would cause problems.
        email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile)

        # Mark this request as having a logged-in user for our server logs.
        process_client(request, user_profile)
        request._email = user_profile.email

        return response

    do_login(request, user_profile)
    if settings.REALMS_HAVE_SUBDOMAINS and user_profile.realm.subdomain is not None:
        return HttpResponseRedirect(user_profile.realm.uri)
    return HttpResponseRedirect("%s%s" % (settings.EXTERNAL_URI_SCHEME,
                                          request.get_host()))

def remote_user_sso(request):
    # type: (HttpRequest) -> HttpResponse
    try:
        remote_user = request.META["REMOTE_USER"]
    except KeyError:
        raise JsonableError(_("No REMOTE_USER set."))

    # Django invokes authenticate methods by matching arguments, and this
    # authentication flow will not invoke LDAP authentication because of
    # this condition of Django so no need to check if LDAP backend is
    # enabled.
    validate_login_email(remote_user_to_email(remote_user))

    user_profile = authenticate(remote_user=remote_user, realm_subdomain=get_subdomain(request))
    return login_or_register_remote_user(request, remote_user, user_profile)

@csrf_exempt
def remote_user_jwt(request):
    # type: (HttpRequest) -> HttpResponse
    subdomain = get_subdomain(request)
    try:
        auth_key = settings.JWT_AUTH_KEYS[subdomain]
    except KeyError:
        raise JsonableError(_("Auth key for this subdomain not found."))

    try:
        json_web_token = request.POST["json_web_token"]
        options = {'verify_signature': True}
        payload = jwt.decode(json_web_token, auth_key, options=options)
    except KeyError:
        raise JsonableError(_("No JSON web token passed in request"))
    except jwt.InvalidTokenError:
        raise JsonableError(_("Bad JSON web token"))

    remote_user = payload.get("user", None)
    if remote_user is None:
        raise JsonableError(_("No user specified in JSON web token claims"))
    realm = payload.get('realm', None)
    if realm is None:
        raise JsonableError(_("No realm specified in JSON web token claims"))

    email = "%s@%s" % (remote_user, realm)

    try:
        # We do all the authentication we need here (otherwise we'd have to
        # duplicate work), but we need to call authenticate with some backend so
        # that the request.backend attribute gets set.
        return_data = {}  # type: Dict[str, bool]
        user_profile = authenticate(username=email,
                                    realm_subdomain=subdomain,
                                    return_data=return_data,
                                    use_dummy_backend=True)
        if return_data.get('invalid_subdomain'):
            logging.warning("User attempted to JWT login to wrong subdomain %s: %s" % (subdomain, email,))
            raise JsonableError(_("Wrong subdomain"))
    except UserProfile.DoesNotExist:
        user_profile = None

    return login_or_register_remote_user(request, email, user_profile, remote_user)

def google_oauth2_csrf(request, value):
    # type: (HttpRequest, str) -> str
    # In Django 1.10, get_token returns a salted token which changes
    # everytime get_token is called.
    from django.middleware.csrf import _unsalt_cipher_token
    token = _unsalt_cipher_token(get_token(request))
    return hmac.new(token.encode('utf-8'), value.encode("utf-8"), hashlib.sha256).hexdigest()

def start_google_oauth2(request):
    # type: (HttpRequest) -> HttpResponse
    url = reverse('zerver.views.auth.send_oauth_request_to_google')

    if not (settings.GOOGLE_OAUTH2_CLIENT_ID and settings.GOOGLE_OAUTH2_CLIENT_SECRET):
        return redirect_to_config_error("google")

    is_signup = bool(request.GET.get('is_signup'))
    return redirect_to_main_site(request, url, is_signup=is_signup)

def redirect_to_main_site(request, url, is_signup=False):
    # type: (HttpRequest, Text, bool) -> HttpResponse
    main_site_uri = ''.join((
        settings.EXTERNAL_URI_SCHEME,
        settings.EXTERNAL_HOST,
        url,
    ))
    params = {
        'subdomain': get_subdomain(request),
        'is_signup': '1' if is_signup else '0',
    }

    # mobile_flow_otp is a one-time pad provided by the app that we
    # can use to encrypt the API key when passing back to the app.
    mobile_flow_otp = request.GET.get('mobile_flow_otp')
    if mobile_flow_otp is not None:
        if not is_valid_otp(mobile_flow_otp):
            raise JsonableError(_("Invalid OTP"))
        params['mobile_flow_otp'] = mobile_flow_otp

    return redirect(main_site_uri + '?' + urllib.parse.urlencode(params))

def start_social_login(request, backend):
    # type: (HttpRequest, Text) -> HttpResponse
    backend_url = reverse('social:begin', args=[backend])
    if (backend == "github") and not (settings.SOCIAL_AUTH_GITHUB_KEY and settings.SOCIAL_AUTH_GITHUB_SECRET):
        return redirect_to_config_error("github")

    return redirect_to_main_site(request, backend_url)

def start_social_signup(request, backend):
    # type: (HttpRequest, Text) -> HttpResponse
    backend_url = reverse('social:begin', args=[backend])
    return redirect_to_main_site(request, backend_url, is_signup=True)

def send_oauth_request_to_google(request):
    # type: (HttpRequest) -> HttpResponse
    subdomain = request.GET.get('subdomain', '')
    is_signup = request.GET.get('is_signup', '')
    mobile_flow_otp = request.GET.get('mobile_flow_otp', '0')

    if settings.REALMS_HAVE_SUBDOMAINS:
        if ((settings.ROOT_DOMAIN_LANDING_PAGE and subdomain == '') or
                not Realm.objects.filter(string_id=subdomain).exists()):
            return redirect_to_subdomain_login_url()

    google_uri = 'https://accounts.google.com/o/oauth2/auth?'
    cur_time = str(int(time.time()))
    csrf_state = '%s:%s:%s:%s' % (cur_time, subdomain, mobile_flow_otp, is_signup)

    # Now compute the CSRF hash with the other parameters as an input
    csrf_state += ":%s" % (google_oauth2_csrf(request, csrf_state),)

    params = {
        'response_type': 'code',
        'client_id': settings.GOOGLE_OAUTH2_CLIENT_ID,
        'redirect_uri': ''.join((
            settings.EXTERNAL_URI_SCHEME,
            settings.EXTERNAL_HOST,
            reverse('zerver.views.auth.finish_google_oauth2'),
        )),
        'scope': 'profile email',
        'state': csrf_state,
    }
    return redirect(google_uri + urllib.parse.urlencode(params))

def finish_google_oauth2(request):
    # type: (HttpRequest) -> HttpResponse
    error = request.GET.get('error')
    if error == 'access_denied':
        return redirect('/')
    elif error is not None:
        logging.warning('Error from google oauth2 login: %s' % (request.GET.get("error"),))
        return HttpResponse(status=400)

    csrf_state = request.GET.get('state')
    if csrf_state is None or len(csrf_state.split(':')) != 5:
        logging.warning('Missing Google oauth2 CSRF state')
        return HttpResponse(status=400)

    (csrf_data, hmac_value) = csrf_state.rsplit(':', 1)
    if hmac_value != google_oauth2_csrf(request, csrf_data):
        logging.warning('Google oauth2 CSRF error')
        return HttpResponse(status=400)
    cur_time, subdomain, mobile_flow_otp, is_signup = csrf_data.split(':')
    if mobile_flow_otp == '0':
        mobile_flow_otp = None

    is_signup = bool(is_signup == '1')

    resp = requests.post(
        'https://www.googleapis.com/oauth2/v3/token',
        data={
            'code': request.GET.get('code'),
            'client_id': settings.GOOGLE_OAUTH2_CLIENT_ID,
            'client_secret': settings.GOOGLE_OAUTH2_CLIENT_SECRET,
            'redirect_uri': ''.join((
                settings.EXTERNAL_URI_SCHEME,
                settings.EXTERNAL_HOST,
                reverse('zerver.views.auth.finish_google_oauth2'),
            )),
            'grant_type': 'authorization_code',
        },
    )
    if resp.status_code == 400:
        logging.warning('User error converting Google oauth2 login to token: %s' % (resp.text,))
        return HttpResponse(status=400)
    elif resp.status_code != 200:
        logging.error('Could not convert google oauth2 code to access_token: %s' % (resp.text,))
        return HttpResponse(status=400)
    access_token = resp.json()['access_token']

    resp = requests.get(
        'https://www.googleapis.com/plus/v1/people/me',
        params={'access_token': access_token}
    )
    if resp.status_code == 400:
        logging.warning('Google login failed making info API call: %s' % (resp.text,))
        return HttpResponse(status=400)
    elif resp.status_code != 200:
        logging.error('Google login failed making API call: %s' % (resp.text,))
        return HttpResponse(status=400)
    body = resp.json()

    try:
        full_name = body['name']['formatted']
    except KeyError:
        # Only google+ users have a formated name. I am ignoring i18n here.
        full_name = u'{} {}'.format(
            body['name']['givenName'], body['name']['familyName']
        )
    for email in body['emails']:
        if email['type'] == 'account':
            break
    else:
        logging.error('Google oauth2 account email not found: %s' % (body,))
        return HttpResponse(status=400)

    email_address = email['value']

    if not subdomain or mobile_flow_otp is not None:
        # When request was not initiated from subdomain.
        user_profile, return_data = authenticate_remote_user(request, email_address,
                                                             subdomain=subdomain)
        invalid_subdomain = bool(return_data.get('invalid_subdomain'))
        return login_or_register_remote_user(request, email_address, user_profile,
                                             full_name, invalid_subdomain,
                                             mobile_flow_otp=mobile_flow_otp,
                                             is_signup=is_signup)

    try:
        realm = Realm.objects.get(string_id=subdomain)
    except Realm.DoesNotExist:  # nocoverage
        return redirect_to_subdomain_login_url()

    return redirect_and_log_into_subdomain(
        realm, full_name, email_address, is_signup=is_signup)

def authenticate_remote_user(request, email_address, subdomain=None):
    # type: (HttpRequest, str, Optional[Text]) -> Tuple[UserProfile, Dict[str, Any]]
    return_data = {}  # type: Dict[str, bool]
    if email_address is None:
        # No need to authenticate if email address is None. We already
        # know that user_profile would be None as well. In fact, if we
        # call authenticate in this case, we might get an exception from
        # ZulipDummyBackend which doesn't accept a None as a username.
        logging.warning("Email address was None while trying to authenticate "
                        "remote user.")
        return None, return_data
    if subdomain is None:
        subdomain = get_subdomain(request)

    user_profile = authenticate(username=email_address,
                                realm_subdomain=subdomain,
                                use_dummy_backend=True,
                                return_data=return_data)
    return user_profile, return_data

def log_into_subdomain(request):
    # type: (HttpRequest) -> HttpResponse
    try:
        # Discard state if older than 15 seconds
        state = request.get_signed_cookie('subdomain.signature',
                                          salt='zerver.views.auth',
                                          max_age=15)
    except KeyError:
        logging.warning('Missing subdomain signature cookie.')
        return HttpResponse(status=400)
    except signing.BadSignature:
        logging.warning('Subdomain cookie has bad signature.')
        return HttpResponse(status=400)

    data = ujson.loads(state)
    if data['subdomain'] != get_subdomain(request):
        logging.warning('Login attempt on invalid subdomain')
        return HttpResponse(status=400)

    email_address = data['email']
    full_name = data['name']
    is_signup = data['is_signup']
    if is_signup:
        # If we are signing up, user_profile should be None. In case
        # email_address already exists, user will get an error message.
        user_profile = None
        return_data = {}  # type: Dict[str, Any]
    else:
        user_profile, return_data = authenticate_remote_user(request, email_address)
    invalid_subdomain = bool(return_data.get('invalid_subdomain'))
    return login_or_register_remote_user(request, email_address, user_profile,
                                         full_name, invalid_subdomain=invalid_subdomain,
                                         is_signup=is_signup)

def get_dev_users(realm=None, extra_users_count=10):
    # type: (Optional[Realm], int) -> List[UserProfile]
    # Development environments usually have only a few users, but
    # it still makes sense to limit how many extra users we render to
    # support performance testing with DevAuthBackend.
    if realm is not None:
        users_query = UserProfile.objects.select_related().filter(is_bot=False, is_active=True, realm=realm)
    else:
        users_query = UserProfile.objects.select_related().filter(is_bot=False, is_active=True)

    shakespearian_users = users_query.exclude(email__startswith='extrauser').order_by('email')
    extra_users = users_query.filter(email__startswith='extrauser').order_by('email')
    # Limit the number of extra users we offer by default
    extra_users = extra_users[0:extra_users_count]
    users = list(shakespearian_users) + list(extra_users)
    return users

def redirect_to_misconfigured_ldap_notice(error_type):
    # type: (int) -> HttpResponse
    if error_type == ZulipLDAPAuthBackend.REALM_IS_NONE_ERROR:
        url = reverse('ldap_error_realm_is_none')
    else:
        raise AssertionError("Invalid error type")

    return HttpResponseRedirect(url)

def login_page(request, **kwargs):
    # type: (HttpRequest, **Any) -> HttpResponse
    if request.user.is_authenticated:
        return HttpResponseRedirect("/")
    if is_subdomain_root_or_alias(request) and settings.ROOT_DOMAIN_LANDING_PAGE:
        redirect_url = reverse('zerver.views.registration.find_account')
        return HttpResponseRedirect(redirect_url)

    realm = get_realm_from_request(request)
    if realm and realm.deactivated:
        return redirect_to_deactivation_notice()

    extra_context = kwargs.pop('extra_context', {})
    if dev_auth_enabled():
        if 'new_realm' in request.POST:
            realm = get_realm(request.POST['new_realm'])
        else:
            realm = get_realm_from_request(request)

        users = get_dev_users(realm)
        extra_context['current_realm'] = realm
        extra_context['all_realms'] = Realm.objects.all()

        extra_context['direct_admins'] = [u.email for u in users if u.is_realm_admin]
        extra_context['direct_users'] = [u.email for u in users if not u.is_realm_admin]

        if settings.REALMS_HAVE_SUBDOMAINS and 'new_realm' in request.POST:
            # If we're switching realms, redirect to that realm
            return HttpResponseRedirect(realm.uri)

    try:
        template_response = django_login_page(
            request, authentication_form=OurAuthenticationForm,
            extra_context=extra_context, **kwargs)
    except ZulipLDAPConfigurationError as e:
        assert len(e.args) > 1
        return redirect_to_misconfigured_ldap_notice(e.args[1])

    try:
        template_response.context_data['email'] = request.GET['email']
    except KeyError:
        pass

    try:
        already_registered = request.GET['already_registered']
        template_response.context_data['already_registered'] = already_registered
    except KeyError:
        pass

    try:
        template_response.context_data['subdomain'] = request.GET['subdomain']
        template_response.context_data['wrong_subdomain_error'] = WRONG_SUBDOMAIN_ERROR
    except KeyError:
        pass

    return template_response

def dev_direct_login(request, **kwargs):
    # type: (HttpRequest, **Any) -> HttpResponse
    # This function allows logging in without a password and should only be called in development environments.
    # It may be called if the DevAuthBackend is included in settings.AUTHENTICATION_BACKENDS
    if (not dev_auth_enabled()) or settings.PRODUCTION:
        # This check is probably not required, since authenticate would fail without an enabled DevAuthBackend.
        raise Exception('Direct login not supported.')
    email = request.POST['direct_email']
    user_profile = authenticate(username=email, realm_subdomain=get_subdomain(request))
    if user_profile is None:
        raise Exception("User cannot login")
    do_login(request, user_profile)
    if settings.REALMS_HAVE_SUBDOMAINS and user_profile.realm.subdomain is not None:
        return HttpResponseRedirect(user_profile.realm.uri)
    return HttpResponseRedirect("%s%s" % (settings.EXTERNAL_URI_SCHEME,
                                          request.get_host()))

@csrf_exempt
@require_post
@has_request_variables
def api_dev_fetch_api_key(request, username=REQ()):
    # type: (HttpRequest, str) -> HttpResponse
    """This function allows logging in without a password on the Zulip
    mobile apps when connecting to a Zulip development environment.  It
    requires DevAuthBackend to be included in settings.AUTHENTICATION_BACKENDS.
    """
    if not dev_auth_enabled() or settings.PRODUCTION:
        return json_error(_("Dev environment not enabled."))

    # Django invokes authenticate methods by matching arguments, and this
    # authentication flow will not invoke LDAP authentication because of
    # this condition of Django so no need to check if LDAP backend is
    # enabled.
    validate_login_email(username)

    return_data = {}  # type: Dict[str, bool]
    user_profile = authenticate(username=username,
                                realm_subdomain=get_subdomain(request),
                                return_data=return_data)
    if return_data.get("inactive_realm"):
        return json_error(_("Your realm has been deactivated."),
                          data={"reason": "realm deactivated"}, status=403)
    if return_data.get("inactive_user"):
        return json_error(_("Your account has been disabled."),
                          data={"reason": "user disable"}, status=403)
    if user_profile is None:
        return json_error(_("This user is not registered."),
                          data={"reason": "unregistered"}, status=403)
    do_login(request, user_profile)
    return json_success({"api_key": user_profile.api_key, "email": user_profile.email})

@csrf_exempt
def api_dev_get_emails(request):
    # type: (HttpRequest) -> HttpResponse
    if not dev_auth_enabled() or settings.PRODUCTION:
        return json_error(_("Dev environment not enabled."))
    users = get_dev_users()
    return json_success(dict(direct_admins=[u.email for u in users if u.is_realm_admin],
                             direct_users=[u.email for u in users if not u.is_realm_admin]))

@csrf_exempt
@require_post
@has_request_variables
def api_fetch_api_key(request, username=REQ(), password=REQ()):
    # type: (HttpRequest, str, str) -> HttpResponse
    return_data = {}  # type: Dict[str, bool]
    if username == "google-oauth2-token":
        user_profile = authenticate(google_oauth2_token=password,
                                    realm_subdomain=get_subdomain(request),
                                    return_data=return_data)
    else:
        if not ldap_auth_enabled(realm=get_realm_from_request(request)):
            # In case we don't authenticate against LDAP, check for a valid
            # email. LDAP backend can authenticate against a non-email.
            validate_login_email(username)

        user_profile = authenticate(username=username,
                                    password=password,
                                    realm_subdomain=get_subdomain(request),
                                    return_data=return_data)
    if return_data.get("inactive_user"):
        return json_error(_("Your account has been disabled."),
                          data={"reason": "user disable"}, status=403)
    if return_data.get("inactive_realm"):
        return json_error(_("Your realm has been deactivated."),
                          data={"reason": "realm deactivated"}, status=403)
    if return_data.get("password_auth_disabled"):
        return json_error(_("Password auth is disabled in your team."),
                          data={"reason": "password auth disabled"}, status=403)
    if user_profile is None:
        if return_data.get("valid_attestation"):
            # We can leak that the user is unregistered iff they present a valid authentication string for the user.
            return json_error(_("This user is not registered; do so from a browser."),
                              data={"reason": "unregistered"}, status=403)
        return json_error(_("Your username or password is incorrect."),
                          data={"reason": "incorrect_creds"}, status=403)

    # Maybe sending 'user_logged_in' signal is the better approach:
    #   user_logged_in.send(sender=user_profile.__class__, request=request, user=user_profile)
    # Not doing this only because over here we don't add the user information
    # in the session. If the signal receiver assumes that we do then that
    # would cause problems.
    email_on_new_login(sender=user_profile.__class__, request=request, user=user_profile)

    # Mark this request as having a logged-in user for our server logs.
    process_client(request, user_profile)
    request._email = user_profile.email

    return json_success({"api_key": user_profile.api_key, "email": user_profile.email})

def get_auth_backends_data(request):
    # type: (HttpRequest) -> Dict[str, Any]
    """Returns which authentication methods are enabled on the server"""
    if settings.REALMS_HAVE_SUBDOMAINS:
        subdomain = get_subdomain(request)
        try:
            realm = Realm.objects.get(string_id=subdomain)
        except Realm.DoesNotExist:
            # If not the root subdomain, this is an error
            if subdomain != "":
                raise JsonableError(_("Invalid subdomain"))
            # With the root subdomain, it's an error or not depending
            # whether ROOT_DOMAIN_LANDING_PAGE (which indicates whether
            # there are some realms without subdomains on this server)
            # is set.
            if settings.ROOT_DOMAIN_LANDING_PAGE:
                raise JsonableError(_("Subdomain required"))
            else:
                realm = None
    else:
        # Without subdomains, we just have to report what the server
        # supports, since we don't know the realm.
        realm = None
    return {"password": password_auth_enabled(realm),
            "dev": dev_auth_enabled(realm),
            "github": github_auth_enabled(realm),
            "google": google_auth_enabled(realm)}

@csrf_exempt
def api_get_auth_backends(request):
    # type: (HttpRequest) -> HttpResponse
    """Deprecated route; this is to be replaced by api_get_server_settings"""
    auth_backends = get_auth_backends_data(request)
    auth_backends['zulip_version'] = ZULIP_VERSION
    return json_success(auth_backends)

@require_GET
@csrf_exempt
def api_get_server_settings(request):
    # type: (HttpRequest) -> HttpResponse
    result = dict(
        authentication_methods=get_auth_backends_data(request),
        zulip_version=ZULIP_VERSION,
    )
    context = zulip_default_context(request)
    # IMPORTANT NOTE:
    # realm_name, realm_icon, etc. are not guaranteed to appear in the response.
    # * If they do, that means the server URL has only one realm on it
    # * If they don't, the server has multiple realms, and it's not clear which is
    #   the requested realm, so we can't send back these data.
    for settings_item in [
            "email_auth_enabled",
            "require_email_format_usernames",
            "realm_uri",
            "realm_name",
            "realm_icon",
            "realm_description"]:
        if context[settings_item] is not None:
            result[settings_item] = context[settings_item]
    return json_success(result)

@authenticated_json_post_view
@has_request_variables
def json_fetch_api_key(request, user_profile, password=REQ(default='')):
    # type: (HttpRequest, UserProfile, str) -> HttpResponse
    if password_auth_enabled(user_profile.realm):
        if not authenticate(username=user_profile.email, password=password,
                            realm_subdomain=get_subdomain(request)):
            return json_error(_("Your username or password is incorrect."))
    return json_success({"api_key": user_profile.api_key})

@csrf_exempt
def api_fetch_google_client_id(request):
    # type: (HttpRequest) -> HttpResponse
    if not settings.GOOGLE_CLIENT_ID:
        return json_error(_("GOOGLE_CLIENT_ID is not configured"), status=400)
    return json_success({"google_client_id": settings.GOOGLE_CLIENT_ID})

@require_post
def logout_then_login(request, **kwargs):
    # type: (HttpRequest, **Any) -> HttpResponse
    return django_logout_then_login(request, kwargs)


text:
package org.nll.hbase.ui.model;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import java.util.Map;

/**
 *
 * @author fivesmallq
 */
public class HbaseData {

    private String rowkey;
    private Map<String, FamilyData> datas = Maps.newLinkedHashMap();

    public String getRowkey() {
        return rowkey;
    }

    public void setRowkey(String rowkey) {
        this.rowkey = rowkey;
    }

    public Map<String, FamilyData> getDatas() {
        return datas;
    }

    public void setDatas(Map<String, FamilyData> datas) {
        this.datas = datas;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this); //To change body of generated methods, choose Tools | Templates.
    }

}


text:
namespace IECoreHoudini
{

/// Converter which converts from an IECore::Object to a Houdini GU_Detail. This converter
/// creates a single GU_CortexPrimitive containing the Object, and adds it to the detail.
class ToHoudiniCortexObjectConverter : public IECoreHoudini::ToHoudiniGeometryConverter
{
	public :

		IE_CORE_DECLARERUNTIMETYPEDEXTENSION( ToHoudiniCortexObjectConverter, ToHoudiniCortexObjectConverterTypeId, IECoreHoudini::ToHoudiniGeometryConverter );

		ToHoudiniCortexObjectConverter( const IECore::Object *object );

		virtual ~ToHoudiniCortexObjectConverter();

		/// We don't actually transfer any attribs during conversion, but this method can be used to
		/// transfer PrimitiveVariables from the source Object, provided it is an IECore::Primitive,
		/// the GA_Range contains a GU_CortexPrimitive which also holds an IECore::Primitive, and both
		/// Primitives have the same variable sizes.
		virtual void transferAttribs( GU_Detail *geo, const GA_Range &points, const GA_Range &prims ) const;

	protected :

		/// performs conversion from the IECore::Object into the given GU_Detail
		virtual bool doConversion( const IECore::Object *object, GU_Detail *geo ) const;

	private :

		// Used to apply the attributeFilter to the Object, if it is a Primitive
		IECore::ConstObjectPtr filterAttribs( const IECore::Object *object ) const;

		static ToHoudiniGeometryConverter::Description<ToHoudiniCortexObjectConverter> m_description;
};

// register our converter
IE_CORE_DECLAREPTR( ToHoudiniCortexObjectConverter );

}

#endif // IECOREHOUDINI_TOHOUDINICORTEXOBJECTCONVERTER_H


text:
<?php

namespace Academe\Instructions;

use Academe\Contracts\Mapper\Instructions\Count as CountContract;

class Count extends BaseCount implements CountContract
{

}


text:
package com.tdp2.androidclient.server.model;

/**
 * Created by Santi on 30/05/2015.
 */
public class UserPreferences {
    public Preferences preferences;
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!--

-->

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout android:id="@+id/body"
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:baselineAligned="false"
        android:paddingLeft="8dip"
        android:paddingTop="10dip"
        android:paddingRight="8dip"
        android:paddingBottom="10dip">

        <ProgressBar android:id="@android:id/progress"
            style="@android:style/Widget.ProgressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:max="10000"
            android:layout_marginRight="12dip" />

        <TextView android:id="@+id/message"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="22sp"
            android:layout_gravity="center_vertical" />

    </LinearLayout>
</FrameLayout>


text:
<?php

/**
 * Decorates a DataObject, giving it the ability to be indexed and searched by
 * Zend_Search_Lucene.
 *
 * To define custom columns, you should this line into your site _config.php:
 *
 *
 * ZendSearchLuceneSearchable::enable(array());
 *
 *
 * This sets up things without defining columns for any classes.
 *
 * After this, you can define non-default columns to index for each object by using:
 *
 *
 * SS_Object::add_extension(
 *      'SiteTree',
 *      "ZendSearchLuceneSearchable('Title,MenuTitle,Content,MetaTitle,MetaDescription,MetaKeywords')"
 * );
 *
 *
 * See the docs for the __construct function for advanced config options.
 *
 * @package lucene-silverstripe-module
 * @author Darren Inwood <darren.inwood@chrometoaster.com>
 */

class ZendSearchLuceneSearchable extends DataExtension {

    /**
     * Number of results per pagination page
     * @static
     */
    public static $pageLength = 10;

    /**
     * Always show this many pages in pagination (can be zero)
     * @static
     */
    public static $alwaysShowPages = 3;

    /**
     * Maximum number of pages shown in pagination (ellipsis are used to indicate more pages)
     * @static
     */
    public static $maxShowPages = 8;

    /**
     * Encoding in which indexes are created and searches made.
     * @static
     */
    public static $encoding = 'utf-8';

    /**
     * Full filesystem path to the directory where the index files should live
     * @static
     */
    public static $cacheDirectory = TEMP_FOLDER;

    /**
     * Boolean indicating whether we should rebuild the index whenever a
     * dev/build is run.
     * @static
     */
    public static $reindexOnDevBuild = true;

    /**
     * Fields which are also indexed in addition to content fields.
     * @static
     */
    protected static $extraSearchFields = array('ID','ClassName','LastEdited');

    /**
     * Default fields to index for each Searchable decorated class.  This isn't
     * public - it's just a convenience thing, for those people who just want to
     * get up and running with indexing SiteTree and File with minimum
     * configuration.
     * @access private
     * @static
     */
    protected static $defaultColumns = array(
		'SiteTree' => 'Title,MenuTitle,Content,MetaTitle,MetaDescription,MetaKeywords',
		'File' => 'Filename,Title,Content'
	);

    /**
     * Fields which should be indexed as 'unstored' by default.
     * @access private
     * @static
     */
    protected static $unstored_fields = array(
        'MenuTitle', 'MetaTitle', 'MetaDescription', 'MetaKeywords'
    );

    /**
     * Fields which should be indexed as 'unindexed' by default.
     * @access private
     * @static
     */
    protected static $unindexed_fields = array(
        'LastEdited', 'Created'
    );

    /**
     * Fields which should be indexed as 'keyword' by default.
     * @access private
     * @static
     */
    protected static $keyword_fields = array(
        'ID', 'ClassName'
    );

    /**
     * The fields which can be searched for each DataObject class, and indexing
     * info for each field.  This is not public, and should be set by configuring
     * the class via the SS_Object::add_extension argument.
     * @access private
     */
    protected $fieldConfig = null;

    /**
     * The raw string used to configure the object's fields.  We have to store it and parse
     * it on first use at runtime, because the owner of the decorator isn't set in
     * the constructor.
     */
    protected $_fieldConfig = null;

    /**
     * The config options for this DataObject class.  This is not public, and
     * should be set by configuring the class via the SS_Object::add_extension argument.
     */
    protected $classConfig = null;

    /**
     * The raw string used to configure the object.  We have to store it and parse
     * it on first use at runtime, because the owner of the decorator isn't set in
     * the constructor.
     */
    protected $_classConfig = null;

    /**
     * Called by the system when initialising each instance of the decorated
     * class.  The argument comes from the SS_Object::add_extension call in the
     * project's _config.php file.
     *
     * Field configuration can simply be a comma-separated list of fieldnames to scan,
     * or alternatively can be a json-encoded string containing extended config
     * information.  Or you can leave it blank.
     *
     * All keys are optional for each fieldname.  The format for $fieldConfig is:
     *
     *
     * array(
     *    'FieldName' => array(
     *        'name' => 'StoredName',
     *        'type' => 'keyword|unindexed|unstored|text',
     *        'content_filter' => [callback]|false
     *     ),
     *     [...]
     * )
     *
     *
     * FieldName - the name of the field on the decorated class
     *
     * name - the name to store this as in the document.  Default is the same as
     * the FieldName.  The FieldName of 'ID' is a special case, this will always
     * use a name of 'ObjectID' as this is used internally.
     *
     * type - the type of indexing to use.  Default is 'text'.
     *
     * content_filter - a callback that should be used to transform the field value
     * prior to being indexed.  The callback will be called with one argument,
     * the field value as a string, and should return the transformed field value
     * also as a string.  Could be useful for eg. turning date strings into unix
     * timestamps prior to indexing.  A value of false will indicate that there
     * should be no content filtering, which is the default.
     *
     * Class-level configuration should be a json-encoded string containing
     * key-value pairs for the class-level config options.  The format for
     * $classConfig is:
     *
     *
     * array(
     *     'index_filter' => 'WHERE clause'
     * )
     *
     *
     * index_filter - a string to be used as the second argument to
     * DataObject::get().  An example of how this might be used in a complex
     * situation:
     *
     * '"ID" IN ( SELECT "ID" FROM "This" LEFT JOIN "Other" ON "This"."ID" = "Other"."ThisID" WHERE "Other"."ThisID" IS NOT NULL )'
     */
	public function __construct($fieldConfig=null, $classConfig=null) {
		parent::__construct();
		$this->_fieldConfig = $fieldConfig;
		$this->_classConfig = $classConfig;
	}

    /**
     * Set up the config for each instantiated object for this class.
     * @access private
     */
    private function setLuceneFieldConfig($config) {
        $this->fieldConfig = array();
        if ( ! $config ) return;

        // Is it a JSON-encoded array?
        $json = json_decode($config, true);
        if ( is_array($json) ) $config = $json;

        // Is is a comma-separated string?
        if ( ! is_array($config) ) {
            $config = explode(',', $config);
            if ( is_array($config) ) $config = array_flip($config);
        }

        // Is the config bad?
	    if ( ! is_array($config) ) {
	        user_error('Your Lucene field config for the class '.$this->owner->class
	            .' was bad. It needs to be a JSON encoded array, or a comma-separated'
	            .' list of fieldnames.  See the documentation for details.');
	    }

        // Do we have ObjectID in there?  Users can't use that, as it's how we track
        // the ID field internally.
         if (
            array_key_exists('ObjectID', $config)
            && (
                !is_array($config['ObjectID'])
                || !isset($config['ObjectID']['name'])
                || $config['ObjectID']['name'] == 'ObjectID'
            )
         ) {
            user_error('ObjectID is reserved for internal Lucene use. Try configuring '
            .'that field to be indexed using a different name via the \'name\' config option. '
            .'See the documentation for details.');

         }

        // Also configure extra search fields using default config options
        $config = array_merge(array_flip($this->getExtraSearchFields()), $config);

	    // Set up default info for each field if nothing was provided.
	    foreach( $config as $fieldName => $data ) {
            if ( ! is_array($data) ) $data = array();
            $tmp = array(
                'name' => $fieldName,
                'type' => false,
                'content_filter' => false
            );
            $tmp = array_merge($tmp, $data);
            // Default to unstored indexing
            if ( !$tmp['type'] && in_array($fieldName, self::$unstored_fields) ) {
                $tmp['type'] = 'unstored';
            }
            // Default to unindexed indexing
            if ( !$tmp['type'] && in_array($fieldName, self::$unindexed_fields) ) {
                $tmp['type'] = 'unindexed';
            }
            // Default to keyword indexing
            if ( !$tmp['type'] && in_array($fieldName, self::$keyword_fields) ) {
                $tmp['type'] = 'keyword';
            }
            // Default to text indexing
            if ( !$tmp['type'] ) $tmp['type'] = 'text';
            $this->fieldConfig[$fieldName] = $tmp;
	    }
    }

    /**
     * Returns the field config array for a given field.  Throws a user_error if
     * the field doesn't exist in the config.
     *
     *
     * array(
     *     'name' => 'FieldName',
     *     'type' => 'keyword|unindexed|unstored|text',
     *     'content_filter' => [callback]|false
     * )
     *
     */
    public function getLuceneFieldConfig($fieldName) {
        if ( $this->fieldConfig === null ) $this->setLuceneFieldConfig($this->_fieldConfig);
        if ( array_key_exists($fieldName, $this->fieldConfig) ) {
            return $this->fieldConfig[$fieldName];
        }
        user_error("You asked for the config for a field that hasn't had its config set up.");
    }

    /**
     * Set up search configuration for the class.
     * @access private
     */
    private function setLuceneClassConfig($config) {
        // Default to filtering out unpublished and unsearchable SiteTree objects
        $this->classConfig = array(
            'index_filter' => $this->owner->is_a('SiteTree')
                ? "\"ShowInSearch\" = 1"
                : ''
        );
        if ( ! $config ) return;

        // Is it a JSON-encoded array?
        $json = json_decode($config, true);
        if ( is_array($json) ) $config = $json;

        // Is the config bad?
	    if ( ! is_array($config) ) {
	        user_error(
	            'Your Lucene class config for the class '.$this->owner->class
	            .' was bad. It needs to be a JSON encoded array.  See the '
	            .'documentation for details.'
	        );
	    }

        $this->classConfig = $config;
    }

    /**
     * Returns the class config array.
     * Should be called as singleton('ClassName')->getLuceneClassConfig().
     */
    public function getLuceneClassConfig() {
        if ( $this->classConfig === null ) $this->setLuceneClassConfig($this->_classConfig);
        return $this->classConfig;
    }

	/**
	 * Enable the default configuration of Zend Search Lucene searching on the
	 * given data classes.
	 *
	 * @param   Array   $searchableClasses  An array of classnames to scan.  Can
	 *                                      choose from SiteTree and/or File.
	 *                                      To not scan any classes, for example
	 *                                      if we will define custom fields to scan,
	 *                                      pass in an empty array.
	 *                                      Defaults to scan SiteTree and File.
	 */
	public static function enable($searchableClasses = array('SiteTree', 'File')) {
        // We can't enable the search engine if we don't have QueuedJobs installed.
        if ( ! ClassInfo::exists('QueuedJobService') ) {
            die(''._t('ZendSearchLucene.ERROR','Error').': '
                ._t('ZendSearchLucene.QueuedJobsRequired',
                'Lucene requires the Queued jobs module.  See '
                .''
                .'http://www.silverstripe.org/queued-jobs-module/.')
            );
        }
		if(!is_array($searchableClasses)) $searchableClasses = array($searchableClasses);
		foreach($searchableClasses as $class) {
			if(isset(self::$defaultColumns[$class])) {
				SS_Object::add_extension($class, "ZendSearchLuceneSearchable('".self::$defaultColumns[$class]."')");
			} else {
				user_error("I don't know the default search columns for class '$class'");
				return;
			}
		}
		SS_Object::add_extension('ContentController', 'ZendSearchLuceneContentController');
		DataObject::add_extension('SiteConfig', 'ZendSearchLuceneSiteConfig');
		SS_Object::add_extension('LeftAndMain', 'ZendSearchLuceneCMSDecorator');
		SS_Object::add_extension('StringField', 'ZendSearchLuceneTextHighlightDecorator');
		// Set up default encoding and analyzer
        Zend_Search_Lucene_Search_QueryParser::setDefaultEncoding(ZendSearchLuceneSearchable::$encoding);
        Zend_Search_Lucene_Analysis_Analyzer::setDefault(
            new StandardAnalyzer_Analyzer_Standard_English()
        );
	}

    /**
     * Indexes the object after it has been written to the database.
     */
    public function onAfterWrite() {
        // skip indexing of other pages than current.
        // otherwise all SiteTree::DependentPages() are newly indexed as well,
        // which harms performance if there are many internal links to this page
        if (is_a($this->owner, 'SiteTree')
            && ($controller = Controller::curr())
            && $controller->hasMethod('currentPageID')
            && $this->owner->ID != $controller->currentPageID()
        ) {
            return;
        }
        // Obey index filter rules
        $objs = ZendSearchLuceneWrapper::getAllIndexableObjects($this->owner->ClassName);
        ZendSearchLuceneWrapper::delete($this->owner);
        foreach( $objs as $obj ) {
            // $obj is an array with ClassName and ID of the indexable object
            if ( ! is_array($obj) ) continue;
            if ( ! is_object($this->owner) ) continue;
            if ( $obj[0] == $this->owner->class && $obj[1] == $this->owner->ID ) {
                ZendSearchLuceneWrapper::index($this->owner);
            }
        }
    }

    /**
     * Removes the object from the search index after it has been deleted.
     */
    function onAfterDelete() {
        ZendSearchLuceneWrapper::delete($this->owner);
    }

    /**
     * Return an array of search field names.
     *
     * @return  Array   An array of strings, each being the name of a field that
     *                  is searched.
     */
    public function getSearchedVars() {
        return array_merge(
            self::$extraSearchFields,
            $this->getSearchFields(),
            array('Link')
        );
    }

    /**
     * Get an array of the class' searched fieldnames from other classes.
     *
     * @return  Array   An array of strings, each being the name of a field that
     *                  is indexed.
     */
    public function getSearchFields() {
        if ( $this->fieldConfig === null ) $this->setLuceneFieldConfig($this->_fieldConfig);
        return array_keys($this->fieldConfig);
    }

    /**
     * Get an array of the class' extra search fieldnames that are indexed but
     * not searched.
     *
     * @return  Array   An array of strings, each being the name of a field that
     *                  is indexed but not searched.
     */
    public function getExtraSearchFields() {
        return self::$extraSearchFields;
    }

    /**
     * Rebuilds the search index whenever a dev/build is run.
     *
     * This can be turned off by adding the following to your _config.php:
     *
     *
     * ZendSearchLuceneSearchable::$reindexOnDevBuild = false;
     *
     */
    public function requireDefaultRecords() {
        if ( ! self::$reindexOnDevBuild ) return;
        ZendSearchLuceneWrapper::rebuildIndex();
        echo '
'
            . _t('ZendSearchLucene.RebuildSuccessMessage', 'A Lucene search index rebuild job has been added to the Jobs queue.')
            .'
';
        // Only run once
        self::$reindexOnDevBuild = false;
    }

}


text: Lorem ipsum


text:
    <meta charset="UTF-8">
    <title>MTFraction.rightDelimiter - </title>
    <link rel="stylesheet" href="../../style.css">

com.agog.mathdisplay.parse / MTFraction / rightDelimiter

rightDelimiter

var rightDelimiter: String?

An optional delimiter for a fraction on the right.


text:
class Crypto
  def initialize(input)
    @text = input
  end

  def normalize_plaintext
    @text.downcase.chars.select { |char| char.match(/\w/) }.join
  end

  def size
    len = normalize_plaintext.length
    1.upto(len) do |i|
      return i if i**2 >= len
    end
  end

  def plaintext_segments
    normalize_plaintext.chars.each_slice(size).map(&:join)
  end

  def ciphertext
    encode.join('').strip
  end

  def normalize_ciphertext
    encode.map(&:join).join(' ').strip
  end

  private

  def encode
    plaintext_segments.each_with_object([]) do |segment, square|
      segment.chars.each_with_index do |char, i|
        square[i] ||= []
        square[i] << char
      end
    end
  end
end


text:
ACCEPTED

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

#### Published in
Arch. Protistenk. , 67, 261.

#### Original name
null

### Remarks
null


text: google sheets interacting google scattered-chart element, created for spaghettiopendata.org