text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import gym
import numpy as np
import time
import unittest

import ray
from ray.rllib.agents.ppo import PPOTrainer
from ray.rllib.agents.ppo.ppo_policy import PPOTFPolicy
from ray.rllib.evaluation import SampleBatch
from ray.rllib.evaluation.rollout_worker import RolloutWorker
from ray.rllib.evaluation.worker_set import WorkerSet
from ray.rllib.optimizers import AsyncGradientsOptimizer, AsyncSamplesOptimizer
from ray.rllib.optimizers.aso_tree_aggregator import TreeAggregator
from ray.rllib.tests.mock_worker import _MockWorker
from ray.rllib.utils import try_import_tf

tf = try_import_tf()

class AsyncOptimizerTest(unittest.TestCase):
    def tearDown(self):
        ray.shutdown()

    def testBasic(self):
        ray.init(num_cpus=4)
        local = _MockWorker()
        remotes = ray.remote(_MockWorker)
        remote_workers = [remotes.remote() for i in range(5)]
        workers = WorkerSet._from_existing(local, remote_workers)
        test_optimizer = AsyncGradientsOptimizer(workers, grads_per_step=10)
        test_optimizer.step()
        self.assertTrue(all(local.get_weights() == 0))

class PPOCollectTest(unittest.TestCase):
    def tearDown(self):
        ray.shutdown()

    def testPPOSampleWaste(self):
        ray.init(num_cpus=4)

        # Check we at least collect the initial wave of samples
        ppo = PPOTrainer(
            env="CartPole-v0",
            config={
                "sample_batch_size": 200,
                "train_batch_size": 128,
                "num_workers": 3,
            })
        ppo.train()
        self.assertEqual(ppo.optimizer.num_steps_sampled, 600)
        ppo.stop()

        # Check we collect at least the specified amount of samples
        ppo = PPOTrainer(
            env="CartPole-v0",
            config={
                "sample_batch_size": 200,
                "train_batch_size": 900,
                "num_workers": 3,
            })
        ppo.train()
        self.assertEqual(ppo.optimizer.num_steps_sampled, 1000)
        ppo.stop()

        # Check in vectorized mode
        ppo = PPOTrainer(
            env="CartPole-v0",
            config={
                "sample_batch_size": 200,
                "num_envs_per_worker": 2,
                "train_batch_size": 900,
                "num_workers": 3,
            })
        ppo.train()
        self.assertEqual(ppo.optimizer.num_steps_sampled, 1200)
        ppo.stop()

        # Check legacy mode
        ppo = PPOTrainer(
            env="CartPole-v0",
            config={
                "sample_batch_size": 200,
                "train_batch_size": 128,
                "num_workers": 3,
                "straggler_mitigation": True,
            })
        ppo.train()
        self.assertEqual(ppo.optimizer.num_steps_sampled, 200)
        ppo.stop()

class SampleBatchTest(unittest.TestCase):
    def testConcat(self):
        b1 = SampleBatch({"a": np.array([1, 2, 3]), "b": np.array([4, 5, 6])})
        b2 = SampleBatch({"a": np.array([1]), "b": np.array([4])})
        b3 = SampleBatch({"a": np.array([1]), "b": np.array([5])})
        b12 = b1.concat(b2)
        self.assertEqual(b12["a"].tolist(), [1, 2, 3, 1])
        self.assertEqual(b12["b"].tolist(), [4, 5, 6, 4])
        b = SampleBatch.concat_samples([b1, b2, b3])
        self.assertEqual(b["a"].tolist(), [1, 2, 3, 1, 1])
        self.assertEqual(b["b"].tolist(), [4, 5, 6, 4, 5])

class AsyncSamplesOptimizerTest(unittest.TestCase):
    @classmethod
    def tearDownClass(cls):
        ray.shutdown()

    @classmethod
    def setUpClass(cls):
        ray.init(num_cpus=8)

    def testSimple(self):
        local, remotes = self._make_evs()
        workers = WorkerSet._from_existing(local, remotes)
        optimizer = AsyncSamplesOptimizer(workers)
        self._wait_for(optimizer, 1000, 1000)

    def testMultiGPU(self):
        local, remotes = self._make_evs()
        workers = WorkerSet._from_existing(local, remotes)
        optimizer = AsyncSamplesOptimizer(workers, num_gpus=2, _fake_gpus=True)
        self._wait_for(optimizer, 1000, 1000)

    def testMultiGPUParallelLoad(self):
        local, remotes = self._make_evs()
        workers = WorkerSet._from_existing(local, remotes)
        optimizer = AsyncSamplesOptimizer(
            workers, num_gpus=2, num_data_loader_buffers=2, _fake_gpus=True)
        self._wait_for(optimizer, 1000, 1000)

    def testMultiplePasses(self):
        local, remotes = self._make_evs()
        workers = WorkerSet._from_existing(local, remotes)
        optimizer = AsyncSamplesOptimizer(
            workers,
            minibatch_buffer_size=10,
            num_sgd_iter=10,
            sample_batch_size=10,
            train_batch_size=50)
        self._wait_for(optimizer, 1000, 10000)
        self.assertLess(optimizer.stats()["num_steps_sampled"], 5000)
        self.assertGreater(optimizer.stats()["num_steps_trained"], 8000)

    def testReplay(self):
        local, remotes = self._make_evs()
        workers = WorkerSet._from_existing(local, remotes)
        optimizer = AsyncSamplesOptimizer(
            workers,
            replay_buffer_num_slots=100,
            replay_proportion=10,
            sample_batch_size=10,
            train_batch_size=10,
        )
        self._wait_for(optimizer, 1000, 1000)
        stats = optimizer.stats()
        self.assertLess(stats["num_steps_sampled"], 5000)
        replay_ratio = stats["num_steps_replayed"] / stats["num_steps_sampled"]
        self.assertGreater(replay_ratio, 0.7)
        self.assertLess(stats["num_steps_trained"], stats["num_steps_sampled"])

    def testReplayAndMultiplePasses(self):
        local, remotes = self._make_evs()
        workers = WorkerSet._from_existing(local, remotes)
        optimizer = AsyncSamplesOptimizer(
            workers,
            minibatch_buffer_size=10,
            num_sgd_iter=10,
            replay_buffer_num_slots=100,
            replay_proportion=10,
            sample_batch_size=10,
            train_batch_size=10)
        self._wait_for(optimizer, 1000, 1000)

        stats = optimizer.stats()
        print(stats)
        self.assertLess(stats["num_steps_sampled"], 5000)
        replay_ratio = stats["num_steps_replayed"] / stats["num_steps_sampled"]
        train_ratio = stats["num_steps_sampled"] / stats["num_steps_trained"]
        self.assertGreater(replay_ratio, 0.7)
        self.assertLess(train_ratio, 0.4)

    def testMultiTierAggregationBadConf(self):
        local, remotes = self._make_evs()
        workers = WorkerSet._from_existing(local, remotes)
        aggregators = TreeAggregator.precreate_aggregators(4)
        optimizer = AsyncSamplesOptimizer(workers, num_aggregation_workers=4)
        self.assertRaises(ValueError,
                          lambda: optimizer.aggregator.init(aggregators))

    def testMultiTierAggregation(self):
        local, remotes = self._make_evs()
        workers = WorkerSet._from_existing(local, remotes)
        aggregators = TreeAggregator.precreate_aggregators(1)
        optimizer = AsyncSamplesOptimizer(workers, num_aggregation_workers=1)
        optimizer.aggregator.init(aggregators)
        self._wait_for(optimizer, 1000, 1000)

    def testRejectBadConfigs(self):
        local, remotes = self._make_evs()
        workers = WorkerSet._from_existing(local, remotes)
        self.assertRaises(
            ValueError, lambda: AsyncSamplesOptimizer(
                local, remotes,
                num_data_loader_buffers=2, minibatch_buffer_size=4))
        optimizer = AsyncSamplesOptimizer(
            workers,
            num_gpus=2,
            train_batch_size=100,
            sample_batch_size=50,
            _fake_gpus=True)
        self._wait_for(optimizer, 1000, 1000)
        optimizer = AsyncSamplesOptimizer(
            workers,
            num_gpus=2,
            train_batch_size=100,
            sample_batch_size=25,
            _fake_gpus=True)
        self._wait_for(optimizer, 1000, 1000)
        optimizer = AsyncSamplesOptimizer(
            workers,
            num_gpus=2,
            train_batch_size=100,
            sample_batch_size=74,
            _fake_gpus=True)
        self._wait_for(optimizer, 1000, 1000)

    def _make_evs(self):
        def make_sess():
            return tf.Session(config=tf.ConfigProto(device_count={"CPU": 2}))

        local = RolloutWorker(
            env_creator=lambda _: gym.make("CartPole-v0"),
            policy=PPOTFPolicy,
            tf_session_creator=make_sess)
        remotes = [
            RolloutWorker.as_remote().remote(
                env_creator=lambda _: gym.make("CartPole-v0"),
                policy=PPOTFPolicy,
                tf_session_creator=make_sess)
        ]
        return local, remotes

    def _wait_for(self, optimizer, num_steps_sampled, num_steps_trained):
        start = time.time()
        while time.time() - start < 30:
            optimizer.step()
            if optimizer.num_steps_sampled > num_steps_sampled and \
                    optimizer.num_steps_trained > num_steps_trained:
                print("OK", optimizer.stats())
                return
        raise AssertionError("TIMED OUT", optimizer.stats())

