text:
require 'rails_helper'

feature 'Dashboard', truncate: true, js: true do
  let!(:account_1) { FactoryGirl.create :account, name: 'Test Account 1', balance: 2000.00 }
  let!(:account_2) { FactoryGirl.create :account, name: 'Test Account 2', balance: 123.45 }
  let!(:account_3) { FactoryGirl.create :account, name: 'Test Account 3', balance: -500.00 }
  let!(:unsorted_transaction) { FactoryGirl.create :transaction, account: account_1 }

  before do
    visit '/'
  end

  it 'sets the correct page title' do
    expect_page_title_to_be 'Dashboard'
  end

  it 'shows the heading' do
    expect(page).to have_content 'Dashboard'
    expect(page).to have_content 'My finances'
  end

  it 'shows the accounts' do
    expect(page).to have_content 'Test Account 1'
    expect(page).to have_content 'Test Account 2'
    expect(page).to have_content 'Test Account 3'
  end

  it 'shows the accout balances' do
    expect(page).to have_content '$2,000.00'
    expect(page).to have_content '$123.45'
    expect(page).to have_content '$-500.00'
  end

  it 'shows the balance summary' do
    expect(page).to have_content 'Total cash: $2,123.45'
    expect(page).to have_content 'Total debt: $500.00'
    expect(page).to have_content 'Difference: $1,623.45'
  end

  it 'shows the unsorted transactions link' do
    expect(page).to have_link '1 unsorted', href: "/accounts/#{account_1.id}?tab=unsorted&page=1"
  end
end


text:
{{name}} CRUD

Папки приложения

     {{folder.name}}

Документы в папке {{selectedFolder.name}}

    {{doc.dateItem}} -- {{doc.name}} -- {{doc.id}}

<button (click)="test_search()">Test search</button>
<button (click)="test_searchObservable()">Test search Observable</button>

 {{test}}

Input date

redpajama_set_name: RedPajamaGithub


text:
package com.eliza.experimental.v2.action;

@FunctionalInterface
public interface Action extends Runnable {

    void execute() throws Exception;