if __name__ == "__main__":
    unittest.main(verbosity=2)


text:
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require("extract-text-webpack-plugin");

const DEBUG = !process.argv.includes('--release');

const entries = ['./examples/src/example'];
if (DEBUG) {
  entries.unshift('react-hot-loader/patch');
  entries.unshift('webpack-dev-server/client?http://localhost:3000');
  entries.unshift('webpack/hot/only-dev-server');
}

var config = {
  devtool: 'eval',
  entry: entries,
  output: {
    path: path.join(__dirname, 'dist/examples'),
    filename: '[name].js',
  },
  resolve: {
    extensions: ['', '.js', '.jsx'],
  },
  plugins: [
    new HtmlWebpackPlugin({template: 'examples/src/index.html'}),
    new ExtractTextPlugin("[name].css")
  ],
  module: {
    loaders: [
      {test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader", "css-loader")},
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        exclude: /(node_modules)/
      }]
  }
};

if (DEBUG) {
  config.plugins.unshift(new webpack.HotModuleReplacementPlugin());
}

module.exports = config;

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>

   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

  <link href="css/election.css" rel="stylesheet">
    <link href="css/bootstrap.min.css" rel="stylesheet">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">

  <link rel="stylesheet" href="css/site.css">
  <link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,800,700,400italic,600italic,700italic,800italic,300italic" rel="stylesheet" type="text/css">

  <title>Elections 2014 | Daily Bruin</title>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>

      CANDIDATES

GOVERNOR

CONGRESS

STATE SENATE

LA COUNTY BOARD OF SUPERVISORS

STATE ASSEMBLY

PROPOSITIONS

ENDORSEMENTS

RESULTS

WHERE TO VOTE

Ben Allen

                  Party
                  Democrat

                Biography
                36 years old. Graduated from Harvard, Cambridge and UC Berkeley Law School. A lawyer and current member of the Santa Monica-Malibu Unified School District Board. A lecturer at the UCLA School of Law and former student regent at the UC.

                  Platform

Prioritizing state funding for the universities and giving the legislature a stronger voice in funding higher education

Training workers and keeping jobs in the region through incentives while restoring funds to welfare programs

Moratorium on "fracking," and conserving water through recycling, rainwater diversion, etc.

Sandra Fluke

                  Party
                  Democrat

                Biography
                33 years old. Graduated from Cornell University and Georgetown University Law Center. A human rights lawyer. Made a congressional testimony in 2012 regarding insurance coverage for birth control, which gained national attention.

                  Platform

Funding public state universities at a higher level while putting a greater emphasis on science, technology, engineering and mathematics programs.

Investing in start-up companies and training students to have technological skills needed for jobs in those companies.

Having a state audit of state employees to examine whether both men and women are paid equally for same work; extending paid family leave policy.

                                More in News

                              Students Garner Support To Give Campaigns Push For Midterm Elections

                              State Primary Sees Intense Competition With Intense List of Candidates

                              Senate Candidates Discuss Platforms During on Campus Forum

                                More in Opinions

                              No topics available.

Elections 2014  |  Home  |  News  |  Sports  |  A&E  |  Opinion

Site by Li-Wei Tseng and Rakshit Garg, Contributors. Content © 2014 the Daily Bruin.


text:
import {
  onFrameStart,
  onFrameUpdate,
  onFrameRender,
  onFrameEnd,
  cancelOnFrameStart,
  cancelOnFrameUpdate,
  cancelOnFrameRender,
  cancelOnFrameEnd,
  timeSinceLastFrame,
  currentFrameTime,
  currentTime
} from "framesync";

const noop = v => {};

// Framesync
onFrameStart(noop);
onFrameUpdate(noop);
onFrameRender(noop);
onFrameEnd(noop);
cancelOnFrameStart(noop);
cancelOnFrameUpdate(noop);
cancelOnFrameRender(noop);
cancelOnFrameEnd(noop);
// $FlowExpectedError
onFrameStart(1);
// $FlowExpectedError
cancelOnFrameStart(1);

let t: number = 0;
let s: string = "";

t = timeSinceLastFrame();
t = currentFrameTime();
t = currentTime();
// $FlowExpectedError
s = timeSinceLastFrame();
// $FlowExpectedError
s = currentFrameTime();
// $FlowExpectedError
s = currentTime();


text:
name: Bug report
about: Create a report to detail an error or unexpected behavior
title: ''
labels: ''
assignees: ''
---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:
1. Open the project, run '...'
2. Type '...' or do '...'
3. ...

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Platform:**
 - OS: [e.g. Windows 10 x64]
 - Version [e.g. neo-cli 2.10.2]

**(Optional) Additional context**
Add any other context about the problem here.

However, if your issue does not fit these aforementioned criteria, or it can be understood in another manner, feel free to open it in a different format.


text:
@interface TSLander()
@property(assign, nonatomic, readwrite) NSUInteger ident;
@property(strong, nonatomic, readwrite) NSString *html;
@property(strong, nonatomic, readwrite) NSURL *url;
@end

@implementation TSLander
+ (instancetype)landerWithDescription:(NSDictionary *)descriptionVal
{
	return [[TSLander alloc] initWithDescription:descriptionVal];
}

- (instancetype)initWithDescription:(NSDictionary *)descriptionVal
{
	self.ident = -1;
	self.html = nil;
	self.url = nil;

	if(self = [super init]) {
		id ident = [descriptionVal objectForKey:@"id"];
		if(ident != nil && ident != (id)[NSNull null]){
			self.ident = [ident unsignedIntegerValue];
		}

		NSString* html = [descriptionVal objectForKey:@"markup"];
		if(html != nil && html != (id)[NSNull null]){
			self.html = html;
		}

		NSString* urlString = [descriptionVal objectForKey:@"url"];
		if(urlString != nil && urlString != (id)[NSNull null]){
			self.url = [NSURL URLWithString:urlString];
		}
	}
	return self;
}
- (BOOL)isValid
{
	if(self.ident <= 0)
	{
		return false;
	}

	// Markup type: any HTML is ok
	if(self.url == nil && self.html != nil)
	{
		return true;
	}

	// Url type: make sure url is present and scheme is http or https
	if(self.url == nil)
	{
		return false;
	}

	if([[self.url scheme] isEqualToString:@"http"])
	{
		return true;
	}

	if([[self.url scheme] isEqualToString:@"https"])
	{
		return true;
	}

	return false;
}
@end


text:
from .. import sql, util, event, exc as sa_exc, inspection
from ..sql import expression, util as sql_util, operators
from .interfaces import PropComparator, MapperProperty
from . import attributes
import re

from .base import instance_str, state_str, state_class_str, attribute_str, \
    state_attribute_str, object_mapper, object_state, _none_set, _never_set
from .base import class_mapper, _class_to_mapper
from .base import InspectionAttr
from .path_registry import PathRegistry

all_cascades = frozenset(("delete", "delete-orphan", "all", "merge",
                          "expunge", "save-update", "refresh-expire",
                          "none"))

class CascadeOptions(frozenset):
    """Keeps track of the options sent to relationship().cascade"""

    _add_w_all_cascades = all_cascades.difference([
        'all', 'none', 'delete-orphan'])
    _allowed_cascades = all_cascades

    __slots__ = (
        'save_update', 'delete', 'refresh_expire', 'merge',
        'expunge', 'delete_orphan')

    def __new__(cls, value_list):
        if isinstance(value_list, util.string_types) or value_list is None:
            return cls.from_string(value_list)
        values = set(value_list)
        if values.difference(cls._allowed_cascades):
            raise sa_exc.ArgumentError(
                "Invalid cascade option(s): %s" %
                ", ".join([repr(x) for x in
                           sorted(values.difference(cls._allowed_cascades))]))

        if "all" in values:
            values.update(cls._add_w_all_cascades)
        if "none" in values:
            values.clear()
        values.discard('all')

        self = frozenset.__new__(CascadeOptions, values)
        self.save_update = 'save-update' in values
        self.delete = 'delete' in values
        self.refresh_expire = 'refresh-expire' in values
        self.merge = 'merge' in values
        self.expunge = 'expunge' in values
        self.delete_orphan = "delete-orphan" in values

        if self.delete_orphan and not self.delete:
            util.warn("The 'delete-orphan' cascade "
                      "option requires 'delete'.")
        return self

    def __repr__(self):
        return "CascadeOptions(%r)" % (
            ",".join([x for x in sorted(self)])
        )

    @classmethod
    def from_string(cls, arg):
        values = [
            c for c
            in re.split(r'\s*,\s*', arg or "")
            if c
        ]
        return cls(values)

def _validator_events(
        desc, key, validator, include_removes, include_backrefs):
    """Runs a validation method on an attribute value to be set or
    appended.
    """

    if not include_backrefs:
        def detect_is_backref(state, initiator):
            impl = state.manager[key].impl
            return initiator.impl is not impl

    if include_removes:
        def append(state, value, initiator):
            if include_backrefs or not detect_is_backref(state, initiator):
                return validator(state.obj(), key, value, False)
            else:
                return value

        def set_(state, value, oldvalue, initiator):
            if include_backrefs or not detect_is_backref(state, initiator):
                return validator(state.obj(), key, value, False)
            else:
                return value

        def remove(state, value, initiator):
            if include_backrefs or not detect_is_backref(state, initiator):
                validator(state.obj(), key, value, True)

    else:
        def append(state, value, initiator):
            if include_backrefs or not detect_is_backref(state, initiator):
                return validator(state.obj(), key, value)
            else:
                return value

        def set_(state, value, oldvalue, initiator):
            if include_backrefs or not detect_is_backref(state, initiator):
                return validator(state.obj(), key, value)
            else:
                return value

    event.listen(desc, 'append', append, raw=True, retval=True)
    event.listen(desc, 'set', set_, raw=True, retval=True)
    if include_removes:
        event.listen(desc, "remove", remove, raw=True, retval=True)

def polymorphic_union(table_map, typecolname,
                      aliasname='p_union', cast_nulls=True):
    """Create a ``UNION`` statement used by a polymorphic mapper.

    See  :ref:`concrete_inheritance` for an example of how
    this is used.

    :param table_map: mapping of polymorphic identities to
     :class:`.Table` objects.
    :param typecolname: string name of a "discriminator" column, which will be
     derived from the query, producing the polymorphic identity for
     each row.  If ``None``, no polymorphic discriminator is generated.
    :param aliasname: name of the :func:`~sqlalchemy.sql.expression.alias()`
     construct generated.
    :param cast_nulls: if True, non-existent columns, which are represented
     as labeled NULLs, will be passed into CAST.   This is a legacy behavior
     that is problematic on some backends such as Oracle - in which case it
     can be set to False.

    """

    colnames = util.OrderedSet()
    colnamemaps = {}
    types = {}
    for key in table_map:
        table = table_map[key]

        # mysql doesn't like selecting from a select;
        # make it an alias of the select
        if isinstance(table, sql.Select):
            table = table.alias()
            table_map[key] = table

        m = {}
        for c in table.c:
            colnames.add(c.key)
            m[c.key] = c
            types[c.key] = c.type
        colnamemaps[table] = m

    def col(name, table):
        try:
            return colnamemaps[table][name]
        except KeyError:
            if cast_nulls:
                return sql.cast(sql.null(), types[name]).label(name)
            else:
                return sql.type_coerce(sql.null(), types[name]).label(name)

    result = []
    for type, table in table_map.items():
        if typecolname is not None:
            result.append(
                sql.select([col(name, table) for name in colnames] +
                           [sql.literal_column(
                               sql_util._quote_ddl_expr(type)).
                               label(typecolname)],
                           from_obj=[table]))
        else:
            result.append(sql.select([col(name, table) for name in colnames],
                                     from_obj=[table]))
    return sql.union_all(*result).alias(aliasname)

def identity_key(*args, **kwargs):
    """Generate "identity key" tuples, as are used as keys in the
    :attr:`.Session.identity_map` dictionary.

    This function has several call styles:

    * ``identity_key(class, ident)``

      This form receives a mapped class and a primary key scalar or
      tuple as an argument.

      E.g.::

        >>> identity_key(MyClass, (1, 2))
        (<class '__main__.MyClass'>, (1, 2))

      :param class: mapped class (must be a positional argument)
      :param ident: primary key, may be a scalar or tuple argument.

    * ``identity_key(instance=instance)``

      This form will produce the identity key for a given instance.  The
      instance need not be persistent, only that its primary key attributes
      are populated (else the key will contain ``None`` for those missing
      values).

      E.g.::

        >>> instance = MyClass(1, 2)
        >>> identity_key(instance=instance)
        (<class '__main__.MyClass'>, (1, 2))

      In this form, the given instance is ultimately run though
      :meth:`.Mapper.identity_key_from_instance`, which will have the
      effect of performing a database check for the corresponding row
      if the object is expired.

      :param instance: object instance (must be given as a keyword arg)

    * ``identity_key(class, row=row)``

      This form is similar to the class/tuple form, except is passed a
      database result row as a :class:`.RowProxy` object.

      E.g.::

        >>> row = engine.execute("select * from table where a=1 and b=2").\
first()
        >>> identity_key(MyClass, row=row)
        (<class '__main__.MyClass'>, (1, 2))

      :param class: mapped class (must be a positional argument)
      :param row: :class:`.RowProxy` row returned by a :class:`.ResultProxy`
       (must be given as a keyword arg)

    """
    if args:
        if len(args) == 1:
            class_ = args[0]
            try:
                row = kwargs.pop("row")
            except KeyError:
                ident = kwargs.pop("ident")
        elif len(args) == 2:
            class_, ident = args
        elif len(args) == 3:
            class_, ident = args
        else:
            raise sa_exc.ArgumentError(
                "expected up to three positional arguments, "
                "got %s" % len(args))
        if kwargs:
            raise sa_exc.ArgumentError("unknown keyword arguments: %s"
                                       % ", ".join(kwargs))
        mapper = class_mapper(class_)
        if "ident" in locals():
            return mapper.identity_key_from_primary_key(util.to_list(ident))
        return mapper.identity_key_from_row(row)
    instance = kwargs.pop("instance")
    if kwargs:
        raise sa_exc.ArgumentError("unknown keyword arguments: %s"
                                   % ", ".join(kwargs.keys))
    mapper = object_mapper(instance)
    return mapper.identity_key_from_instance(instance)

class ORMAdapter(sql_util.ColumnAdapter):
    """ColumnAdapter subclass which excludes adaptation of entities from
    non-matching mappers.

    """

    def __init__(self, entity, equivalents=None, adapt_required=False,
                 chain_to=None, allow_label_resolve=True,
                 anonymize_labels=False):
        info = inspection.inspect(entity)

        self.mapper = info.mapper
        selectable = info.selectable
        is_aliased_class = info.is_aliased_class
        if is_aliased_class:
            self.aliased_class = entity
        else:
            self.aliased_class = None

        sql_util.ColumnAdapter.__init__(
            self, selectable, equivalents, chain_to,
            adapt_required=adapt_required,
            allow_label_resolve=allow_label_resolve,
            anonymize_labels=anonymize_labels,
            include_fn=self._include_fn
        )

    def _include_fn(self, elem):
        entity = elem._annotations.get('parentmapper', None)
        return not entity or entity.isa(self.mapper)