    default void run() {
        try {
            execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}


text:
package com.sixt.service.framework.configuration;

/**
 * To provide configuration data in a way specific to your environment, implement
 * a class with the ConfigurationPlugin annotation and implement this interface.
 * Early in service startup, initialize() will be called, and you will have the
 * opportunity to do whatever you wish.  At Sixt, we have a dedicated microservice
 * to serve the configuration data, and long-polling is implemented to get
 * immediate updates when a configuration value is modified / added.
 */
public interface ConfigurationProvider {

    void initialize();

}


text:
package ch.qos.logback.classic;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.List;

import org.junit.Test;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import ch.qos.logback.core.status.Status;

public class LoggerTest {

    LoggerContext lc = new LoggerContext();
    Logger root = lc.getLogger(Logger.ROOT_LOGGER_NAME);
    Logger loggerTest = lc.getLogger(LoggerTest.class);

    ListAppender<ILoggingEvent> listAppender = new ListAppender<ILoggingEvent>();

    @Test
    public void smoke() {
        ListAppender<ILoggingEvent> listAppender = new ListAppender<ILoggingEvent>();
        listAppender.start();
        root.addAppender(listAppender);
        Logger logger = lc.getLogger(LoggerTest.class);
        assertEquals(0, listAppender.list.size());
        logger.debug("hello");
        assertEquals(1, listAppender.list.size());
    }

    @Test
    public void testNoStart() {
        // listAppender.start();
        listAppender.setContext(lc);
        root.addAppender(listAppender);
        Logger logger = lc.getLogger(LoggerTest.class);
        logger.debug("hello");

        List<Status> statusList = lc.getStatusManager().getCopyOfStatusList();
        Status s0 = statusList.get(0);
        assertEquals(Status.WARN, s0.getLevel());
        assertTrue(s0.getMessage().startsWith("Attempted to append to non started"));
    }

    @Test
    public void testAdditive() {
        listAppender.start();
        root.addAppender(listAppender);
        loggerTest.addAppender(listAppender);
        loggerTest.setAdditive(false);
        loggerTest.debug("hello");
        // 1 instead of two, since logger is not additive
        assertEquals(1, listAppender.list.size());
    }

    @Test
    public void testRootLogger() {
        Logger logger = (Logger) LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
        LoggerContext lc = logger.getLoggerContext();

        assertNotNull("Returned logger is null", logger);
        assertEquals("Return logger isn't named root", logger.getName(), Logger.ROOT_LOGGER_NAME);
        assertTrue("logger instances should be indentical", logger == lc.root);
    }

    @Test
    public void testBasicFiltering() throws Exception {
        listAppender.start();
        root.addAppender(listAppender);
        root.setLevel(Level.INFO);
        loggerTest.debug("x");
        assertEquals(0, listAppender.list.size());
        loggerTest.info("x");
        loggerTest.warn("x");
        loggerTest.error("x");
        assertEquals(3, listAppender.list.size());
    }

    void checkLevelThreshold(Logger logger, Level threshold) {

        if (Level.ERROR_INT >= threshold.levelInt) {
            assertTrue(logger.isErrorEnabled());
            assertTrue(logger.isEnabledFor(Level.ERROR));
        } else {
            assertFalse(logger.isErrorEnabled());
            assertFalse(logger.isEnabledFor(Level.ERROR));
        }

        if (Level.WARN_INT >= threshold.levelInt) {
            assertTrue(logger.isWarnEnabled());
            assertTrue(logger.isEnabledFor(Level.WARN));
        } else {
            assertFalse(logger.isWarnEnabled());
            assertFalse(logger.isEnabledFor(Level.WARN));
        }
        if (Level.INFO_INT >= threshold.levelInt) {
            assertTrue(logger.isInfoEnabled());
            assertTrue(logger.isEnabledFor(Level.INFO));
        } else {
            assertFalse(logger.isInfoEnabled());
            assertFalse(logger.isEnabledFor(Level.INFO));
        }
        if (Level.DEBUG_INT >= threshold.levelInt) {
            assertTrue(logger.isDebugEnabled());
            assertTrue(logger.isEnabledFor(Level.DEBUG));
        } else {
            assertFalse(logger.isDebugEnabled());
            assertFalse(logger.isEnabledFor(Level.DEBUG));
        }
        if (Level.TRACE_INT >= threshold.levelInt) {
            assertTrue(logger.isTraceEnabled());
            assertTrue(logger.isEnabledFor(Level.TRACE));
        } else {
            assertFalse(logger.isTraceEnabled());
            assertFalse(logger.isEnabledFor(Level.TRACE));
        }
    }

    @Test
    public void innerClass_I() {
        root.setLevel(Level.DEBUG);
        Logger a = lc.getLogger("a");
        a.setLevel(Level.INFO);
        Logger a_b = lc.getLogger("a$b");
        assertEquals(Level.INFO, a_b.getEffectiveLevel());
    }

    @Test
    public void innerClass_II() {
        root.setLevel(Level.DEBUG);
        Logger a = lc.getLogger(this.getClass());
        a.setLevel(Level.INFO);
        Logger a_b = lc.getLogger(new Inner().getClass());
        assertEquals(Level.INFO, a_b.getEffectiveLevel());
    }

    class Inner {
    }

    @Test
    public void testEnabled_All() throws Exception {
        root.setLevel(Level.ALL);
        checkLevelThreshold(loggerTest, Level.ALL);
    }

    @Test
    public void testEnabled_Debug() throws Exception {
        root.setLevel(Level.DEBUG);
        checkLevelThreshold(loggerTest, Level.DEBUG);
    }

    @Test
    public void testEnabled_Info() throws Exception {
        root.setLevel(Level.INFO);
        checkLevelThreshold(loggerTest, Level.INFO);
    }

    @Test
    public void testEnabledX_Warn() throws Exception {
        root.setLevel(Level.WARN);
        checkLevelThreshold(loggerTest, Level.WARN);
    }

    public void testEnabledX_Errror() throws Exception {
        root.setLevel(Level.ERROR);
        checkLevelThreshold(loggerTest, Level.ERROR);
    }

    @Test
    public void testEnabledX_Off() throws Exception {
        root.setLevel(Level.OFF);
        checkLevelThreshold(loggerTest, Level.OFF);
    }

    @Test
    public void setRootLevelToNull() {
        try {
            root.setLevel(null);
            fail("The level of the root logger should not be settable to null");
        } catch (IllegalArgumentException e) {
        }
    }

    @Test
    public void setLevelToNull_A() {
        loggerTest.setLevel(null);
        assertEquals(root.getEffectiveLevel(), loggerTest.getEffectiveLevel());
    }

    @Test
    public void setLevelToNull_B() {
        loggerTest.setLevel(Level.DEBUG);
        loggerTest.setLevel(null);
        assertEquals(root.getEffectiveLevel(), loggerTest.getEffectiveLevel());
    }

    @Test
    public void setLevelToNull_LBCLASSIC_91() {
        loggerTest.setLevel(Level.DEBUG);
        ch.qos.logback.classic.Logger child = lc.getLogger(loggerTest.getName() + ".child");
        loggerTest.setLevel(null);
        assertEquals(root.getEffectiveLevel(), loggerTest.getEffectiveLevel());
        assertEquals(root.getEffectiveLevel(), child.getEffectiveLevel());
    }

}


text:
<?php

namespace User\DbTable;

use Eva\Db\TableGateway\TableGateway;
use Zend\Stdlib\Parameters;

class Fields extends TableGateway
{
    protected $tableName ='fields';
    protected $primaryKey = 'id';

    public function setParameters(Parameters $params)
    {
        $this->enableCount();

        if($params->applyToAll !== null){
            $this->where(array(
                'applyToAll' => $params->applyToAll,
            ));
        }

        if($params->keyword){
            $keyword = $params->keyword;
            $this->where(function($where) use ($keyword){
                $where->like('userName', "%$keyword%");
                return $where;
            });
        }

        if ($params->rows) {
            $this->limit((int) $params->rows);
        }

        if($params->page){
            $this->page($params->page);
        }

        return $this;
    }
}


text:
namespace MassTransit.Transports
{
    using System;
    using Configuration;

    public class TransportBusInstance<TEndpointConfigurator> :
        IBusInstance,
        IReceiveEndpointConnector<TEndpointConfigurator>
        where TEndpointConfigurator : class, IReceiveEndpointConfigurator
    {
        readonly IHost<TEndpointConfigurator> _host;

        public TransportBusInstance(IBusControl busControl, IHost<TEndpointConfigurator> host, IHostConfiguration hostConfiguration, IBusRegistrationContext
            busRegistrationContext)
        {
            _host = host;
            RegistrationContext = busRegistrationContext;

            BusControl = busControl;
            HostConfiguration = hostConfiguration;
        }

        protected IBusRegistrationContext RegistrationContext { get; }

        public string Name => "masstransit-bus";
        public Type InstanceType => typeof(IBus);
        public IBus Bus => BusControl;
        public IBusControl BusControl { get; }

        public IHostConfiguration HostConfiguration { get; }

        public void Connect<TRider>(IRiderControl riderControl)
            where TRider : IRider
        {
            var name = GetRiderName<TRider>();
            _host.AddRider(name, riderControl);
        }

        public TRider GetRider<TRider>()
            where TRider : IRider
        {
            var name = GetRiderName<TRider>();
            return (TRider)_host.GetRider(name);
        }

        public HostReceiveEndpointHandle ConnectReceiveEndpoint(IEndpointDefinition definition, IEndpointNameFormatter endpointNameFormatter,
            Action<IBusRegistrationContext, IReceiveEndpointConfigurator> configure = null)
        {
            return _host.ConnectReceiveEndpoint(definition, endpointNameFormatter, configurator =>
            {
                configure?.Invoke(RegistrationContext, configurator);
            });
        }

        public HostReceiveEndpointHandle ConnectReceiveEndpoint(string queueName,
            Action<IBusRegistrationContext, IReceiveEndpointConfigurator> configure = null)
        {
            return _host.ConnectReceiveEndpoint(queueName, configurator =>
            {
                configure?.Invoke(RegistrationContext, configurator);
            });
        }

        public HostReceiveEndpointHandle ConnectReceiveEndpoint(IEndpointDefinition definition, IEndpointNameFormatter endpointNameFormatter,
            Action<IBusRegistrationContext, TEndpointConfigurator> configure = null)
        {
            return _host.ConnectReceiveEndpoint(definition, endpointNameFormatter, configurator =>
            {
                RegistrationContext.GetConfigureReceiveEndpoints().Configure(definition.GetEndpointName(endpointNameFormatter), configurator);

                configure?.Invoke(RegistrationContext, configurator);
            });
        }

        public HostReceiveEndpointHandle ConnectReceiveEndpoint(string queueName, Action<IBusRegistrationContext, TEndpointConfigurator> configure = null)
        {
            return _host.ConnectReceiveEndpoint(queueName, configurator =>
            {
                RegistrationContext.GetConfigureReceiveEndpoints().Configure(queueName, configurator);

                configure?.Invoke(RegistrationContext, configurator);
            });
        }

        static string GetRiderName<TRider>()
            where TRider : IRider
        {
            return TypeCache<TRider>.ShortName;
        }
    }
}


text:
.list {
  flex: auto 0 1;
  overflow-y: auto;
  border: 1px solid var(--color-details-hairline);
  flex-direction: column;

  --override-background-list-item-color: hsl(0deg 0% 96%);
}

.-theme-with-dark-background .list,
:host-context(.-theme-with-dark-background) .list {
  --override-background-list-item-color: hsl(0deg 0% 16%);
}

.list-separator {
  background: var(--color-background-elevation-1);
  height: 1px;
}

.list-item {
  flex: none;
  min-height: 30px;
  display: flex;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.list-item:focus-within,
.list-item:hover {
  background: var(--override-background-list-item-color);
}

.list-widget-input-validation-error {
  color: var(--legacy-input-validation-error);
  margin: 0 5px;
}

.controls-container {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: stretch;
  pointer-events: none;
}

.controls-gradient {
  flex: 0 1 50px;
}

.list-item:focus-within .controls-gradient,
.list-item:hover .controls-gradient {
  background-image: linear-gradient(90deg, transparent, var(--override-background-list-item-color));
}

.controls-buttons {
  flex: none;
  display: flex;
  flex-direction: row;
  align-items: center;
  pointer-events: auto;
  visibility: hidden;
}

.list-item:focus-within .controls-buttons,
.list-item:hover .controls-buttons {
  background-color: var(--override-background-list-item-color);
  visibility: visible;
}

.editor-container {
  display: flex;
  flex-direction: column;
  align-items: stretch;
  flex: none;
  background: var(--color-background-elevation-2);
  overflow: hidden;
}

.editor-content {
  flex: auto;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.editor-buttons {
  flex: none;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  padding: 5px;
}

.editor-buttons > button {
  flex: none;
  margin-right: 10px;
}

.editor-content input {
  margin-right: 10px;
}

.editor-content input.error-input {
  background-color: var(--color-background);
}

.text-prompt-container {
  padding: 3px 6px;
  height: 24px;
  border: none;
  box-shadow: var(--legacy-focus-ring-inactive-shadow);
  border-radius: 2px;
  width: 100%;
  background-color: var(--color-background);
}

.text-prompt-container:focus {
  box-shadow: var(--legacy-focus-ring-active-shadow);
}

.text-prompt-container .text-prompt {
  width: 100%;
}

@media (forced-colors: active) {
  .list-item:focus-within .controls-buttons,
  .list-item:hover .controls-buttons {
    background-color: canvas;
  }

  .list-item:focus-within,
  .list-item:hover {
    forced-color-adjust: none;
    background: Highlight;
  }

  .list-item:focus-within *,
  .list-item:hover * {
    color: HighlightText;
  }

  .list-item:focus-within .controls-gradient,
  .list-item:hover .controls-gradient {
    background-image: unset;
  }
}


text:
"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.notNull = void 0;
// ConvertTo-TS run at 2016-10-04T11:26:39.6568608-07:00
/**
 * Validates that an argument is not `null` or `undefined`.
 *
 * @param parameterName The name of the parameter
 * @param value The argument value
 *
 * @throws `TypeError` if `value` is `null` or `undefined`.
 */
function notNull(parameterName, value) {
    if (value == null) {
        throw new TypeError(parameterName + " cannot be null or undefined.");
    }
}
exports.notNull = notNull;
//# sourceMappingURL=Args.js.map


text:
#include "EscapeOStream.h"
#include "WebUtils.h"

namespace Wt {

const EscapeOStream::Entry EscapeOStream::htmlAttributeEntries_[] = {
  { '&', "&" },
  { '\"', """ },
  { '<', "<" }
};

const EscapeOStream::Entry EscapeOStream::plainTextEntries_[] = {
  { '&', "&" },
  { '>', ">" },
  { '<', "<" }
};

const EscapeOStream::Entry EscapeOStream::plainTextNewLinesEntries_[] = {
  { '&', "&" },
  { '>', ">" },
  { '<', "<" },
  { '\n', "<br />" }
};

const EscapeOStream::Entry EscapeOStream::jsStringLiteralSQuoteEntries_[] = {
  { '\\', "\\\\" },
  { '\n', "\\n" },
  { '\r', "\\r" },
  { '\t', "\\t" },
  { '\'', "\\'" },
};

const EscapeOStream::Entry EscapeOStream::jsStringLiteralDQuoteEntries_[] = {
  { '\\', "\\\\" },
  { '\n', "\\n" },
  { '\r', "\\r" },
  { '\t', "\\t" },
  { '"', "\\\"" },
};

const std::vector<EscapeOStream::Entry> EscapeOStream::standardSets_[] = {
  std::vector<EscapeOStream::Entry>(),
  std::vector<EscapeOStream::Entry>(htmlAttributeEntries_,
				    htmlAttributeEntries_ + 3),
  std::vector<EscapeOStream::Entry>(jsStringLiteralSQuoteEntries_,
				    jsStringLiteralSQuoteEntries_ + 5),
  std::vector<EscapeOStream::Entry>(jsStringLiteralDQuoteEntries_,
				    jsStringLiteralDQuoteEntries_ + 5),
  std::vector<EscapeOStream::Entry>(plainTextEntries_,
				    plainTextEntries_ + 3),
  std::vector<EscapeOStream::Entry>(plainTextNewLinesEntries_,
				    plainTextNewLinesEntries_ + 4)
};

const std::string EscapeOStream::standardSetsSpecial_[] = {
  std::string(),
  std::string("&\"<"),
  std::string("\\\n\r\t'"),
  std::string("\\\n\r\t\""),
  std::string("&><"),
  std::string("&><\n")
};

EscapeOStream::EscapeOStream()
  : stream_(own_stream_),
    c_special_(0)
{ }

EscapeOStream::EscapeOStream(std::ostream& sink)
  : own_stream_(sink),
    stream_(own_stream_),
    c_special_(0)
{ }

EscapeOStream::EscapeOStream(WStringStream& sink)
  : stream_(sink),
    c_special_(0)
{ }

EscapeOStream::EscapeOStream(EscapeOStream& other)
  : stream_(own_stream_),
    mixed_(other.mixed_),
    special_(other.special_),
    c_special_(special_.empty() ? 0 : special_.c_str()),
    ruleSets_(other.ruleSets_)
{ }

void EscapeOStream::mixRules()
{
  mixed_.clear();
  special_.clear();

  const int ruleSetsSize = ruleSets_.size();

  if (ruleSetsSize == 0) {
    c_special_ = 0;
  } else {
    if (ruleSetsSize == 1) {
      mixed_ = standardSets_[ruleSets_[0]];
      special_ = standardSetsSpecial_[ruleSets_[0]];
    } else
      for (int i = ruleSetsSize - 1; i >= 0; --i) {
	const std::vector<Entry>& toMix = standardSets_[ruleSets_[i]];

	for (unsigned j = 0; j < mixed_.size(); ++j)
	  for (unsigned k = 0; k < toMix.size(); ++k)
	    Utils::replace(mixed_[j].s, toMix[k].c, toMix[k].s);

	mixed_.insert(mixed_.end(), toMix.begin(), toMix.end());

	for (unsigned j = 0; j < toMix.size(); ++j)
	  special_.push_back(toMix[j].c);
      }

    if (!special_.empty())
      c_special_ = special_.c_str();
    else
      c_special_ = 0;
  }
}

void EscapeOStream::pushEscape(RuleSet rules)
{
  ruleSets_.push_back(rules);
  mixRules();
}

void EscapeOStream::popEscape()
{
  ruleSets_.pop_back();
  mixRules();
}

EscapeOStream& EscapeOStream::operator<< (char c)
{
  if (c_special_ == 0) {
    stream_ << c;
  } else {
    std::size_t i = special_.find(c);

    if (i != std::string::npos)
      stream_ << mixed_[i].s;
    else
      stream_ << c;
  }

  return *this;
}

void EscapeOStream::append(const char *s, std::size_t len)
{
  if (c_special_ == 0)
    stream_.append(s, len);
  else
    put(s, *this);
}

EscapeOStream& EscapeOStream::operator<< (char *s)
{
  if (c_special_ == 0)
    stream_ << s;
  else
    put(s, *this);

  return *this;
}

void EscapeOStream::append(const std::string& s, const EscapeOStream& rules)
{
  if (rules.c_special_ == 0)
    stream_ << s;
  else
    put(s.c_str(), rules);
}

EscapeOStream& EscapeOStream::operator<< (const std::string& s)
{
  append(s, *this);

  return *this;
}

EscapeOStream& EscapeOStream::operator<< (int i)
{
  stream_ << i;

  return *this;
}

EscapeOStream& EscapeOStream::operator<< (long long i)
{
  stream_ << i;

  return *this;
}

void EscapeOStream::put(const char *s, const EscapeOStream& rules)
{
  for (;s;) {
    const char *f = std::strpbrk(s, rules.c_special_);
    if (f != 0) {
      stream_.append(s, static_cast<int>(f - s));

      unsigned i = 0;
      for (; i < rules.mixed_.size(); ++i)
	if (rules.mixed_[i].c == *f) {
	  stream_ << rules.mixed_[i].s;
	  break;
	}

      if (i == rules.mixed_.size())
	stream_ << *f;

      s = f + 1;
    } else {
      stream_ << const_cast<char *>(s);
      s = 0;
    }
  }
}

EscapeOStream& EscapeOStream::operator<< (bool b)
{
  stream_ << b;

  return *this;
}

EscapeOStream& EscapeOStream::operator<< (const EscapeOStream& other)
{
  if (!other.empty())
    *this << other.str(); // FIXME could be optimized ?

  return *this;
}

const char *EscapeOStream::c_str()
{
  return stream_.c_str();
}

std::string EscapeOStream::str() const
{
  return stream_.str();
}

void EscapeOStream::clear()
{
  stream_.clear();
}

bool EscapeOStream::empty() const
{
  return stream_.empty();
}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:activiti="http://activiti.org/bpmn" targetNamespace="Examples">
  <process id="testProcess">

    <startEvent id="theStart" />
    <sequenceFlow id="flow1" sourceRef="theStart" targetRef="theService" />

    <serviceTask id="theService" activiti:async="true" activiti:expression="${true}"></serviceTask>

    <sequenceFlow id="flow2" sourceRef="theService" targetRef="theEnd" />
    <endEvent id="theEnd" />

  </process>
</definitions>


text:
<title>IM_META(3) manual page</title>

Table of Contents

Name

im_meta_set_int, im_meta_get_int, im_meta_set_double, im_meta_get_double,
im_meta_set_area, im_meta_get_area, im_meta_set_string, im_meta_get_string,
im_meta_set_blob, im_meta_get_blob, im_meta_set, im_meta_get - read and
write extra header fields

Synopsis

#include <vips/vips.h>

 int im_meta_set_int(
IMAGE *im, const char *field, int i );

int im_meta_get_int( IMAGE *im, const char *field, int *i );

int im_meta_set_double( IMAGE *im, const char *field, double d );

int im_meta_get_double( IMAGE *im, const char *field, double *d );

int im_meta_set_area( IMAGE *im, const char *field,    im_callback_fn free_fn,
void *data );

int im_meta_get_area( IMAGE *im, const char *field, void **data );

int im_meta_set_string( IMAGE *im, const char *field,    const char *str
);

int im_meta_get_string( IMAGE *im, const char *field, char **str );

int im_meta_set_blob( IMAGE *im, const char *field,    im_callback_fn free_fn,
void *blob, size_t blob_length );

int im_meta_get_blob( IMAGE *im, const char *field,    void **blob, size_t
*blob_length );

 typedef int (*im_callback_fn)( void *, void * );

 int im_meta_set( IMAGE
*im, const char *field, GValue *value );

int im_meta_get( IMAGE *im, const char *field, GValue *value_copy );

GType im_meta_get_type( IMAGE *im, const char *field );

 #define IM_TYPE_SAVE_STRING
(im_save_string_get_type())

GType im_save_string_get_type( void );

const char *im_save_string_get( const GValue *value );

void im_save_string_set( GValue *value, const char *str );

void im_save_string_setf( GValue *value, const char *fmt, ... );

Description

These
functions read and write extra image header fields. Writing to a field destroys
any old value. You must read a field with the correct type of reader: you
can’t read an int field as a string. Fields are copied when images are processed,
so you can use them to pass information to subsequent operations. Unless
otherwise noted, image header fields created with these functions are also
saved to disc when an image is saved in VIPS format, and automatically
restored when the image is loaded again.

 im_meta_set_int(3)
 sets an integer
field. Any existing field of any type with this name is  removed. It returns
0 for success, or -1 on error setting  im_error(3)
.

 im_meta_get_int(3)
 reads
an integer field. It returns 0 for success, or -1 on error, setting im_error(3)
.
 It can fail if the field does not exist, or if the field is not an int.

 im_meta_set_double(3)
 and im_meta_get_double(3)
 work exactly as  im_meta_set_int(3)

and im_meta_get_int(3)
.

 im_meta_set_area(3)
 sets a field which is an area
of memory. When the field is copied to a subsequent IMAGE, VIPS just copies
the pointer. VIPS keeps a reference count and when the last IMAGE using
this field is closed, VIPS will call  free_fn to release the memory. You
can therefore use this function to attach very large areas of memory to
images efficiently. Areas cannot be saved to VIPS files on disc, since there
is no known length.

 im_meta_set_string(3)
 is a convenience function over
 im_meta_set_area(3)
.  It copies the string, and then shares that copy between
all images derived from this IMAGE.

 im_meta_get_string(3)
 is a convenience
function over  im_meta_get_area(3)
.  It returns a pointer to the string
being mananged by VIPS. Do not free the return result!

 im_meta_set_blob(3)

sets a field which is a blob (binary object). A blob is just like string,
 except that rather than being NULL-terminated, you must pass an explicit
 length.

 im_meta_set(3)
, im_meta_get_type(3)
 and im_meta_get(3)
 operate
at a lower level: they let you set image header fields as GValue. Use one
of the convenience functions above if possible.  im_meta_get_type(3)
 returns
0 if the field is not defined.

 In order for the autoload/save to VIPS files
to work, you need to use a GType with a transform defined to and from
IM_TYPE_SAVE_STRING.

Return Value

The functions return 0 success and -1 on
error.

See Also

im_header_int(3)
, im_header_map(3)
.

Copyright

The National
Gallery, 2005.

Author

Markus Wollgarten and John Cupitt

Table of Contents

Name

Synopsis

Description

Return Value

See Also

Copyright

Author


text:
process_t * process_get(pid_t pid) __attribute__((warn_unused_result));
process_t * process_put(process_t * process);
process_t * process_dup(process_t * process);

void process_add(process_t * process);
void process_del(process_t * process);

thread_t * thread_get(pid_t pid) __attribute__((warn_unused_result));
thread_t * thread_put(thread_t * thread);
thread_t * thread_dup(thread_t * thread);

void thread_add(thread_t * thread);
void thread_del(thread_t * thread);

typedef void (process_callback_t)(process_t *);
#define process_lambda(process, ...) ({ void $(process_t * process) { __VA_ARGS__ } $; })

void process_iter(void (fn)(process_t *));
void thread_iter(process_t * process, void (fn)(thread_t *));

thread_t * thread_any_running(process_t * process) __attribute__((warn_unused_result));
thread_t * thread_any_stopped(process_t * process) __attribute__((warn_unused_result));

#endif


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>The GTK+ Drawing Model</title>
<meta name="generator" content="DocBook XSL Stylesheets V1.78.0">
<link rel="home" href="index.html" title="GTK+ 3 Reference Manual">
<link rel="up" href="gtk.html" title="Part I. GTK+ Overview">
<link rel="prev" href="gtk-question-index.html" title="Common Questions">
<link rel="next" href="gtkbase.html" title="Part II. GTK+ Core Reference">
<meta name="generator" content="GTK-Doc V1.18.1 (XML mode)">
<link rel="stylesheet" href="style.css" type="text/css">

GTK+ 3 Reference Manual

The GTK+ Drawing Model

The GTK+ Drawing Model —
    The GTK+ drawing model in detail

Overview of the drawing model

      This chapter describes the GTK+ drawing model in detail.  If you
      are interested in the procedure which GTK+ follows to draw its
      widgets and windows, you should read this chapter; this will be
      useful to know if you decide to implement your own widgets.  This
      chapter will also clarify the reasons behind the ways certain
      things are done in GTK+; for example, why you cannot change the
      background color of all widgets with the same method.

      Programs that run in a windowing system generally create
      rectangular regions in the screen called
      windows.  Traditional windowing systems
      do not automatically save the graphical content of windows, and
      instead ask client programs to repaint those windows whenever it
      is needed.  For example, if a window that is stacked below other
      windows gets raised to the top, then a client program has to
      repaint the area that was previously obscured.  When the
      windowing system asks a client program to redraw part of a
      window, it sends an exposure event to the
      program for that window.

      Here, "windows" means "rectangular regions with automatic
      clipping", instead of "toplevel application windows".  Most
      windowing systems support nested windows, where the contents of
      child windows get clipped by the boundaries of their parents.
      Although GTK+ and GDK in particular may run on a windowing
      system with no such notion of nested windows, GDK presents the
      illusion of being under such a system.  A toplevel window may
      contain many subwindows and sub-subwindows, for example, one for
      the menu bar, one for the document area, one for each scrollbar,
      and one for the status bar.  In addition, controls that receive
      user input, such as clickable buttons, are likely to have their
      own subwindows as well.

      Generally, the drawing cycle begins when GTK+ receives an
      exposure event from the underlying windowing system:  if the
      user drags a window over another one, the windowing system will
      tell the underlying window that it needs to repaint itself.  The
      drawing cycle can also be initiated when a widget itself decides
      that it needs to update its display.  For example, when the user
      types a character in a GtkEntry
      widget, the entry asks GTK+ to queue a redraw operation for
      itself.

      The following sections describe how GTK+ decides which widgets
      need to be repainted, and how widgets work internally in terms
      of the resources they use from the windowing system.

      A GdkWindow
      represents a window from the underlying windowing system on which GTK+
      is running.  For example, on X11 it corresponds to a
      Window; on Win32, it corresponds to a HANDLE.
      The windowing system generates events for these windows.  The GDK
      interface to the windowing system translates such native events into
      GdkEvent
      structures and sends them on to the GTK layer.  In turn, the GTK layer
      finds the widget that corresponds to a particular
      GdkWindow and emits the corresponding event
      signals on that widget.

Emission of the draw event

        When the program needs to redraw a region of a
        GdkWindow, generates an event of
        type GDK_EVENT_EXPOSE
        for that window, specifying the region to redraw in the process.

        When generating the event, GDK also sets up double buffering to
        avoid the flickering that would result from each widget drawing
        itself in turn.  the section called "Double buffering" describes
        the double buffering mechanism in detail.

        When the GTK+ widget layer receives the event, it finds the widget that
        corresponds to the window, and causes it to render itself using the
        widget's #GtkWidget::draw signal. For this purpose it creates a
        cairo context. It then clips the context
        to the area that needs to be drawn. This makes sure that the minimal
        amount of work is done if only a small part of the widget needs to be
        repainted. After translating the context so that its (0, 0) coordinate
        corresponds to the top left corner of the widget, it effectively calls
        the widget's gtk_widget_draw function.

        gtk_widget_draw takes care of drawing the widget
        to the cairo context. It first checks that the widget actually needs to
        be drawn. Widgets might for example be empty or outside of the cairo
        context's clipped area, which would make drawing them not do anything.
        Usually they will need to be drawn. In this case, the context will be
        clipped to the widget's allocated size and the
        draw signal will be emitted on
        the widget which will finally draw the widget.

Window and no-window widgets

	In principle, each widget could have a
	GdkWindow of its own.  With such a
	scheme, the drawing cycle would be trivial:  when GDK notifies
	the GTK layer about an exposure event for a
	GdkWindow, the GTK layer would simply
	emit the #GtkWidget::draw signal for that widget.  The signal
	handler would subsequently repaint the widget.  No further
	work would be necessary; the windowing system would generate
	exposure events for each window that needs it, and then each
	corresponding widget would draw itself in turn.

	However, in practice it is convenient to have widgets which do
	not have a GdkWindow of their own, but
	rather share the one from their parent widget.  Such widgets
	have called gtk_widget_set_has_window to
	disable it; this can be tested easily with the gtk_widget_get_has_window()
	function.  As such, these are called no-window
	widgets.

	No-window widgets are useful for various reasons:

	    Some widgets may want the parent's background to show through, even
	    when they draw on parts of it.  For example, consider a theme that
	    uses textured backgrounds, such as gradients or repeating
	    patterns.  If each widget had its own window, and in turn its own
	    gradient background, labels would look bad because there would be a
	    visible break with respect to their surroundings.  Figure 1, "Windowed label vs. no-window label" shows this undesirable effect.

Figure 1. Windowed label vs. no-window label

	    Reducing the number of windows creates less traffic between GTK+ and
	    the underlying windowing system, especially when getting events.

	On the other hand, widgets that would benefit from having a "hard"
	clipping region may find it more convenient to create their own
	windows.  Also, widgets which want to receive events resulting from
	user interaction may find it convenient to use windows of their own as
	well.  Widgets may have more than one window if they want to
	define different regions for capturing events.

Hierarchical drawing

	When the GTK layer receives an exposure event from GDK, it
	finds the widget that corresponds to the window which received
	the event.  By definition, this corresponds to a widget that
	has the GTK_NO_WINDOW flag turned
	off (otherwise, the widget wouldn't own
	the window!).  First this widget paints its background, and
	then, if it is a container widget, it tells each of its
	GTK_NO_WINDOW children to paint
	themselves.  This process is applied recursively for all the
	GTK_NO_WINDOW descendants of the original
	widget.

	Note that this process does not get propagated to widgets
	which have windows of their own, that is, to widgets which
	have the GTK_NO_WINDOW flag turned off.
	If such widgets require redrawing, then the windowing system
	will already have sent exposure events to their corresponding
	windows.  As such, there is no need to
	propagate the exposure to them on the
	GTK+ side.

	Figure 2, "Hierarchical drawing order" shows how a simple toplevel window would
	paint itself when it contains only GTK_NO_WINDOW descendants:

	      The outermost, thick rectangle is a toplevel GtkWindow,
	      which is not a GTK_NO_WINDOW widget —
	      as such, it does receive its exposure event as it comes from GDK.
	      First the GtkWindow would paint its own
	      background.  Then, it would ask its only child to paint itself,
	      numbered 2.

	      The dotted rectangle represents a GtkVBox, which
	      has been made the sole child of the
	      GtkWindow.  Boxes are just layout
	      containers that do not paint anything by themselves, so this
	      GtkVBox would draw nothing, but rather ask
	      its children to draw themselves.  The children are numbered 3 and
	      6.

	      The thin rectangle is a GtkFrame,
	      which has two children:  a label for the frame, numbered 4, and
	      another label inside, numbered 5.  First the frame would draw its
	      own beveled box, then ask the frame label and its internal child to
	      draw themselves.

	      The frame label has no children, so it just draws its text:  "Frame Label".

	      The internal label has no children, so it just draws its text:  "This
	      is some text inside the frame!".

	      The dotted rectangle represents a GtkHBox.  Again,
	      this does not draw anything by itself, but rather asks its children
	      to draw themselves.  The children are numbered 7 and 9.

	      The thin rectangle is a GtkButton with
	      a single child, numbered 8.  First the button would draw its
	      beveled box, and then it would ask its child to draw itself.

	      This is a text label which has no children, so it just draws its
	      own text:  "Cancel".

	      Similar to number 7, this is a button with a single child, numbered
	      10.  First the button would draw its beveled box, and then it would
	      ask its child to draw itself.

	      Similar to number 8, this is a text label which has no children,
	      so it just draws its own text:  "OK".

Figure 2. Hierarchical drawing order

Double buffering

      When the GTK layer receives an exposure event from GDK, it first finds
      the !GTK_NO_WINDOW widget that
      corresponds to the event's window.  Then, it emits the
      #GtkWidget::draw signal for that
      widget.  As described above, that widget will first draw its background,
      and then ask each of its GTK_NO_WINDOW children to
      draw themselves.

      If each of the drawing calls made by each subwidget's
      draw handler were sent directly to the
      windowing system, flicker could result.  This is because areas may get
      redrawn repeatedly:  the background, then decorative frames, then text
      labels, etc.  To avoid flicker, GTK+ employs a double
	buffering system at the GDK level.  Widgets normally don't
      know that they are drawing to an off-screen buffer; they just issue their
      normal drawing commands, and the buffer gets sent to the windowing system
      when all drawing operations are done.

      Two basic functions in GDK form the core of the double-buffering
      mechanism:  gdk_window_begin_paint_region()
      and gdk_window_end_paint().
      The first function tells a GdkWindow to
      create a temporary off-screen buffer for drawing.  All
      subsequent drawing operations to this window get automatically
      redirected to that buffer.  The second function actually paints
      the buffer onto the on-screen window, and frees the buffer.

Automatic double buffering

	It would be inconvenient for all widgets to call
	gdk_window_begin_paint_region() and
	gdk_window_end_paint() at the beginning
	and end of their draw handlers.

	To make this easier, most GTK+ widgets have the
	GTK_DOUBLE_BUFFERED widget flag turned on by
	default.  When GTK+ encounters such a widget, it automatically
	calls gdk_window_begin_paint_region()
	before emitting the #GtkWidget::draw signal for the widget, and
	then it calls gdk_window_end_paint()
	after the signal has been emitted.  This is convenient for
	most widgets, as they do not need to worry about creating
	their own temporary drawing buffers or about calling those
	functions.

	However, some widgets may prefer to disable this kind of
	automatic double buffering and do things on their own.  To do
        this, call the
        gtk_widget_set_double_buffered() function
	in your widget's constructor.

Example 5. Disabling automatic double buffering

1
2
3
4
5
6
7
8
9

static void
my_widget_init (MyWidget *widget)
{
  ...

  gtk_widget_set_double_buffered (widget, FALSE);

  ...
}

	When is it convenient to disable double buffering?  Generally,
	this is the case only if your widget gets drawn in such a way
	that the different drawing operations do not overlap each
	other.  For example, this may be the case for a simple image
	viewer:  it can just draw the image in a single operation.
	This would not be the case with a word
	processor, since it will need to draw and over-draw the page's
	background, then the background for highlighted text, and then
	the text itself.

	Even if you turn off double buffering on a widget, you
	can still call
	gdk_window_begin_paint_region() and
	gdk_window_end_paint() by hand to use
	temporary drawing buffers.

App-paintable widgets

      Generally, applications use the pre-defined widgets in GTK+ and
      they do not draw extra things on top of them (the exception
      being GtkDrawingArea).  However,
      applications may sometimes find it convenient to draw directly
      on certain widgets like toplevel windows or event boxes.  When
      this is the case, GTK+ needs to be told not to overwrite your
      drawing afterwards, when the window gets to drawing its default
      contents.

      GtkWindow and
      GtkEventBox are the two widgets that allow
      turning off drawing of default contents by calling
      gtk_widget_set_app_paintable(). If you call
      this function, they will not draw their contents and let you do
      it instead.

      Since the #GtkWidget::draw signal runs user-connected handlers
      before the widget's default handler, what
      usually happens is this:

	  Your own draw handler gets run.  It paints something
	  on the window or the event box.

	  The widget's default draw handler gets run.  If
          gtk_widget_set_app_paintable() has not
          been called to turn off widget drawing (this
	  is the default), your drawing will be
            overwritten.  An app paintable widget will not
          draw its default contents however and preserve your drawing
          instead.

	  The draw handler for the parent class gets run.
	  Since both GtkWindow and
	  GtkEventBox are descendants of
	  GtkContainer, their no-window
	  children will be asked to draw themselves recursively, as
	  described in the section called "Hierarchical drawing".

Summary of app-paintable widgets.
        Call gtk_widget_set_app_paintable() if you
	intend to draw your own content directly on a
	GtkWindow and
	GtkEventBox.  You seldom need to draw
	on top of other widgets, and
	GtkDrawingArea ignores this flag, as it
	is intended to be drawn on.

          Generated by GTK-Doc V1.18.1


text:
package sun.java2d.loops;

import sun.java2d.loops.GraphicsPrimitive;
import sun.java2d.SunGraphics2D;
import sun.java2d.SurfaceData;
import java.awt.geom.Path2D;

/**
 *   DrawPath
 *   1. draw single-width line path onto destination surface
 *   2. must accept output area [x, y, dx, dy]
 *      from within the surface description data for clip rect
 */
public class DrawPath extends GraphicsPrimitive {

    public final static String methodSignature =
        "DrawPath(...)".toString();

    public final static int primTypeID = makePrimTypeID();

    public static DrawPath locate(SurfaceType srctype,
                                  CompositeType comptype,
                                  SurfaceType dsttype)
    {
        return (DrawPath)
            GraphicsPrimitiveMgr.locate(primTypeID,
                                        srctype, comptype, dsttype);
    }

    protected DrawPath(SurfaceType srctype,
                       CompositeType comptype,
                       SurfaceType dsttype)
    {
        super(methodSignature, primTypeID,
              srctype, comptype, dsttype);
    }

    public DrawPath(long pNativePrim,
                    SurfaceType srctype,
                    CompositeType comptype,
                    SurfaceType dsttype)
    {
        super(pNativePrim, methodSignature, primTypeID,
              srctype, comptype, dsttype);
    }

    /**
     *   All DrawPath implementors must have this invoker method
     */
    public native void DrawPath(SunGraphics2D sg2d, SurfaceData sData,
                                int transX, int transY,
                                Path2D.Float p2df);

    public GraphicsPrimitive makePrimitive(SurfaceType srctype,
                                           CompositeType comptype,
                                           SurfaceType dsttype)
    {
        throw new InternalError("DrawPath not implemented for "+
                                srctype+" with "+comptype);
    }

    public GraphicsPrimitive traceWrap() {
        return new TraceDrawPath(this);
    }

    private static class TraceDrawPath extends DrawPath {
        DrawPath target;

        public TraceDrawPath(DrawPath target) {
            super(target.getSourceType(),
                  target.getCompositeType(),
                  target.getDestType());
            this.target = target;
        }

        public GraphicsPrimitive traceWrap() {
            return this;
        }

        public void DrawPath(SunGraphics2D sg2d, SurfaceData sData,
                             int transX, int transY,
                             Path2D.Float p2df)
        {
            tracePrimitive(target);
            target.DrawPath(sg2d, sData, transX, transY, p2df);
        }
    }
}


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Complex Layout - jQuery EasyUI Demo</title>
	<link rel="stylesheet" type="text/css" href="../themes/default/easyui.css">
	<link rel="stylesheet" type="text/css" href="../themes/icon.css">

The north content.

sub center

sub center

content1

content1

content1

content1

content1

content1

content1

content12

				content2

				content3

jQuery EasyUI framework help you build your web page easily.

easyui is a collection of user-interface plugin based on jQuery.

using easyui you don't write many javascript code, instead you defines user-interface by writing some HTML markup.

easyui is very easy but powerful.

This is Tab2 width close button.


text:
package net.devh.boot.grpc.test.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import net.devh.boot.grpc.test.server.TestServiceImpl;

@Configuration
public class ServiceConfiguration {

    @Bean
    TestServiceImpl testService() {
        return new TestServiceImpl();
    }

}


text:
<?xml version="1.0"?>

<!--
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
-->
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">

    <description>MyProject web.xml</description>

    <!--optional: context-param>
        <description>Comma separated list of URIs of (additional) faces config files.
            (e.g. /WEB-INF/my-config.xml)
            See JSF 1.0 PRD2, 10.3.2
            Attention: You do not need to put /WEB-INF/faces-config.xml in here.
        </description>
        <param-name>javax.faces.CONFIG_FILES</param-name>
        <param-value>/WEB-INF/examples-config.xml</param-value>
    </context-param-->
    <context-param>
        <description>State saving method: "client" or "server" (= default)
            See JSF Specification 2.5.3</description>
        <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
        <param-value>client</param-value>
    </context-param>
    <context-param>
        <description>Only applicable if state saving method is "server" (= default).
            Defines the amount (default = 20) of the latest views are stored in session.</description>
        <param-name>org.apache.myfaces.NUMBER_OF_VIEWS_IN_SESSION</param-name>
        <param-value>20</param-value>
    </context-param>
    <context-param>
        <description>Only applicable if state saving method is "server" (= default).
            If true (default) the state will be serialized to a byte stream before it
            is written to the session.
            If false the state will not be serialized to a byte stream.</description>
        <param-name>org.apache.myfaces.SERIALIZE_STATE_IN_SESSION</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>Only applicable if state saving method is "server" (= default) and if
            org.apache.myfaces.SERIALIZE_STATE_IN_SESSION is true (= default)
            If true (default) the serialized state will be compressed before it
            is written to the session. If false the state will not be compressed.</description>
        <param-name>org.apache.myfaces.COMPRESS_STATE_IN_SESSION</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>This parameter tells MyFaces if javascript code should be allowed in the
            rendered HTML output.
            If javascript is allowed, command_link anchors will have javascript code
            that submits the corresponding form.
            If javascript is not allowed, the state saving info and nested parameters
            will be added as url parameters.
            Default: "true"</description>
        <param-name>org.apache.myfaces.ALLOW_JAVASCRIPT</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <param-name>org.apache.myfaces.DETECT_JAVASCRIPT</param-name>
        <param-value>false</param-value>
    </context-param>
    <context-param>
        <description>If true, rendered HTML code will be formatted, so that it is "human readable".
            i.e. additional line separators and whitespace will be written, that do not
            influence the HTML code.
            Default: "true"</description>
        <param-name>org.apache.myfaces.PRETTY_HTML</param-name>
        <param-value>true</param-value>
    </context-param>
    <context-param>
        <description>If true, a javascript function will be rendered that is able to restore the
            former vertical scroll on every request. Convenient feature if you have pages
            with long lists and you do not want the browser page to always jump to the top
            if you trigger a link or button action that stays on the same page.
            Default: "false"</description>
        <param-name>org.apache.myfaces.AUTO_SCROLL</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <description>Used for encrypting view state. Only relevant for client side
            state saving. See MyFaces wiki/web site documentation for instructions
            on how to configure an application for diffenent encryption strengths.
        </description>
        <param-name>org.apache.myfaces.SECRET</param-name>
        <param-value>NzY1NDMyMTA=</param-value>
    </context-param>

    <context-param>
        <description>
            Validate managed beans, navigation rules and ensure that forms are not nested.
        </description>
        <param-name>org.apache.myfaces.VALIDATE</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <description>
            Treat readonly same as if disabled attribute was set for select elements.
        </description>
        <param-name>org.apache.myfaces.READONLY_AS_DISABLED_FOR_SELECTS</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <description>
            Use the defined class as the class which will be called when a resource is added to the
            ExtensionFilter handling. Using StreamingAddResource here helps with performance. If you want to add
            custom components and want to use the ExtensionFilter, you need to provide your custom implementation here.
        </description>
        <param-name>org.apache.myfaces.ADD_RESOURCE_CLASS</param-name>
        <param-value>org.apache.myfaces.renderkit.html.util.DefaultAddResource</param-value>
    </context-param>

    <context-param>
        <description>
            Virtual path in the URL which triggers loading of resources for the MyFaces extended components
            in the ExtensionFilter.
        </description>
        <param-name>org.apache.myfaces.RESOURCE_VIRTUAL_PATH</param-name>
        <param-value>/faces/myFacesExtensionResource</param-value>
    </context-param>

    <context-param>
        <description>
            Check if the extensions-filter has been properly configured.
        </description>
        <param-name>org.apache.myfaces.CHECK_EXTENSIONS_FILTER</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <description>
            Define partial state saving as true/false.
        </description>
        <param-name>javax.faces.PARTIAL_STATE_SAVING_METHOD</param-name>
        <param-value>false</param-value>
    </context-param>

    <!-- Extensions Filter -->
    <filter>
        <filter-name>extensionsFilter</filter-name>
        <filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
        <init-param>
            <description>Set the size limit for uploaded files.
                Format: 10 - 10 bytes
                10k - 10 KB
                10m - 10 MB
                1g - 1 GB</description>
            <param-name>uploadMaxFileSize</param-name>
            <param-value>100m</param-value>
        </init-param>
        <init-param>
            <description>Set the threshold size - files
                below this limit are stored in memory, files above
                this limit are stored on disk.

                Format: 10 - 10 bytes
                10k - 10 KB
                10m - 10 MB
                1g - 1 GB</description>
            <param-name>uploadThresholdSize</param-name>
            <param-value>100k</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>extensionsFilter</filter-name>
        <url-pattern>*.jsf</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>extensionsFilter</filter-name>
        <url-pattern>/faces/*</url-pattern>
    </filter-mapping>

    <!-- Listener, to allow Jetty serving MyFaces apps -->
    <listener>
        <listener-class>org.apache.myfaces.webapp.StartupServletContextListener</listener-class>
    </listener>

    <!-- Faces Servlet -->
    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Faces Servlet Mapping -->
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>

    <!-- Welcome files -->
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

</web-app>


text:
package net.jpountz.lz4;

/*
 * 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.
 */
/**
 * LZ4 decompressor that requires the size of the compressed data to be known.
 *

 * Implementations of this class are usually a little slower than those of
 * {@link LZ4Decompressor} but do not require the size of the original data to
 * be known.
 */
public abstract class LZ4UnknownSizeDecompressor
{

    /**
     * Uncompress src[srcOff:srcLen] into
     * dest[destOff:destOff+maxDestLen] and returns the number of
     * decompressed bytes written into dest.
     *
     * @param srcLen the exact size of the compressed stream
     *
     * @return the original input size
     *
     * @throws LZ4Exception if maxDestLen is too small
     */
    public abstract int decompress (byte[] src, int srcOff, int srcLen, byte[] dest, int destOff, int maxDestLen);

    /**
     * Convenience method. Equivalent to calling
     * {@link #decompress(byte[], int, int, byte[], int, int)} with
     * maxDestLen = dest.length - destOff.
     */
    public final int decompress (byte[] src, int srcOff, int srcLen, byte[] dest, int destOff) {
        return decompress (src, srcOff, srcLen, dest, destOff, dest.length - destOff);
    }

    @Override
    public String toString () {
        return getClass ().getSimpleName ();
    }

}


text:
require "google/cloud/org_policy/v2"

##
# Example demonstrating basic usage of
# Google::Cloud::OrgPolicy::V2::OrgPolicy::Client#create_policy
#
def create_policy
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::OrgPolicy::V2::OrgPolicy::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::OrgPolicy::V2::CreatePolicyRequest.new

  # Call the create_policy method.
  result = client.create_policy request

  # The returned object is of type Google::Cloud::OrgPolicy::V2::Policy.
  p result
end
# [END orgpolicy_v2_generated_OrgPolicy_CreatePolicy_sync]


text:
package cz.auderis.tools.model.change;

import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.Set;

/**
 * A set that is always empty, despite not being immutable.
 * @param <E>  the type parameter
 *
 * @author Boleslav Bobcik <bbobcik@gmail.com>
 * @version 1.0
 */
class BlackHoleSet<E> implements Set<E> {

	protected static final Object[] EMPTY_ARRAY = new Object[0];

	@Override
	public int size() {
		return 0;
	}

	@Override
	public boolean isEmpty() {
		return true;
	}

	@Override
	public boolean contains(Object o) {
		return false;
	}

	@Override
	public Iterator<E> iterator() {
		return Collections.emptyIterator();
	}

	@Override
	public Object[] toArray() {
		return EMPTY_ARRAY;
	}

	@Override
	@SuppressWarnings("unchecked")
	public <T> T[] toArray(T[] a) {
		return (T[]) EMPTY_ARRAY;
	}

	@Override
	public boolean add(E e) {
		return false;
	}

	@Override
	public boolean remove(Object o) {
		return false;
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		return false;
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		return false;
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		return false;
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		return false;
	}

	@Override
	public void clear() {
		// No action needed
	}

	@Override
	public int hashCode() {
		return 0;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		} else if ((null == obj) || !(obj instanceof Set)) {
			return false;
		}
		final Set<?> other = (Set<?>) obj;
		return other.isEmpty();
	}

	@Override
	public String toString() {
		return "EmptySet{}";
	}

}


text:
"""Restricted execution facilities.

The class RExec exports methods r_exec(), r_eval(), r_execfile(), and
r_import(), which correspond roughly to the built-in operations
exec, eval(), execfile() and import, but executing the code in an
environment that only exposes those built-in operations that are
deemed safe.  To this end, a modest collection of 'fake' modules is
created which mimics the standard modules by the same names.  It is a
policy decision which built-in modules and operations are made
available; this module provides a reasonable default, but derived
classes can change the policies e.g. by overriding or extending class
variables like ok_builtin_modules or methods like make_sys().

XXX To do:
- r_open should allow writing tmp dir
- r_exec etc. with explicit globals/locals? (Use rexec("exec ... in ...")?)

"""

import sys
import __builtin__
import os
import ihooks
import imp

__all__ = ["RExec"]

class FileBase:

    ok_file_methods = ('fileno', 'flush', 'isatty', 'read', 'readline',
            'readlines', 'seek', 'tell', 'write', 'writelines', 'xreadlines',
            '__iter__')

class FileWrapper(FileBase):

    # XXX This is just like a Bastion -- should use that!

    def __init__(self, f):
        for m in self.ok_file_methods:
            if not hasattr(self, m) and hasattr(f, m):
                setattr(self, m, getattr(f, m))

    def close(self):
        self.flush()

TEMPLATE = """
def %s(self, *args):
        return getattr(self.mod, self.name).%s(*args)
"""

class FileDelegate(FileBase):

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

    for m in FileBase.ok_file_methods + ('close',):
        exec TEMPLATE % (m, m)

class RHooks(ihooks.Hooks):

    def __init__(self, *args):
        # Hacks to support both old and new interfaces:
        # old interface was RHooks(rexec[, verbose])
        # new interface is RHooks([verbose])
        verbose = 0
        rexec = None
        if args and type(args[-1]) == type(0):
            verbose = args[-1]
            args = args[:-1]
        if args and hasattr(args[0], '__class__'):
            rexec = args[0]
            args = args[1:]
        if args:
            raise TypeError, "too many arguments"
        ihooks.Hooks.__init__(self, verbose)
        self.rexec = rexec

    def set_rexec(self, rexec):
        # Called by RExec instance to complete initialization
        self.rexec = rexec

    def get_suffixes(self):
        return self.rexec.get_suffixes()

    def is_builtin(self, name):
        return self.rexec.is_builtin(name)

    def init_builtin(self, name):
        m = __import__(name)
        return self.rexec.copy_except(m, ())

    def init_frozen(self, name): raise SystemError, "don't use this"
    def load_source(self, *args): raise SystemError, "don't use this"
    def load_compiled(self, *args): raise SystemError, "don't use this"
    def load_package(self, *args): raise SystemError, "don't use this"

    def load_dynamic(self, name, filename, file):
        return self.rexec.load_dynamic(name, filename, file)

    def add_module(self, name):
        return self.rexec.add_module(name)

    def modules_dict(self):
        return self.rexec.modules

    def default_path(self):
        return self.rexec.modules['sys'].path

# XXX Backwards compatibility
RModuleLoader = ihooks.FancyModuleLoader
RModuleImporter = ihooks.ModuleImporter

class RExec(ihooks._Verbose):
    """Basic restricted execution framework.

    Code executed in this restricted environment will only have access to
    modules and functions that are deemed safe; you can subclass RExec to
    add or remove capabilities as desired.

    The RExec class can prevent code from performing unsafe operations like
    reading or writing disk files, or using TCP/IP sockets.  However, it does
    not protect against code using extremely large amounts of memory or
    processor time.

    """

    ok_path = tuple(sys.path)           # That's a policy decision

    ok_builtin_modules = ('audioop', 'array', 'binascii',
                          'cmath', 'errno', 'imageop',
                          'marshal', 'math', 'md5', 'operator',
                          'parser', 'regex', 'pcre', 'rotor', 'select',
                          'sha', '_sre', 'strop', 'struct', 'time',
                          'xreadlines', '_weakref')

    ok_posix_names = ('error', 'fstat', 'listdir', 'lstat', 'readlink',
                      'stat', 'times', 'uname', 'getpid', 'getppid',
                      'getcwd', 'getuid', 'getgid', 'geteuid', 'getegid')

    ok_sys_names = ('byteorder', 'copyright', 'exit', 'getdefaultencoding',
                    'getrefcount', 'hexversion', 'maxint', 'maxunicode',
                    'platform', 'ps1', 'ps2', 'version', 'version_info')

    nok_builtin_names = ('open', 'file', 'reload', '__import__')

    ok_file_types = (imp.C_EXTENSION, imp.PY_SOURCE)

    def __init__(self, hooks = None, verbose = 0):
        """Returns an instance of the RExec class.

        The hooks parameter is an instance of the RHooks class or a subclass
        of it.  If it is omitted or None, the default RHooks class is
        instantiated.

        Whenever the RExec module searches for a module (even a built-in one)
        or reads a module's code, it doesn't actually go out to the file
        system itself.  Rather, it calls methods of an RHooks instance that
        was passed to or created by its constructor.  (Actually, the RExec
        object doesn't make these calls --- they are made by a module loader
        object that's part of the RExec object.  This allows another level of
        flexibility, which can be useful when changing the mechanics of
        import within the restricted environment.)

        By providing an alternate RHooks object, we can control the file
        system accesses made to import a module, without changing the
        actual algorithm that controls the order in which those accesses are
        made.  For instance, we could substitute an RHooks object that
        passes all filesystem requests to a file server elsewhere, via some
        RPC mechanism such as ILU.  Grail's applet loader uses this to support
        importing applets from a URL for a directory.

        If the verbose parameter is true, additional debugging output may be
        sent to standard output.

        """

        raise RuntimeError, "This code is not secure in Python 2.2 and 2.3"

        ihooks._Verbose.__init__(self, verbose)
        # XXX There's a circular reference here:
        self.hooks = hooks or RHooks(verbose)
        self.hooks.set_rexec(self)
        self.modules = {}
        self.ok_dynamic_modules = self.ok_builtin_modules
        list = []
        for mname in self.ok_builtin_modules:
            if mname in sys.builtin_module_names:
                list.append(mname)
        self.ok_builtin_modules = tuple(list)
        self.set_trusted_path()
        self.make_builtin()
        self.make_initial_modules()
        # make_sys must be last because it adds the already created
        # modules to its builtin_module_names
        self.make_sys()
        self.loader = RModuleLoader(self.hooks, verbose)
        self.importer = RModuleImporter(self.loader, verbose)

    def set_trusted_path(self):
        # Set the path from which dynamic modules may be loaded.
        # Those dynamic modules must also occur in ok_builtin_modules
        self.trusted_path = filter(os.path.isabs, sys.path)

    def load_dynamic(self, name, filename, file):
        if name not in self.ok_dynamic_modules:
            raise ImportError, "untrusted dynamic module: %s" % name
        if name in sys.modules:
            src = sys.modules[name]
        else:
            src = imp.load_dynamic(name, filename, file)
        dst = self.copy_except(src, [])
        return dst

    def make_initial_modules(self):
        self.make_main()
        self.make_osname()

    # Helpers for RHooks

    def get_suffixes(self):
        return [item   # (suff, mode, type)
                for item in imp.get_suffixes()
                if item[2] in self.ok_file_types]

    def is_builtin(self, mname):
        return mname in self.ok_builtin_modules

    # The make_* methods create specific built-in modules

    def make_builtin(self):
        m = self.copy_except(__builtin__, self.nok_builtin_names)
        m.__import__ = self.r_import
        m.reload = self.r_reload
        m.open = m.file = self.r_open

    def make_main(self):
        m = self.add_module('__main__')

    def make_osname(self):
        osname = os.name
        src = __import__(osname)
        dst = self.copy_only(src, self.ok_posix_names)
        dst.environ = e = {}
        for key, value in os.environ.items():
            e[key] = value

    def make_sys(self):
        m = self.copy_only(sys, self.ok_sys_names)
        m.modules = self.modules
        m.argv = ['RESTRICTED']
        m.path = map(None, self.ok_path)
        m.exc_info = self.r_exc_info
        m = self.modules['sys']
        l = self.modules.keys() + list(self.ok_builtin_modules)
        l.sort()
        m.builtin_module_names = tuple(l)

    # The copy_* methods copy existing modules with some changes

    def copy_except(self, src, exceptions):
        dst = self.copy_none(src)
        for name in dir(src):
            setattr(dst, name, getattr(src, name))
        for name in exceptions:
            try:
                delattr(dst, name)
            except AttributeError:
                pass
        return dst

    def copy_only(self, src, names):
        dst = self.copy_none(src)
        for name in names:
            try:
                value = getattr(src, name)
            except AttributeError:
                continue
            setattr(dst, name, value)
        return dst

    def copy_none(self, src):
        m = self.add_module(src.__name__)
        m.__doc__ = src.__doc__
        return m

    # Add a module -- return an existing module or create one

    def add_module(self, mname):
        m = self.modules.get(mname)
        if m is None:
            self.modules[mname] = m = self.hooks.new_module(mname)
        m.__builtins__ = self.modules['__builtin__']
        return m

    # The r* methods are public interfaces

    def r_exec(self, code):
        """Execute code within a restricted environment.

        The code parameter must either be a string containing one or more
        lines of Python code, or a compiled code object, which will be
        executed in the restricted environment's __main__ module.

        """
        m = self.add_module('__main__')
        exec code in m.__dict__

    def r_eval(self, code):
        """Evaluate code within a restricted environment.

        The code parameter must either be a string containing a Python
        expression, or a compiled code object, which will be evaluated in
        the restricted environment's __main__ module.  The value of the
        expression or code object will be returned.

        """
        m = self.add_module('__main__')
        return eval(code, m.__dict__)

    def r_execfile(self, file):
        """Execute the Python code in the file in the restricted
        environment's __main__ module.

        """
        m = self.add_module('__main__')
        execfile(file, m.__dict__)

    def r_import(self, mname, globals={}, locals={}, fromlist=[]):
        """Import a module, raising an ImportError exception if the module
        is considered unsafe.

        This method is implicitly called by code executing in the
        restricted environment.  Overriding this method in a subclass is
        used to change the policies enforced by a restricted environment.

        """
        return self.importer.import_module(mname, globals, locals, fromlist)

    def r_reload(self, m):
        """Reload the module object, re-parsing and re-initializing it.

        This method is implicitly called by code executing in the
        restricted environment.  Overriding this method in a subclass is
        used to change the policies enforced by a restricted environment.

        """
        return self.importer.reload(m)

    def r_unload(self, m):
        """Unload the module.

        Removes it from the restricted environment's sys.modules dictionary.

        This method is implicitly called by code executing in the
        restricted environment.  Overriding this method in a subclass is
        used to change the policies enforced by a restricted environment.

        """
        return self.importer.unload(m)

    # The s_* methods are similar but also swap std{in,out,err}

    def make_delegate_files(self):
        s = self.modules['sys']
        self.delegate_stdin = FileDelegate(s, 'stdin')
        self.delegate_stdout = FileDelegate(s, 'stdout')
        self.delegate_stderr = FileDelegate(s, 'stderr')
        self.restricted_stdin = FileWrapper(sys.stdin)
        self.restricted_stdout = FileWrapper(sys.stdout)
        self.restricted_stderr = FileWrapper(sys.stderr)

    def set_files(self):
        if not hasattr(self, 'save_stdin'):
            self.save_files()
        if not hasattr(self, 'delegate_stdin'):
            self.make_delegate_files()
        s = self.modules['sys']
        s.stdin = self.restricted_stdin
        s.stdout = self.restricted_stdout
        s.stderr = self.restricted_stderr
        sys.stdin = self.delegate_stdin
        sys.stdout = self.delegate_stdout
        sys.stderr = self.delegate_stderr

    def reset_files(self):
        self.restore_files()
        s = self.modules['sys']
        self.restricted_stdin = s.stdin
        self.restricted_stdout = s.stdout
        self.restricted_stderr = s.stderr

    def save_files(self):
        self.save_stdin = sys.stdin
        self.save_stdout = sys.stdout
        self.save_stderr = sys.stderr

    def restore_files(self):
        sys.stdin = self.save_stdin
        sys.stdout = self.save_stdout
        sys.stderr = self.save_stderr

    def s_apply(self, func, args=(), kw={}):
        self.save_files()
        try:
            self.set_files()
            r = func(*args, **kw)
        finally:
            self.restore_files()
        return r

    def s_exec(self, *args):
        """Execute code within a restricted environment.

        Similar to the r_exec() method, but the code will be granted access
        to restricted versions of the standard I/O streams sys.stdin,
        sys.stderr, and sys.stdout.

        The code parameter must either be a string containing one or more
        lines of Python code, or a compiled code object, which will be
        executed in the restricted environment's __main__ module.

        """
        return self.s_apply(self.r_exec, args)

    def s_eval(self, *args):
        """Evaluate code within a restricted environment.

        Similar to the r_eval() method, but the code will be granted access
        to restricted versions of the standard I/O streams sys.stdin,
        sys.stderr, and sys.stdout.

        The code parameter must either be a string containing a Python
        expression, or a compiled code object, which will be evaluated in
        the restricted environment's __main__ module.  The value of the
        expression or code object will be returned.

        """
        return self.s_apply(self.r_eval, args)

    def s_execfile(self, *args):
        """Execute the Python code in the file in the restricted
        environment's __main__ module.

        Similar to the r_execfile() method, but the code will be granted
        access to restricted versions of the standard I/O streams sys.stdin,
        sys.stderr, and sys.stdout.

        """
        return self.s_apply(self.r_execfile, args)

    def s_import(self, *args):
        """Import a module, raising an ImportError exception if the module
        is considered unsafe.

        This method is implicitly called by code executing in the
        restricted environment.  Overriding this method in a subclass is
        used to change the policies enforced by a restricted environment.

        Similar to the r_import() method, but has access to restricted
        versions of the standard I/O streams sys.stdin, sys.stderr, and
        sys.stdout.

        """
        return self.s_apply(self.r_import, args)

    def s_reload(self, *args):
        """Reload the module object, re-parsing and re-initializing it.

        This method is implicitly called by code executing in the
        restricted environment.  Overriding this method in a subclass is
        used to change the policies enforced by a restricted environment.

        Similar to the r_reload() method, but has access to restricted
        versions of the standard I/O streams sys.stdin, sys.stderr, and
        sys.stdout.

        """
        return self.s_apply(self.r_reload, args)

    def s_unload(self, *args):
        """Unload the module.

        Removes it from the restricted environment's sys.modules dictionary.

        This method is implicitly called by code executing in the
        restricted environment.  Overriding this method in a subclass is
        used to change the policies enforced by a restricted environment.

        Similar to the r_unload() method, but has access to restricted
        versions of the standard I/O streams sys.stdin, sys.stderr, and
        sys.stdout.

        """
        return self.s_apply(self.r_unload, args)

    # Restricted open(...)

    def r_open(self, file, mode='r', buf=-1):
        """Method called when open() is called in the restricted environment.

        The arguments are identical to those of the open() function, and a
        file object (or a class instance compatible with file objects)
        should be returned.  RExec's default behaviour is allow opening
        any file for reading, but forbidding any attempt to write a file.

        This method is implicitly called by code executing in the
        restricted environment.  Overriding this method in a subclass is
        used to change the policies enforced by a restricted environment.

        """
        mode = str(mode)
        if mode not in ('r', 'rb'):
            raise IOError, "can't open files for writing in restricted mode"
        return open(file, mode, buf)

    # Restricted version of sys.exc_info()

    def r_exc_info(self):
        ty, va, tr = sys.exc_info()
        tr = None
        return ty, va, tr

def test():
    import getopt, traceback
    opts, args = getopt.getopt(sys.argv[1:], 'vt:')
    verbose = 0
    trusted = []
    for o, a in opts:
        if o == '-v':
            verbose = verbose+1
        if o == '-t':
            trusted.append(a)
    r = RExec(verbose=verbose)
    if trusted:
        r.ok_builtin_modules = r.ok_builtin_modules + tuple(trusted)
    if args:
        r.modules['sys'].argv = args
        r.modules['sys'].path.insert(0, os.path.dirname(args[0]))
    else:
        r.modules['sys'].path.insert(0, "")
    fp = sys.stdin
    if args and args[0] != '-':
        try:
            fp = open(args[0])
        except IOError, msg:
            print "%s: can't open file %s" % (sys.argv[0], `args[0]`)
            return 1
    if fp.isatty():
        try:
            import readline
        except ImportError:
            pass
        import code
        class RestrictedConsole(code.InteractiveConsole):
            def runcode(self, co):
                self.locals['__builtins__'] = r.modules['__builtin__']
                r.s_apply(code.InteractiveConsole.runcode, (self, co))
        try:
            RestrictedConsole(r.modules['__main__'].__dict__).interact()
        except SystemExit, n:
            return n
    else:
        text = fp.read()
        fp.close()
        c = compile(text, fp.name, 'exec')
        try:
            r.s_exec(c)
        except SystemExit, n:
            return n
        except:
            traceback.print_exc()
            return 1

if __name__ == '__main__':
    sys.exit(test())


text:
> NodeJS wrapper for MyAnimeList API

[![npm version](https://badge.fury.io/js/popura.svg)](https://badge.fury.io/js/popura)
[![Travis CI Build Status](https://travis-ci.org/lubien/popura.svg?branch=master)](https://travis-ci.org/lubien/popura)
[![Coverage Status](https://coveralls.io/repos/github/lubien/popura/badge.svg?branch=master)](https://coveralls.io/github/lubien/popura?branch=master)
[![XO code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)

    Image by yotsu

[Popura](http://myanimelist.net/character/24417/Popura_Taneshima) is a promise-returning wrapper for MAL API.

## Warning

[MAL API is broken](https://myanimelist.net/forum/?topicid=1731860#msg55362465). Popura wont work until they solve their internal issues.

## Table of Contents

* [Install](#install)
* [Usage](#usage)
* [API](#api)
* [Models](#models)
 * [Anime Model][anime-model]
 * [Manga Model][manga-model]
 * [Anime List Item Model][anime-list-item-model]
 * [Manga List Item Model][manga-list-item-model]
 * [Myinfo Model][myinfo-model]
* [Development](#development)
* [License](#license)

## Install

```
$ npm install --save popura
```

## Usage

```js
import popura from 'popura';
const client = popura('YourAwesomeUsername', 'YourHackablePassword');

client.getAnimeList()
  .then(res => console.log(res))
  .catch(err => console.log(err));
```

## API

### `.getUser()`

Return the current user's username.

### `.setUser(username, password)`

Change the current user in this client instance.

### `.verifyAuth()`

Check if this user is valid.

Returns `Promise` => `{id, username}`.

### `.searchAnimes(name)` and `.searchMangas(name)`

Search for an anime or manga title by `name`.

Returns `Promise` => Array of [Anime Models][anime-model] | [Manga Models][manga-model].

### `.getAnimeList(username = this.user)` and `.getMangaList(username = this.user)`

Get the animelist or mangalist from an user. If `username` is empty, returns current user's list.

Returns `Promise` => `{myinfo, list}` where `myinfo` is a [Myinfo Model][myinfo-model] and `list` is an array of [Anime List Item Models][anime-list-item-model] | [Manga List Item Models][manga-list-item-model].

### `.addAnime(id, values = {})` and `.addManga(id, values = {})`

Inserts an anime or manga with `id` into your list. Optionally you can define `values` from [Anime Models][anime-model] | [Manga Models][manga-model].

Returns `Promise` => Raw `response.body`.

### `.updateAnime(id, values = {})` and `updateManga(id, values = {})`

Changes `values` from an anime or manga with `id` in your list. Define `values` from [Anime Models][anime-model] | [Manga Models][manga-model].

Returns `Promise` => Raw `response.body`.

### `.deleteAnime(id)` and `deleteManga(id)`

Removes an anime or manga with `id` from your list.

Returns `Promise` => Raw `response.body`.

## Models

### Anime Model

Model used to add/update animes

Property | Type | Note
-------- | ---- | ----
episode | int
status | `int` or `string` | `1` / `watching`, `2` / `completed`, `3` / `onhold`, `4` / `dropped`, `6` / `plantowatch`
score | `int`
storage_type | `int`
storage_value | `float`
times_rewatched | `int`
rewatch_value | `int`
date_start | `date` | `mmddyyyy`
date_finish | `date` | `mmddyyyy`
priority | `int`
enable_discussion | `int` | `1` = enable, `0` = disable
enable_rewatching | `int` | `1` = enable, `0` = disable
comments | `string`
fansub_group | `string`
tags | `array`

### Manga Model

Model used to add/update mangas

Property | Type | Note
-------- | ---- | ----
chapter | int
volume | int
status | `int` or `string` | `1` / `reading`, `2` / `completed`, `3` / `onhold`, `4` / `dropped`, `6` / `plantoread`
score | `int`
times_reread | `int`
reread_value | `int`
date_start | `date` | `mmddyyyy`
date_finish | `date` | `mmddyyyy`
priority | `int`
enable_discussion | `int` | `1` = enable, `0` = disable
enable_rereading | `int` | `1` = enable, `0` = disable
comments | `string`
scan_group | `string`
tags | `array`
retail_volumes | `int`

### Anime List Item Model

Model you receive from API when requesting anime list

Property | Type | Note
-------- | ---- | ----
series_animedb_id | `int`
series_title | `string`
series_synonyms | `array`
series_type | `int` | `1` = `TV`, `2` = `OVA`, `3` = `Movie`, `4` = `Special`, `5` = `ONA`, `6` = `Music`
series_episodes | `int`
series_status | `int` | `1` = `Airing`, `2` = `Finished`, `3` = `Not Yet Aired`
series_start | `date` | `mmddyyyy`
series_end | `date` | `mmddyyyy`
my_id | `int`
my_watched_episodes | `int`
my_start_date | `date` | `mmddyyyy`
my_finish_date | `date` | `mmddyyyy`
my_score | `int`
my_status | `int` | `1` = `watching`, `2` = `completed`, `3` = `onhold`, `4` = `dropped`, `6` = `plantowatch`
my_rewatching | `int`
my_rewatching_ep | `int`
my_last_updated | `date` | `mmddyyyy`
my_tags | `array`

### Manga List Item Model

Model you receive from API when requesting anime list

Property | Type | Note
-------- | ---- | ----
series_mangadb_id | `int`
series_title | `string`
series_synonyms | `array`
series_type | `int` | TODO: figure out the meaning of these `int`s
series_chapters | `int`
series_volumes | `int`
series_status | `int` | TODO: figure out the meaning of these `int`s
series_start | `date` | `mmddyyyy`
series_end | `date` | `mmddyyyy`
my_id | `int`
my_read_chapters | `int`
my_read_volumes | `int`
my_start_date | `date` | `mmddyyyy`
my_finish_date | `date` | `mmddyyyy`
my_score | `int`
my_status | `int` | `1` = `reading`, `2` = `completed`, `3` = `onhold`, `4` = `dropped`, `6` = `plantoread`
my_rereading | `int`
my_rereading_chap | `int`
my_last_updated | `date` | `mmddyyyy`
my_tags | `array`

### Myinfo Model

Property | Type | Note
-------- | ---- | ----
user_id | `int`
user_name | `string`
user_watching | `int` | Only for anime
user_reading | `int` | Only for manga
user_completed | `int`
user_onhold | `int`
user_dropped | `int`
user_plantowatch | `int` | Only for anime
user_plantoread | `int` | Only for manga
user_days_spent_watching | `float` | Yes, they use 'watching' for manga too

## Development

After clonning this repo, you must copy `.env.sample` to `.env` and put your MAL username and password.

In some tests, it'll add, update and remove one anime and one manga from your lists. You can specify these two at `.env`. Defaults to anime Tachumaru Gekijou (id = 9562) and manga Junshin Miracle 100% (id = 94483), two not so known titles.

## License

[MIT](LICENSE.md)

[myinfo-model]: #myinfo-model
[anime-model]: #anime-model
[manga-model]: #manga-model
[anime-list-item-model]: #anime-list-item-model
[manga-list-item-model]: #manga-list-item-model


text:
package io.mile.mileio;

import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.PolylineOptions;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;

import io.mile.mileio.types.Trip;

public class TripAdapter extends RecyclerView.Adapter<TripAdapter.ViewHolder> {
    private static final SimpleDateFormat whenFormat = new SimpleDateFormat("MM/dd/yy", Locale.US);
    private final ArrayList<Trip> trips;

    public TripAdapter(ArrayList<Trip> trips) {
        this.trips = trips;
    }

    @Override
    public TripAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_trip, parent, false);

        return new TripAdapter.ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(TripAdapter.ViewHolder holder, int position) {
        // Lookup view for data population
        Trip trip = trips.get(position);

        holder.distanceView.setText(
                String.format(Locale.US, "%.1f miles", 0d)
        );

        if (trip.getDriver() != null) {
            holder.operatorNameView.setText(
                    trip.getDriver().getDisplayName()
            );
        }

        holder.whenView.setText(
                whenFormat.format(trip.getWhenStarted())
        );

        // update map
        holder.setTripData(trip);
    }

    @Override
    public void onViewRecycled(ViewHolder holder) {
        if (holder.googleMap != null) {
            holder.googleMap.clear();
            holder.googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
        }
    }

    @Override
    public int getItemCount() {
        return trips.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements OnMapReadyCallback {
        private final int trackColor;
        public TextView operatorNameView;
        public TextView distanceView;
        public TextView whenView;
        public MapView mapView;
        public GoogleMap googleMap;

        private Trip tripData;

        public ViewHolder(View convertView) {
            super(convertView);

            operatorNameView = (TextView) convertView.findViewById(R.id.operator_name_view);
            distanceView = (TextView) convertView.findViewById(R.id.distance_view);
            whenView = (TextView) convertView.findViewById(R.id.when_view);

            mapView = (MapView) convertView.findViewById(R.id.map_view);

            if (mapView != null) {
                mapView.onCreate(null);
                mapView.onResume();
                mapView.getMapAsync(this);
            }

            trackColor = ContextCompat.getColor(convertView.getContext(), R.color.colorPrimaryDark);
        }

        @Override
        public void onMapReady(GoogleMap googleMap) {
            this.googleMap = googleMap;
            googleMap.getUiSettings().setAllGesturesEnabled(false);

            updateMap();
        }

        public void updateMap() {
            if (googleMap == null) {
                return;
            }

            googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

            PolylineOptions tripTrack = new PolylineOptions();

            tripTrack.color(trackColor);

            Random random = new Random();
            // fake trip data
            for (int i = 0; i < 10; i++) {
                tripTrack.add(new LatLng(42.291358 + random.nextDouble(), -71.265296 + random.nextDouble()));
            }

            googleMap.addPolyline(tripTrack);

            LatLngBounds.Builder boundBuilder = LatLngBounds.builder();

            for (LatLng point : tripTrack.getPoints()) {
                boundBuilder = boundBuilder.include(point);
            }

            LatLngBounds bounds = boundBuilder.build();

            googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 32));
        }

        public void setTripData(Trip tripData) {
            this.tripData = tripData;

            updateMap();
        }
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: R.Sadoyan
 * Date: 19.10.2015
 * Time: 11:41
 */
if (!class_exists('msPaymentInterface')) {
  require_once dirname(dirname(dirname(__FILE__))) . '/model/minishop2/mspaymenthandler.class.php';
}

class Rsb extends msPaymentHandler implements msPaymentInterface {

  function __construct(xPDOObject $object, $config = array()) {
    $this->modx = & $object->xpdo;

    $siteUrl = $this->modx->getOption('site_url');
    $assetsUrl = $this->modx->getOption('minishop2.assets_url', $config, $this->modx->getOption('assets_url').'components/minishop2/');
    // Файл в /assets/components/minishop2/
    $paymentUrl = $siteUrl . substr($assetsUrl, 1) . 'payment/Rsb.php';

    //Считываем настройки из конфига в MODX, если пустые подставляем свои значения
    $this->config = array_merge(array(
      'paymentUrl' => $paymentUrl
    ,'apiUrl' => $this->modx->getOption('ms2_payment_rsb_api_url', null, 'https://www.onlinecredit.ru/sites/anketa/minipotreb.php')
    , 'shop' => $this->modx->getOption('ms2_payment_rsb_shopname', null, '')
    , 'shopUrl' => $this->modx->getOption('ms2_payment_rsb_shopurl', null, '')
    , 'idTpl' => $this->modx->getOption('ms2_payment_rsb_idtlp', null, '')
    , 'mincost' => $this->modx->getOption('ms2_payment_rsb_mincost', null, '3000')
      //  ,'json_response' => false
    ), $config);
  }

  /* @inheritdoc} */
  public function send(msOrder $order) {
    $link = $this->getPaymentLink($order);
    return $this->success('', array('redirect' => $link));
  }

  public function getPaymentLink(msOrder $order) {
    $products = $order->getMany('Products');
    $count = count($products);
    $i = 1;
    $tolink = "";
    foreach ($products as $product) {
      $price = $product->get('price');
      $name = $product->get('name');
      $countp = $product->get('count');
      $tolink .= "&TC_$i=".$countp."&TPr_$i=".$price."&TName_$i=".$name;
      $i++;
    }
    $link = $this->config['apiUrl'] .'?'."IdTpl=". $this->config['idTpl']."&TTName=".$this->config['shopUrl']."&TCount=".$count.$tolink;
    return $link;
  }
}


text:
__author__ = 'Jon'

class DisableCSRF(object):
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)


text:
'use strict';

let database = require('../lib/mysql');
let _ = require('lodash');
let util = require('util');

module.exports = function (req, res, next) {
    let log = req.log;
    let body = req.body;

    let username = _.get(body, 'username');
    let password = _.get(body, 'password');

    let query = util.format("select * from users where username='%s'", username);
    log.info('query', query);

    database.select(query, function(result) {
        if (result && result.password === password) {
            res.json({ 'status': 'success' });
        } else {
            res.status(401).send();
        }
    });
};


text:
package com.westudio.java.util;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class Executors {

    private static final int POOL_SIZE = 50;

    private static AtomicInteger threadNum = new AtomicInteger(0);

    private static LinkedBlockingDeque<Runnable> queue = new LinkedBlockingDeque<>();

    public static int getThreadNum() {
        return threadNum.get();
    }

    private static Lazy<ThreadPoolExecutor> executor = new Lazy<ThreadPoolExecutor>() {
        @Override
        protected ThreadPoolExecutor makeObject() {
            ThreadPoolExecutor executor_ = new ThreadPoolExecutor(POOL_SIZE, POOL_SIZE,
                    1, TimeUnit.MINUTES, queue);
            executor_.allowCoreThreadTimeOut(true);
            return executor_;
        }

        @Override
        protected void destroyObj(ThreadPoolExecutor executor_) {
            executor_.shutdown();
            try {
                while (!executor_.awaitTermination(1, TimeUnit.SECONDS)) {/**/}
            } catch (InterruptedException e) {/**/}
        }
    };

    public static void execute(final Runnable runnable) {
        executor.getInstance().execute(new Runnable() {
            @Override
            public void run() {
                threadNum.incrementAndGet();
                try {
                    runnable.run();
                } catch (RuntimeException e) {

                } finally {
                    threadNum.decrementAndGet();
                }
            }
        });
    }

    public static void shutdown() {
        executor.close();
    }
}


text:
layout: example
categories: example/v1.0.0
version: v1.0.0
title: Display marker tooltip onload
description: Control whether a marker tooltip should be displayed on load
tags: [ui, markers]
---


text:
//-----------------------------------------------------------------------
// <copyright file="NFINetModule.cs">
//     Copyright (C) 2015-2015 lvsheng.huang <https://github.com/ketoo/NFrame>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NFrame
{
    public class NFCNet : NFINet
    {
        public NFCNet(OnSocketEvent xEventHandler, OnRecivePack xPackHandler)
        {

        }

        public override void Initialization(string strIP, UInt16 nPort)
        {

        }

        public override int Initialization(UInt32 nMaxClient, UInt16 nPort)
        {
            return 0;
        }

        public override bool Final()
        {
            return true;
        }

        //无包头,内部组装
        public override bool SendMsgWithOutHead(UInt16 nMsgID, string msg, UInt32 nSockIndex)
        {
            return true;
        }

        //无包头,内部组装
        public override bool SendMsgWithOutHead(UInt16 nMsgID, string msg, List<UInt32> fdList)
        {
            return true;
        }

        //无包头,内部组装
        public override bool SendMsgToAllClientWithOutHead(UInt16 nMsgID, string msg)
        {
            return true;
        }

        public override int CloseNetObject(UInt32 nSockIndex)
        {
            return 0;
        }

        public override int IsServer()
        {
            return 0;
        }

        public override int Log(int severity, string msg)
        {
            return 0;
        }
    }
}