class AliasedClass(object):
    r"""Represents an "aliased" form of a mapped class for usage with Query.

    The ORM equivalent of a :func:`sqlalchemy.sql.expression.alias`
    construct, this object mimics the mapped class using a
    __getattr__ scheme and maintains a reference to a
    real :class:`~sqlalchemy.sql.expression.Alias` object.

    Usage is via the :func:`.orm.aliased` function, or alternatively
    via the :func:`.orm.with_polymorphic` function.

    Usage example::

        # find all pairs of users with the same name
        user_alias = aliased(User)
        session.query(User, user_alias).\
                        join((user_alias, User.id > user_alias.id)).\
                        filter(User.name==user_alias.name)

    The resulting object is an instance of :class:`.AliasedClass`.
    This object implements an attribute scheme which produces the
    same attribute and method interface as the original mapped
    class, allowing :class:`.AliasedClass` to be compatible
    with any attribute technique which works on the original class,
    including hybrid attributes (see :ref:`hybrids_toplevel`).

    The :class:`.AliasedClass` can be inspected for its underlying
    :class:`.Mapper`, aliased selectable, and other information
    using :func:`.inspect`::

        from sqlalchemy import inspect
        my_alias = aliased(MyClass)
        insp = inspect(my_alias)

    The resulting inspection object is an instance of :class:`.AliasedInsp`.

    See :func:`.aliased` and :func:`.with_polymorphic` for construction
    argument descriptions.

    """

    def __init__(self, cls, alias=None,
                 name=None,
                 flat=False,
                 adapt_on_names=False,
                 #  TODO: None for default here?
                 with_polymorphic_mappers=(),
                 with_polymorphic_discriminator=None,
                 base_alias=None,
                 use_mapper_path=False):
        mapper = _class_to_mapper(cls)
        if alias is None:
            alias = mapper._with_polymorphic_selectable.alias(
                name=name, flat=flat)

        self._aliased_insp = AliasedInsp(
            self,
            mapper,
            alias,
            name,
            with_polymorphic_mappers
            if with_polymorphic_mappers
            else mapper.with_polymorphic_mappers,
            with_polymorphic_discriminator
            if with_polymorphic_discriminator is not None
            else mapper.polymorphic_on,
            base_alias,
            use_mapper_path,
            adapt_on_names
        )

        self.__name__ = 'AliasedClass_%s' % mapper.class_.__name__

    def __getattr__(self, key):
        try:
            _aliased_insp = self.__dict__['_aliased_insp']
        except KeyError:
            raise AttributeError()
        else:
            for base in _aliased_insp._target.__mro__:
                try:
                    attr = object.__getattribute__(base, key)
                except AttributeError:
                    continue
                else:
                    break
            else:
                raise AttributeError(key)

        if isinstance(attr, PropComparator):
            ret = attr.adapt_to_entity(_aliased_insp)
            setattr(self, key, ret)
            return ret
        elif hasattr(attr, 'func_code'):
            is_method = getattr(_aliased_insp._target, key, None)
            if is_method and is_method.__self__ is not None:
                return util.types.MethodType(attr.__func__, self, self)
            else:
                return None
        elif hasattr(attr, '__get__'):
            ret = attr.__get__(None, self)
            if isinstance(ret, PropComparator):
                return ret.adapt_to_entity(_aliased_insp)
            else:
                return ret
        else:
            return attr

    def __repr__(self):
        return '<AliasedClass at 0x%x; %s>' % (
            id(self), self._aliased_insp._target.__name__)

class AliasedInsp(InspectionAttr):
    """Provide an inspection interface for an
    :class:`.AliasedClass` object.

    The :class:`.AliasedInsp` object is returned
    given an :class:`.AliasedClass` using the
    :func:`.inspect` function::

        from sqlalchemy import inspect
        from sqlalchemy.orm import aliased

        my_alias = aliased(MyMappedClass)
        insp = inspect(my_alias)

    Attributes on :class:`.AliasedInsp`
    include:

    * ``entity`` - the :class:`.AliasedClass` represented.
    * ``mapper`` - the :class:`.Mapper` mapping the underlying class.
    * ``selectable`` - the :class:`.Alias` construct which ultimately
      represents an aliased :class:`.Table` or :class:`.Select`
      construct.
    * ``name`` - the name of the alias.  Also is used as the attribute
      name when returned in a result tuple from :class:`.Query`.
    * ``with_polymorphic_mappers`` - collection of :class:`.Mapper` objects
      indicating all those mappers expressed in the select construct
      for the :class:`.AliasedClass`.
    * ``polymorphic_on`` - an alternate column or SQL expression which
      will be used as the "discriminator" for a polymorphic load.

    .. seealso::

        :ref:`inspection_toplevel`

    """

    def __init__(self, entity, mapper, selectable, name,
                 with_polymorphic_mappers, polymorphic_on,
                 _base_alias, _use_mapper_path, adapt_on_names):
        self.entity = entity
        self.mapper = mapper
        self.selectable = selectable
        self.name = name
        self.with_polymorphic_mappers = with_polymorphic_mappers
        self.polymorphic_on = polymorphic_on
        self._base_alias = _base_alias or self
        self._use_mapper_path = _use_mapper_path

        self._adapter = sql_util.ColumnAdapter(
            selectable, equivalents=mapper._equivalent_columns,
            adapt_on_names=adapt_on_names, anonymize_labels=True)

        self._adapt_on_names = adapt_on_names
        self._target = mapper.class_

        for poly in self.with_polymorphic_mappers:
            if poly is not mapper:
                setattr(self.entity, poly.class_.__name__,
                        AliasedClass(poly.class_, selectable, base_alias=self,
                                     adapt_on_names=adapt_on_names,
                                     use_mapper_path=_use_mapper_path))

    is_aliased_class = True
    "always returns True"

    @property
    def class_(self):
        """Return the mapped class ultimately represented by this
        :class:`.AliasedInsp`."""
        return self.mapper.class_

    @util.memoized_property
    def _path_registry(self):
        if self._use_mapper_path:
            return self.mapper._path_registry
        else:
            return PathRegistry.per_mapper(self)

    def __getstate__(self):
        return {
            'entity': self.entity,
            'mapper': self.mapper,
            'alias': self.selectable,
            'name': self.name,
            'adapt_on_names': self._adapt_on_names,
            'with_polymorphic_mappers':
                self.with_polymorphic_mappers,
            'with_polymorphic_discriminator':
                self.polymorphic_on,
            'base_alias': self._base_alias,
            'use_mapper_path': self._use_mapper_path
        }

    def __setstate__(self, state):
        self.__init__(
            state['entity'],
            state['mapper'],
            state['alias'],
            state['name'],
            state['with_polymorphic_mappers'],
            state['with_polymorphic_discriminator'],
            state['base_alias'],
            state['use_mapper_path'],
            state['adapt_on_names']
        )

    def _adapt_element(self, elem):
        return self._adapter.traverse(elem).\
            _annotate({
                'parententity': self,
                'parentmapper': self.mapper}
        )

    def _entity_for_mapper(self, mapper):
        self_poly = self.with_polymorphic_mappers
        if mapper in self_poly:
            if mapper is self.mapper:
                return self
            else:
                return getattr(
                    self.entity, mapper.class_.__name__)._aliased_insp
        elif mapper.isa(self.mapper):
            return self
        else:
            assert False, "mapper %s doesn't correspond to %s" % (
                mapper, self)

    @util.memoized_property
    def _memoized_values(self):
        return {}

    def _memo(self, key, callable_, *args, **kw):
        if key in self._memoized_values:
            return self._memoized_values[key]
        else:
            self._memoized_values[key] = value = callable_(*args, **kw)
            return value

    def __repr__(self):
        if self.with_polymorphic_mappers:
            with_poly = "(%s)" % ", ".join(
                mp.class_.__name__ for mp in self.with_polymorphic_mappers)
        else:
            with_poly = ""
        return '<AliasedInsp at 0x%x; %s%s>' % (
            id(self), self.class_.__name__, with_poly)

inspection._inspects(AliasedClass)(lambda target: target._aliased_insp)
inspection._inspects(AliasedInsp)(lambda target: target)

def aliased(element, alias=None, name=None, flat=False, adapt_on_names=False):
    """Produce an alias of the given element, usually an :class:`.AliasedClass`
    instance.

    E.g.::

        my_alias = aliased(MyClass)

        session.query(MyClass, my_alias).filter(MyClass.id > my_alias.id)

    The :func:`.aliased` function is used to create an ad-hoc mapping
    of a mapped class to a new selectable.  By default, a selectable
    is generated from the normally mapped selectable (typically a
    :class:`.Table`) using the :meth:`.FromClause.alias` method.
    However, :func:`.aliased` can also be used to link the class to
    a new :func:`.select` statement.   Also, the :func:`.with_polymorphic`
    function is a variant of :func:`.aliased` that is intended to specify
    a so-called "polymorphic selectable", that corresponds to the union
    of several joined-inheritance subclasses at once.

    For convenience, the :func:`.aliased` function also accepts plain
    :class:`.FromClause` constructs, such as a :class:`.Table` or
    :func:`.select` construct.   In those cases, the :meth:`.FromClause.alias`
    method is called on the object and the new :class:`.Alias` object
    returned.  The returned :class:`.Alias` is not ORM-mapped in this case.

    :param element: element to be aliased.  Is normally a mapped class,
     but for convenience can also be a :class:`.FromClause` element.

    :param alias: Optional selectable unit to map the element to.  This should
     normally be a :class:`.Alias` object corresponding to the :class:`.Table`
     to which the class is mapped, or to a :func:`.select` construct that
     is compatible with the mapping.   By default, a simple anonymous
     alias of the mapped table is generated.

    :param name: optional string name to use for the alias, if not specified
     by the ``alias`` parameter.  The name, among other things, forms the
     attribute name that will be accessible via tuples returned by a
     :class:`.Query` object.

    :param flat: Boolean, will be passed through to the
     :meth:`.FromClause.alias` call so that aliases of :class:`.Join` objects
     don't include an enclosing SELECT.  This can lead to more efficient
     queries in many circumstances.  A JOIN against a nested JOIN will be
     rewritten as a JOIN against an aliased SELECT subquery on backends that
     don't support this syntax.

     .. versionadded:: 0.9.0

     .. seealso:: :meth:`.Join.alias`

    :param adapt_on_names: if True, more liberal "matching" will be used when
     mapping the mapped columns of the ORM entity to those of the
     given selectable - a name-based match will be performed if the
     given selectable doesn't otherwise have a column that corresponds
     to one on the entity.  The use case for this is when associating
     an entity with some derived selectable such as one that uses
     aggregate functions::

        class UnitPrice(Base):
            __tablename__ = 'unit_price'
            ...
            unit_id = Column(Integer)
            price = Column(Numeric)

        aggregated_unit_price = Session.query(
                                    func.sum(UnitPrice.price).label('price')
                                ).group_by(UnitPrice.unit_id).subquery()

        aggregated_unit_price = aliased(UnitPrice,
                    alias=aggregated_unit_price, adapt_on_names=True)

     Above, functions on ``aggregated_unit_price`` which refer to
     ``.price`` will return the
     ``func.sum(UnitPrice.price).label('price')`` column, as it is
     matched on the name "price".  Ordinarily, the "price" function
     wouldn't have any "column correspondence" to the actual
     ``UnitPrice.price`` column as it is not a proxy of the original.

     .. versionadded:: 0.7.3

    """
    if isinstance(element, expression.FromClause):
        if adapt_on_names:
            raise sa_exc.ArgumentError(
                "adapt_on_names only applies to ORM elements"
            )
        return element.alias(name, flat=flat)
    else:
        return AliasedClass(element, alias=alias, flat=flat,
                            name=name, adapt_on_names=adapt_on_names)

def with_polymorphic(base, classes, selectable=False,
                     flat=False,
                     polymorphic_on=None, aliased=False,
                     innerjoin=False, _use_mapper_path=False,
                     _existing_alias=None):
    """Produce an :class:`.AliasedClass` construct which specifies
    columns for descendant mappers of the given base.

    Using this method will ensure that each descendant mapper's
    tables are included in the FROM clause, and will allow filter()
    criterion to be used against those tables.  The resulting
    instances will also have those columns already loaded so that
    no "post fetch" of those columns will be required.

    .. seealso::

        :ref:`with_polymorphic` - full discussion of
        :func:`.orm.with_polymorphic`.

    :param base: Base class to be aliased.

    :param classes: a single class or mapper, or list of
        class/mappers, which inherit from the base class.
        Alternatively, it may also be the string ``'*'``, in which case
        all descending mapped classes will be added to the FROM clause.

    :param aliased: when True, the selectable will be wrapped in an
        alias, that is ``(SELECT * FROM <fromclauses>) AS anon_1``.
        This can be important when using the with_polymorphic()
        to create the target of a JOIN on a backend that does not
        support parenthesized joins, such as SQLite and older
        versions of MySQL.

    :param flat: Boolean, will be passed through to the
     :meth:`.FromClause.alias` call so that aliases of :class:`.Join`
     objects don't include an enclosing SELECT.  This can lead to more
     efficient queries in many circumstances.  A JOIN against a nested JOIN
     will be rewritten as a JOIN against an aliased SELECT subquery on
     backends that don't support this syntax.

     Setting ``flat`` to ``True`` implies the ``aliased`` flag is
     also ``True``.

     .. versionadded:: 0.9.0

     .. seealso:: :meth:`.Join.alias`

    :param selectable: a table or select() statement that will
        be used in place of the generated FROM clause. This argument is
        required if any of the desired classes use concrete table
        inheritance, since SQLAlchemy currently cannot generate UNIONs
        among tables automatically. If used, the ``selectable`` argument
        must represent the full set of tables and columns mapped by every
        mapped class. Otherwise, the unaccounted mapped columns will
        result in their table being appended directly to the FROM clause
        which will usually lead to incorrect results.

    :param polymorphic_on: a column to be used as the "discriminator"
        column for the given selectable. If not given, the polymorphic_on
        attribute of the base classes' mapper will be used, if any. This
        is useful for mappings that don't have polymorphic loading
        behavior by default.

    :param innerjoin: if True, an INNER JOIN will be used.  This should
       only be specified if querying for one specific subtype only
    """
    primary_mapper = _class_to_mapper(base)
    if _existing_alias:
        assert _existing_alias.mapper is primary_mapper
        classes = util.to_set(classes)
        new_classes = set([
            mp.class_ for mp in
            _existing_alias.with_polymorphic_mappers])
        if classes == new_classes:
            return _existing_alias
        else:
            classes = classes.union(new_classes)
    mappers, selectable = primary_mapper.\
        _with_polymorphic_args(classes, selectable,
                               innerjoin=innerjoin)
    if aliased or flat:
        selectable = selectable.alias(flat=flat)
    return AliasedClass(base,
                        selectable,
                        with_polymorphic_mappers=mappers,
                        with_polymorphic_discriminator=polymorphic_on,
                        use_mapper_path=_use_mapper_path)

def _orm_annotate(element, exclude=None):
    """Deep copy the given ClauseElement, annotating each element with the
    "_orm_adapt" flag.

    Elements within the exclude collection will be cloned but not annotated.

    """
    return sql_util._deep_annotate(element, {'_orm_adapt': True}, exclude)

def _orm_deannotate(element):
    """Remove annotations that link a column to a particular mapping.

    Note this doesn't affect "remote" and "foreign" annotations
    passed by the :func:`.orm.foreign` and :func:`.orm.remote`
    annotators.

    """

    return sql_util._deep_deannotate(element,
                                     values=("_orm_adapt", "parententity")
                                     )

def _orm_full_deannotate(element):
    return sql_util._deep_deannotate(element)

class _ORMJoin(expression.Join):
    """Extend Join to support ORM constructs as input."""

    __visit_name__ = expression.Join.__visit_name__

    def __init__(
            self,
            left, right, onclause=None, isouter=False,
            full=False, _left_memo=None, _right_memo=None):

        left_info = inspection.inspect(left)
        left_orm_info = getattr(left, '_joined_from_info', left_info)

        right_info = inspection.inspect(right)
        adapt_to = right_info.selectable

        self._joined_from_info = right_info

        self._left_memo = _left_memo
        self._right_memo = _right_memo

        if isinstance(onclause, util.string_types):
            onclause = getattr(left_orm_info.entity, onclause)

        if isinstance(onclause, attributes.QueryableAttribute):
            on_selectable = onclause.comparator._source_selectable()
            prop = onclause.property
        elif isinstance(onclause, MapperProperty):
            prop = onclause
            on_selectable = prop.parent.selectable
        else:
            prop = None

        if prop:
            if sql_util.clause_is_present(
                    on_selectable, left_info.selectable):
                adapt_from = on_selectable
            else:
                adapt_from = left_info.selectable

            pj, sj, source, dest, \
                secondary, target_adapter = prop._create_joins(
                    source_selectable=adapt_from,
                    dest_selectable=adapt_to,
                    source_polymorphic=True,
                    dest_polymorphic=True,
                    of_type=right_info.mapper)

            if sj is not None:
                if isouter:
                    # note this is an inner join from secondary->right
                    right = sql.join(secondary, right, sj)
                    onclause = pj
                else:
                    left = sql.join(left, secondary, pj, isouter)
                    onclause = sj
            else:
                onclause = pj
            self._target_adapter = target_adapter

        expression.Join.__init__(self, left, right, onclause, isouter, full)

        if not prop and getattr(right_info, 'mapper', None) \
                and right_info.mapper.single:
            # if single inheritance target and we are using a manual
            # or implicit ON clause, augment it the same way we'd augment the
            # WHERE.
            single_crit = right_info.mapper._single_table_criterion
            if single_crit is not None:
                if right_info.is_aliased_class:
                    single_crit = right_info._adapter.traverse(single_crit)
                self.onclause = self.onclause & single_crit

    def _splice_into_center(self, other):
        """Splice a join into the center.

        Given join(a, b) and join(b, c), return join(a, b).join(c)

        """
        leftmost = other
        while isinstance(leftmost, sql.Join):
            leftmost = leftmost.left

        assert self.right is leftmost

        left = _ORMJoin(
            self.left, other.left,
            self.onclause, isouter=self.isouter,
            _left_memo=self._left_memo,
            _right_memo=other._left_memo
        )

        return _ORMJoin(
            left,
            other.right,
            other.onclause, isouter=other.isouter,
            _right_memo=other._right_memo
        )

    def join(
            self, right, onclause=None,
            isouter=False, full=False, join_to_left=None):
        return _ORMJoin(self, right, onclause, full, isouter)

    def outerjoin(
            self, right, onclause=None,
            full=False, join_to_left=None):
        return _ORMJoin(self, right, onclause, True, full=full)

def join(
        left, right, onclause=None, isouter=False,
        full=False, join_to_left=None):
    r"""Produce an inner join between left and right clauses.

    :func:`.orm.join` is an extension to the core join interface
    provided by :func:`.sql.expression.join()`, where the
    left and right selectables may be not only core selectable
    objects such as :class:`.Table`, but also mapped classes or
    :class:`.AliasedClass` instances.   The "on" clause can
    be a SQL expression, or an attribute or string name
    referencing a configured :func:`.relationship`.

    :func:`.orm.join` is not commonly needed in modern usage,
    as its functionality is encapsulated within that of the
    :meth:`.Query.join` method, which features a
    significant amount of automation beyond :func:`.orm.join`
    by itself.  Explicit usage of :func:`.orm.join`
    with :class:`.Query` involves usage of the
    :meth:`.Query.select_from` method, as in::

        from sqlalchemy.orm import join
        session.query(User).\
            select_from(join(User, Address, User.addresses)).\
            filter(Address.email_address=='foo@bar.com')

    In modern SQLAlchemy the above join can be written more
    succinctly as::

        session.query(User).\
                join(User.addresses).\
                filter(Address.email_address=='foo@bar.com')

    See :meth:`.Query.join` for information on modern usage
    of ORM level joins.

    .. versionchanged:: 0.8.1 - the ``join_to_left`` parameter
       is no longer used, and is deprecated.

    """
    return _ORMJoin(left, right, onclause, isouter, full)

def outerjoin(left, right, onclause=None, full=False, join_to_left=None):
    """Produce a left outer join between left and right clauses.

    This is the "outer join" version of the :func:`.orm.join` function,
    featuring the same behavior except that an OUTER JOIN is generated.
    See that function's documentation for other usage details.

    """
    return _ORMJoin(left, right, onclause, True, full)

def with_parent(instance, prop):
    """Create filtering criterion that relates this query's primary entity
    to the given related instance, using established :func:`.relationship()`
    configuration.

    The SQL rendered is the same as that rendered when a lazy loader
    would fire off from the given parent on that attribute, meaning
    that the appropriate state is taken from the parent object in
    Python without the need to render joins to the parent table
    in the rendered statement.

    .. versionchanged:: 0.6.4
        This method accepts parent instances in all
        persistence states, including transient, persistent, and detached.
        Only the requisite primary key/foreign key attributes need to
        be populated.  Previous versions didn't work with transient
        instances.

    :param instance:
      An instance which has some :func:`.relationship`.

    :param property:
      String property name, or class-bound attribute, which indicates
      what relationship from the instance should be used to reconcile the
      parent/child relationship.

    """
    if isinstance(prop, util.string_types):
        mapper = object_mapper(instance)
        prop = getattr(mapper.class_, prop).property
    elif isinstance(prop, attributes.QueryableAttribute):
        prop = prop.property

    return prop._with_parent(instance)

def has_identity(object):
    """Return True if the given object has a database
    identity.

    This typically corresponds to the object being
    in either the persistent or detached state.

    .. seealso::

        :func:`.was_deleted`

    """
    state = attributes.instance_state(object)
    return state.has_identity

def was_deleted(object):
    """Return True if the given object was deleted
    within a session flush.

    This is regardless of whether or not the object is
    persistent or detached.

    .. versionadded:: 0.8.0

    .. seealso::

        :attr:`.InstanceState.was_deleted`

    """

    state = attributes.instance_state(object)
    return state.was_deleted

def randomize_unitofwork():
    """Use random-ordering sets within the unit of work in order
    to detect unit of work sorting issues.

    This is a utility function that can be used to help reproduce
    inconsistent unit of work sorting issues.   For example,
    if two kinds of objects A and B are being inserted, and
    B has a foreign key reference to A - the A must be inserted first.
    However, if there is no relationship between A and B, the unit of work
    won't know to perform this sorting, and an operation may or may not
    fail, depending on how the ordering works out.   Since Python sets
    and dictionaries have non-deterministic ordering, such an issue may
    occur on some runs and not on others, and in practice it tends to
    have a great dependence on the state of the interpreter.  This leads
    to so-called "heisenbugs" where changing entirely irrelevant aspects
    of the test program still cause the failure behavior to change.

    By calling ``randomize_unitofwork()`` when a script first runs, the
    ordering of a key series of sets within the unit of work implementation
    are randomized, so that the script can be minimized down to the
    fundamental mapping and operation that's failing, while still reproducing
    the issue on at least some runs.

    This utility is also available when running the test suite via the
    ``--reversetop`` flag.

    .. versionadded:: 0.8.1 created a standalone version of the
       ``--reversetop`` feature.

    """
    from sqlalchemy.orm import unitofwork, session, mapper, dependency
    from sqlalchemy.util import topological
    from sqlalchemy.testing.util import RandomSet
    topological.set = unitofwork.set = session.set = mapper.set = \
        dependency.set = RandomSet


text:
<?php
namespace Icecave\Pasta\AST\Func;

use Icecave\Pasta\AST\Identifier;

abstract class NamedFunction extends FunctionBase
{
    public function __construct(Identifier $name)
    {
        $this->name = $name;
    }

    public function name()
    {
        return $this->name;
    }

    public function setName(Identifier $name)
    {
        $this->name = $name;
    }

    private $name;
}


text:
#ifndef VICE_PLUS4MEMLIMIT_H
#define VICE_PLUS4MEMLIMIT_H

extern void mem_limit_init(int mem_read_limit_tab[2][0x101]);

#endif


text:
The sample source codes on this page will demonstrate you how to make PDF to image API in PowerShell. PDF to image API in PowerShell can be implemented with PDF.co Web API. PDF.co Web API is the Web API with a set of tools for documents manipulation, data conversion, data extraction, splitting and merging of documents. Includes image recognition, built-in OCR, barcode generation and barcode decoders to decode bar codes from scans, pictures and pdf.

You will save a lot of time on writing and testing code as you may just take the code below and use it in your application. This PowerShell sample code should be copied and pasted into your project. After doing this just compile your project and click Run. This basic programming language sample code for PowerShell will do the whole work for you in implementing PDF to image API in your app.

Trial version of ByteScout is available for free download from our website. This and other source code samples for PowerShell and other programming languages are available.

## REQUEST FREE TECH SUPPORT

[Click here to get in touch](https://bytescout.zendesk.com/hc/en-us/requests/new?subject=PDF.co%20Web%20API%20Question)

or just send email to [support@bytescout.com](mailto:support@bytescout.com?subject=PDF.co%20Web%20API%20Question)

## ON-PREMISE OFFLINE SDK

[Get Your 60 Day Free Trial](https://bytescout.com/download/web-installer?utm_source=github-readme)
[Explore Documentation](https://bytescout.com/documentation/index.html?utm_source=github-readme)
[Explore Source Code Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/)
[Sign Up For Online Training](https://academy.bytescout.com/)

## ON-DEMAND REST WEB API

[Get your API key](https://app.pdf.co/signup?utm_source=github-readme)
[Security](https://pdf.co/security)
[Explore Web API Documentation](https://apidocs.pdf.co?utm_source=github-readme)
[Explore Web API Samples](https://github.com/bytescout/ByteScout-SDK-SourceCode/tree/master/PDF.co%20Web%20API)

## VIDEO REVIEW

[https://www.youtube.com/watch?v=NEwNs2b9YN8](https://www.youtube.com/watch?v=NEwNs2b9YN8)

<!-- code block begin -->

##### **ConvertPdfToTiffFromUploadedFile.ps1:**

```
# The authentication key (API Key).
# Get your own by registering at https://app.pdf.co
$API_KEY = "***********************************"

# Source PDF file
$SourceFile = ".\sample.pdf"
# Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'.
$Pages = ""
# PDF document password. Leave empty for unprotected documents.
$Password = ""
# Destination TIFF file name
$DestinationFile = ".\result.tif"

# 1. RETRIEVE THE PRESIGNED URL TO UPLOAD THE FILE.
# * If you already have a direct file URL, skip to the step 3.

# Prepare URL for `Get Presigned URL` API call
$query = "https://api.pdf.co/v1/file/upload/get-presigned-url?contenttype=application/octet-stream&name=" + `
    [System.IO.Path]::GetFileName($SourceFile)
$query = [System.Uri]::EscapeUriString($query)

try {
    # Execute request
    $jsonResponse = Invoke-RestMethod -Method Get -Headers @{ "x-api-key" = $API_KEY } -Uri $query

    if ($jsonResponse.error -eq $false) {
        # Get URL to use for the file upload
        $uploadUrl = $jsonResponse.presignedUrl
        # Get URL of uploaded file to use with later API calls
        $uploadedFileUrl = $jsonResponse.url

        # 2. UPLOAD THE FILE TO CLOUD.

        $r = Invoke-WebRequest -Method Put -Headers @{ "x-api-key" = $API_KEY; "content-type" = "application/octet-stream" } -InFile $SourceFile -Uri $uploadUrl

        if ($r.StatusCode -eq 200) {

            # 3. CONVERT UPLOADED PDF FILE TO TIFF

            # Prepare URL for `PDF To TIFF` API call
            $query = "https://api.pdf.co/v1/pdf/convert/to/tiff"

            # Prepare request body (will be auto-converted to JSON by Invoke-RestMethod)
            # See documentation: https://apidocs.pdf.co
            $body = @{
                "name" = $(Split-Path $DestinationFile -Leaf)
                "password" = $Password
                "pages" = $Pages
                "url" = $uploadedFileUrl
            } | ConvertTo-Json

            # Execute request
            $response = Invoke-WebRequest -Method Post -Headers @{ "x-api-key" = $API_KEY; "Content-Type" = "application/json" } -Body $body -Uri $query

            $jsonResponse = $response.Content | ConvertFrom-Json

            if ($jsonResponse.error -eq $false) {
                # Get URL of generated TIFF file
                $resultFileUrl = $jsonResponse.url;

                # Download TIFF file
                Invoke-WebRequest -Headers @{ "x-api-key" = $API_KEY } -OutFile $DestinationFile -Uri $resultFileUrl

                Write-Host "Generated TIFF file saved as `"$($DestinationFile)`" file."
            }
            else {
                # Display service reported error
                Write-Host $jsonResponse.message
            }
        }
        else {
            # Display request error status
            Write-Host $r.StatusCode + " " + $r.StatusDescription
        }
    }
    else {
        # Display service reported error
        Write-Host $jsonResponse.message
    }
}
catch {
    # Display request error
    Write-Host $_.Exception
}

```

<!-- code block end -->

<!-- code block begin -->

##### **run.bat:**

```
@echo off

powershell -NoProfile -ExecutionPolicy Bypass -Command "& .\ConvertPdfToTiffFromUploadedFile.ps1"
echo Script finished with errorlevel=%errorlevel%

pause
```

<!-- code block end -->


text:
package com.google.android.agera;

import android.support.annotation.NonNull;

/**
 * Receives events of the {@link UpdateDispatcher} created with
 * {@link Observables#updateDispatcher(ActivationHandler)} when the first {@link Updatable} is
 * added
 * and the last {@link Updatable} is removed.
 *
 *
Typically an {@link Observable} service implemented using a {@link UpdateDispatcher} only
 * needs to be updated if it has clients of its own. By starting to listen to updates from its
 * clients on {@link #observableActivated} and stopping on {@link #observableDeactivated}, the
 * service of the service can implement an active/inactive lifecycle,
 * saving memory and execution time when not needed.
 *
 * Agera 中抽象出来的 激活处理 接口
 * 用于 执行 被观察者 的 激活 和 释放 功能
 * 这里的 被观察者 是 UpdateDispatcher
 * 因为 UpdateDispatcher 继承了 被观察者( Observable )接口 和 观察者( Updatable )接口
 */
public interface ActivationHandler {

    /**
     * Called when the the {@code caller} changes state from having no {@link Updatable}s to
     * having at least one {@link Updatable}.
     *
     * 被观察者 被 激活时
     */
    void observableActivated(@NonNull UpdateDispatcher caller);

    /**
     * Called when the the {@code caller} changes state from having {@link Updatable}s to
     * no longer having {@link Updatable}s.
     *
     * 被观察者 被 释放时
     */
    void observableDeactivated(@NonNull UpdateDispatcher caller);
}


text:
package id.web.edom.io;

import id.web.edom.Threaded;
import id.web.edom.rmi.Log;

import java.io.EOFException;
import java.io.IOException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;

/**
 *
Selects multiple {@link SelectableChannel}s
 * using exactly one {@link Selector}
 * and one {@linkplain Thread thread}.

 *
 *
Kills connections that are idle for too long.

 *
 *
Uses only one thread and that thread is
 * not the thread used to call the constructor.

 *
 *
Also gathers some statistics.

 *
 * @author erik
 */
public class Hub implements Threaded
{

    private static final Logger lt = Log.getTransput();
    private static final Logger ls = Log.getSelector();

    /**
     *
The hub expects one instance of this class to be
     * {@linkplain SelectionKey#attachment() attached}
     * to one selection key in the hub.

     *
     *
All methods here should return quickly
     * since they run in the thread that is used by the hub
     * to {@linkplain Selector#select() select}.
     * Blocking this thread will hang the entire hub.

     *
     *
Throwing an exception will close the associated channel.

     *
     * @author erik
     */
    public static class Listener
    {
        // Does this long really need to be atomic?
        // It is used in only one thread, isn't it?
        /**
         *
The time of last access as returned by {@link System#currentTimeMillis()}.

         */
        private final AtomicLong last = new AtomicLong(System.currentTimeMillis());
        /**
         *
Updates the time of last access.

         */
        private final void touch () { last.set(System.currentTimeMillis()); }
        /**
         *
Gets the time of last access.
         *
         * @return the time of last access
         */
        private final long getLastAccess () { return last.get(); }
        /**
         *
If this method returns true,
         * the hub will close the channel
         * if the channel is idle for too long.

         *
         * @return whether the channel is subject to idle timeout
         */
        public boolean canTimeOut () { return true; }
        /**
         *
The default implementation closes the channel.

         *
         * @param channel the channel
         *
         * @throws Exception if there is an error
         */
        public void terminate (SelectableChannel channel) throws Exception
        {
            Log.close(channel);
            channel.close();
        }
        /**
         *
         * @param in
         * @return the number of bytes read
         * @throws Exception
         */
        public int read (ReadableByteChannel in) throws Exception { return 0; }
        /**
         *
         * @param out
         * @return the number of bytes actually written
         * @throws Exception
         */
        public int write (WritableByteChannel out) throws Exception { return 0; }
        public void accept (ServerSocketChannel channel) throws Exception {}
        public void connect (SocketChannel channel) throws Exception {}
    }

    /**
     *
Milliseconds.

     */
    private final long maxIdleDuration = 5 * 60 * 1000;

    /**
     *
The soonest time to kill idle connections.

     */
    private long nextIdleCheck = System.currentTimeMillis();

    /**
     *
Set this flag to true to signal the {@link #thread} to stop
     * as soon as it reads this flag.

     */
    private final AtomicBoolean shutdown = new AtomicBoolean();
    private final AtomicLong lifetimeConnections = new AtomicLong();
    private final AtomicLong connectionsAccepted = new AtomicLong();
    private final AtomicLong bytesRead = new AtomicLong();
    private final AtomicLong bytesWritten = new AtomicLong();
    private final Object lock = new Object();
    private final Selector selector;
    private final Thread thread;

    private Hub () throws Exception
    {
        lt.info("Starting {}.", this);
        this.selector = Selector.open();
        this.thread = new Thread ()
        {
            @Override
            public void run ()
            {
                Hub.this.run();
            }
        };
    }

    /**
     *
Worker thread loop.

     */
    private void run ()
    {
        try
        {
            lt.info("{} started.", this);
            for (;;)
            {
                if (shutdown.get()) { break; }
                final long now = System.currentTimeMillis();
                final long duration = nextIdleCheck - now;
                if (duration <= 0)
                {
                    killIdleChannels();
                    continue;
                }
                synchronized (lock) {}
                selector.select(duration);
                dispatchSelectedChannels();
            }
        }
        catch (Exception e)
        {
            lt.error("Unhandled exception in hub loop.", e);
        }
        finally
        {
            lt.info("Stopping {}.", this);
            for (SelectionKey k : selector.keys())
            {
                if (!k.isValid()) { continue; } // key is already cancelled
                cancel(k);
            }
            try
            {
                selector.close();
            }
            catch (Exception e)
            {
                lt.error("Exception while closing selector.", e);
            }
            lt.info("{} stopped.", this);
        }
    }
    /**
     *
Kills all connections that have been idle
     * for more than {@link #maxIdleDuration} milliseconds.

     */
    private void killIdleChannels ()
    {
        final long now = System.currentTimeMillis();
        long minLastAccess = now;
        synchronized (lock)
        {
            for (SelectionKey key : selector.keys())
            {
                final Listener l = (Listener) key.attachment();
                if (!l.canTimeOut()) { continue; }
                final long lastAccess = l.getLastAccess();
                final long idleTime = now - lastAccess;
                if (idleTime >= maxIdleDuration)
                {
                    Log.timeout(key.channel());
                    cancel(key);
                    continue;
                }
                if (lastAccess < minLastAccess)
                {
                    minLastAccess = lastAccess;
                }
            }
        }
        nextIdleCheck = minLastAccess + maxIdleDuration;
    }

    /**
     *
Dispatch events to listeners of selected channels.

     */
    private void dispatchSelectedChannels ()
    {
        final Set<SelectionKey> selectedKeys = selector.selectedKeys();
        if (ls.isTraceEnabled())
        {
            final int n = selectedKeys.size();
            if (n > 0)
            {
                ls.trace("Selected {} keys.", n);
            }
        }
        for (SelectionKey key : selectedKeys)
        {
            try
            {
                if (ls.isTraceEnabled())
                {
                    ls.trace("{} readyOps:{}.", key, key.readyOps());
                }
                final Listener l = (Listener) key.attachment();
                final SelectableChannel c = key.channel();
                l.touch();
                if (key.isReadable())
                {
                    final int n = l.read((ReadableByteChannel) c);
                    bytesRead.addAndGet(n);
                }
                if (key.isWritable())
                {
                    final int n = l.write((WritableByteChannel) c);
                    bytesWritten.addAndGet(n);
                }
                if (key.isAcceptable())
                {
                    lifetimeConnections.incrementAndGet();
                    l.accept((ServerSocketChannel) c);
                    connectionsAccepted.incrementAndGet();
                }
                if (key.isConnectable())
                {
                    l.connect((SocketChannel) c);
                }
            }
            catch (EOFException e)
            {
                lt.info("{} closed by peer.", key.channel());
                cancel(key);
            }
            catch (Exception e)
            {
                lt.error("Exception while dispatching events in selected channel.", e);
                cancel(key);
            }
        }
        selectedKeys.clear();
    }

    /**
     *
This method is safe to call at any time from any thread.
     * Calls {@link Listener#terminate(SelectableChannel)}.

     *
     * @param key the key to cancel
     *
     * @return this
     */
    public Hub cancel (SelectionKey key)
    {
        try
        {
            final Listener l = (Listener) key.attachment();
            final SelectableChannel c = key.channel();
            l.terminate(c);
        }
        catch (Exception e)
        {
            lt.warn("Exception while cancelling key " + key + ".", e);
        }
        finally
        {
            key.cancel();
        }
        return this;
    }

    /**
     *
Registers the channel for use with the selector in this hub.

     *
     * @param channel channel
     * @param operations operations
     * @param listener listener
     *
     * @return the selection key
     *
     * @throws IOException if there is a transput error
     *
     * @see {@link SelectableChannel#register(Selector, int, Object)}
     */
    public SelectionKey register (SelectableChannel channel, int operations, Listener listener) throws IOException
    {
        if (shutdown.get()) { throw new IllegalStateException(); }
        if (ls.isDebugEnabled())
        {
            ls.debug("Registering {} interestOps:{}.", channel, operations);
        }
        final SelectionKey key;
        synchronized (lock)
        {
            selector.wakeup();
            channel.configureBlocking(false);
            key = channel.register(selector, operations, listener);
        }
        return key;
    }

    public Hub stop ()
    {
        shutdown.set(true);
        selector.wakeup();
        return this;
    }

    public Hub join () throws InterruptedException
    {
        thread.join();
        return this;
    }

    public void setInterestOps (SelectionKey key, int newOps)
    {
        if (ls.isTraceEnabled())
        {
            final int oldOps = key.interestOps();
            if (oldOps != newOps)
            {
                ls.trace("{} interestOps:{}->{}.", key, oldOps, newOps);
            }
        }
        synchronized (lock)
        {
            selector.wakeup();
            key.interestOps(newOps);
        }
    }

    private static final AtomicLong serial = new AtomicLong();

    public static Hub create () throws Exception
    {
        final Hub m = new Hub();
        m.thread.setName("hub-" + serial.getAndIncrement());
        m.thread.start();
        return m;
    }

    public long getLifetimeConnections () { return lifetimeConnections.get(); }
    public long getConnectionsAccepted () { return connectionsAccepted.get(); }
    public long getBytesRead () { return bytesRead.get(); }
    public long getBytesWritten () { return bytesWritten.get(); }
}


text:
package think.rpgitems.power.impl;

import com.meowj.langutils.lang.convert.EnumEnchantment;
import com.meowj.langutils.lang.convert.EnumEnchantmentLevel;
import org.bukkit.NamespacedKey;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import think.rpgitems.I18n;
import think.rpgitems.power.PowerHit;
import think.rpgitems.power.PowerMeta;
import think.rpgitems.power.PowerResult;
import think.rpgitems.power.Property;

import java.util.concurrent.ThreadLocalRandom;

import static think.rpgitems.power.Utils.getAngleBetweenVectors;

@PowerMeta(immutableTrigger = true)
public class PowerEnchantedHit extends BasePower implements PowerHit {

    @Property
    public Mode mode = Mode.ADDITION;

    @Property
    public double amountPerLevel = 1;

    @Property
    public String display;

    @Property
    public EnumEnchantment enchantmentType = EnumEnchantment.ARROW_DAMAGE;

    @Property
    public boolean setBaseDamage = false;

    @Override
    public PowerResult<Double> hit(Player player, ItemStack stack, LivingEntity entity, double damage, EntityDamageByEntityEvent event) {
        int enchLevel = stack.getEnchantmentLevel(enchantmentType.getEnchantment());
        if (mode == Mode.ADDITION) {
            damage += (enchLevel * amountPerLevel);
        }
        if (mode == Mode.MULTIPLICATION) {
            damage *= Math.pow(amountPerLevel, enchLevel);
        }
        if (damage < 0 ) damage = 0;
        if (setBaseDamage) {
            event.setDamage(damage);
        }
        return PowerResult.ok(damage);
    }

    private enum Mode {
        ADDITION,
        MULTIPLICATION,
        ;
    }

    @Override
    public String getName() {
        return "enchantedhit";
    }

    @Override
    public String displayText() {
        return display;
    }

}


text:
package com.splunk.javaagent.hprof;

import com.splunk.javaagent.SplunkLogEvent;

public class StartThreadRecord extends HprofRecord {

	private int threadSerial;
	private int stackTraceSerial;
	private HprofIDField threadObjectID;
	private HprofIDField threadNameID;
	private HprofIDField threadGroupNameID;
	private HprofIDField threadGroupParentID;

	@Override
	public void parseRecord() {

		this.threadSerial = buf.getInt();
		this.threadObjectID = readId();
		this.stackTraceSerial = buf.getInt();
		this.threadNameID = readId();
		this.threadGroupNameID = readId();
		this.threadGroupParentID = readId();

	}

	@Override
	public SplunkLogEvent getSplunkLogEvent() {
		SplunkLogEvent event = new SplunkLogEvent("hprof_startthread",
				"splunkagent", false, false);
		addCommonSplunkLogEventFields(event);
		event.addPair("threadSerial", this.threadSerial);
		event.addPair("threadObjectID", this.threadObjectID.toString());
		event.addPair("stackTraceSerial", this.stackTraceSerial);
		event.addPair("threadNameID", this.threadNameID.toString());
		event.addPair("threadGroupNameID", this.threadGroupNameID.toString());
		event.addPair("threadGroupParentID",
				this.threadGroupParentID.toString());

		return event;
	}

}