text:
<?php

namespace JosekiTests\LeanMapperExtension;

use Joseki\LeanMapper\Mapper;
use Tester\Assert;
use Tester\TestCase;

$container = require __DIR__ . '/../bootstrap.php';

class MapperMock extends Mapper
{

    /** @var string */
    protected $defaultEntityNamespace = 'JosekiTests\LeanMapperExtension\Tables';

}

class MapperTest extends TestCase
{
    /** @var  MapperMock */
    private $mapper;

    function setUp()
    {
        $this->mapper = new MapperMock(['Special', 'camelCase']);
    }

    function testGetTable()
    {
        Assert::same('user', $this->mapper->getTable('JosekiTests\\LeanMapperExtension\\Tables\\User'));
        Assert::same('user', $this->mapper->getTable('\\JosekiTests\\LeanMapperExtension\\Tables\\User'));
    }

    function testGetEntityClass()
    {
        Assert::same('JosekiTests\\LeanMapperExtension\\Tables\\User', $this->mapper->getEntityClass('user'));
    }

    function testGetTableByRepositoryClass()
    {
        Assert::same('user', $this->mapper->getTableByRepositoryClass('JosekiTests\\LeanMapperExtension\\Tables\\UserRepository'));
        Assert::same('user', $this->mapper->getTableByRepositoryClass('JosekiTests\\LeanMapperExtension\\Tables\\UserRepository'));
    }

    function testGetColumn()
    {
        Assert::same('pub_date', $this->mapper->getColumn('JosekiTests\\LeanMapperExtension\\Tables\\Book', 'pubDate'));
        Assert::same('author', $this->mapper->getColumn('JosekiTests\\LeanMapperExtension\\Tables\\Special\\Book', 'author'));
    }

    function testGetEntityField()
    {
        Assert::same('id', $this->mapper->getEntityField('user', 'id'));
        Assert::same('address', $this->mapper->getEntityField('user', 'myaddress'));
        Assert::same('firstName', $this->mapper->getEntityField('user', 'my_name'));
    }

    function testGetRelationshipColumn()
    {

    }
}

run(new MapperTest($container));


text:
package com.twitter.finagle.thrift.transport

import com.twitter.finagle.filter.PayloadSizeFilter
import com.twitter.finagle._
import com.twitter.finagle.thrift._
import com.twitter.finagle.thrift.thrift.ConnectionOptions
import com.twitter.util.{Future, Stopwatch}
import org.apache.thrift.protocol.{TBinaryProtocol, TMessage, TMessageType, TProtocolFactory}
import org.apache.thrift.transport.TMemoryInputTransport

/**
 * A class to prepare a client. It adds a payload size filter and a
 * connection validation filter. If requested, it will also prepare
 * clients for upgrade: it attempts to send a probe message to upgrade
 * the protocol to TTwitter. If this succeeds, the TTwitter filter is
 * added.
 */
private[finagle] case class ThriftClientPreparer(
  protocolFactory: TProtocolFactory,
  serviceName: String = "unknown",
  clientId: Option[ClientId] = None,
  useCallerSeqIds: Boolean = false) {

  private def prepareService(params: Stack.Params)(
    service: Service[ThriftClientRequest, Array[Byte]]
  ): Future[Service[ThriftClientRequest, Array[Byte]]] = {
    val payloadSize = new PayloadSizeFilter[ThriftClientRequest, Array[Byte]](
      params[param.Stats].statsReceiver, _.message.length, _.length
    )
    val Thrift.param.AttemptTTwitterUpgrade(attemptUpgrade) =
      params[Thrift.param.AttemptTTwitterUpgrade]
    val payloadSizeService = payloadSize.andThen(service)
    val upgradedService =
      if (attemptUpgrade) {
        upgrade(payloadSizeService)
      } else {
        Future.value(payloadSizeService)
      }

    upgradedService.map { upgraded =>
      new ValidateThriftService(upgraded, protocolFactory)
    }
  }

  def prepare(
    underlying: ServiceFactory[ThriftClientRequest, Array[Byte]],
    params: Stack.Params
  ): ServiceFactory[ThriftClientRequest, Array[Byte]] = {
    val param.Stats(stats) = params[param.Stats]
    val Thrift.param.AttemptTTwitterUpgrade(attemptUpgrade) =
      params[Thrift.param.AttemptTTwitterUpgrade]
    val preparingFactory = underlying.flatMap(prepareService(params))

    if (attemptUpgrade) {
      new ServiceFactoryProxy(preparingFactory) {
        val stat = stats.stat("codec_connection_preparation_latency_ms")
        override def apply(conn: ClientConnection) = {
          val elapsed = Stopwatch.start()
          super.apply(conn).ensure {
            stat.add(elapsed().inMilliseconds)
          }
        }
      }
    } else {
      preparingFactory
    }
  }

  private def upgrade(
    service: Service[ThriftClientRequest, Array[Byte]]
  ): Future[Service[ThriftClientRequest, Array[Byte]]] = {
    // Attempt to upgrade the protocol the first time around by
    // sending a magic method invocation.
    val buffer = new OutputBuffer(protocolFactory)
    buffer().writeMessageBegin(
      new TMessage(ThriftTracing.CanTraceMethodName, TMessageType.CALL, 0))

    val options = new ConnectionOptions
    options.write(buffer())

    buffer().writeMessageEnd()

    service(new ThriftClientRequest(buffer.toArray, false)).map { bytes =>
      val memoryTransport = new TMemoryInputTransport(bytes)
      val iprot = protocolFactory.getProtocol(memoryTransport)
      val reply = iprot.readMessageBegin()

      val ttwitter = new TTwitterClientFilter(
        serviceName,
        reply.`type` != TMessageType.EXCEPTION,
        clientId, protocolFactory)
      // TODO: also apply this for Protocols.binaryFactory

      val seqIdFilter =
        if (protocolFactory.isInstanceOf[TBinaryProtocol.Factory] && !useCallerSeqIds)
          new SeqIdFilter
        else
          Filter.identity[ThriftClientRequest, Array[Byte]]

      seqIdFilter.andThen(ttwitter).andThen(service)
    }
  }
}

redpajama_set_name: RedPajamaGithub


text:
import semver from 'semver';

export default function semverDiff(versionA, versionB) {
	versionA = semver.parse(versionA);
	versionB = semver.parse(versionB);

	if (semver.compareBuild(versionA, versionB) >= 0) {
		return;
	}

	return semver.diff(versionA, versionB) || 'build';
}


text:
using System;
using System.IO;
using System.Linq;
using System.Xml;
using NUnit.Framework;
using Xcst.Compiler;

namespace Xcst.Tests.ProgramStructure.Packages.OverridingComponents.Variable;
using ModuleResolver = VariableTests.Overridden_Non_Compiled_Resolver;

partial class VariableTests {

   const string
   TestCategory = nameof(ProgramStructure) + "." + nameof(Packages) + "." + nameof(OverridingComponents) + "." + nameof(Variable);

   [Test]
   [Category(TestCategory)]
   public void
   Overridden_Non_Compiled() {

      var compilerA = TestsHelper.CreateCompiler();
      compilerA.TargetClass = "FooPackage";
      compilerA.TargetNamespace = typeof(VariableTests).Namespace;
      compilerA.PackageLocationResolver = name => new Uri("urn:x:" + name);
      compilerA.ModuleResolver = new ModuleResolver();

      var usingPackageUri = new Uri(@"c:\foo.xcst");

      var resultA = compilerA.Compile(
         new StringReader(ModuleResolver.GetPackageString("")),
         baseUri: usingPackageUri
      );

      var compilerB = TestsHelper.CreateCompiler();
      compilerB.PackageLocationResolver = compilerA.PackageLocationResolver;
      compilerB.ModuleResolver = compilerA.ModuleResolver;

      var resultB = compilerB.Compile(
         new StringReader(ModuleResolver.GetPackageString("localhost.PackageB")),
         baseUri: compilerB.PackageLocationResolver("localhost.PackageB")
      );

      var compilationUnits = resultB.CompilationUnits
         .Concat(resultA.CompilationUnits)
         .ToArray();

      TestsHelper.CompileCode(
         compilerA.TargetNamespace + "." + compilerA.TargetClass,
         usingPackageUri,
         compilationUnits,
         resultA.Language
      );
   }

   internal class Overridden_Non_Compiled_Resolver : XmlResolver {

      public static string
      GetPackageString(string name) {

         switch (name) {
            case "":
               return @"
<c:package version='1.0' language='C#' xmlns:c='http://maxtoroq.github.io/XCST'>
   <c:use-package name='localhost.PackageB'>
      <c:override>
         <c:variable name='foo' value='""bar""' as='string'/>
      </c:override>
   </c:use-package>
</c:package>
";
            case "localhost.PackageB":
               return @"
<c:package name='localhost.PackageB' version='1.0' language='C#' xmlns:c='http://maxtoroq.github.io/XCST'>
   <c:import-namespace ns='System'/>
   <c:variable name='foo' value='""foo""' as='String' visibility='public'/>
</c:package>
";
            default:
               throw new ArgumentException("Invalid name.", nameof(name));
         }
      }

      public override object
      GetEntity(Uri absoluteUri, string? role, System.Type? ofObjectToReturn) =>
         CreateStreamForString(GetPackageString(absoluteUri.AbsoluteUri.Substring("urn:x:".Length)));

      static Stream
      CreateStreamForString(string s) {

         var stream = new MemoryStream();
         var writer = new StreamWriter(stream);

         writer.Write(s);
         writer.Flush();

         stream.Position = 0;

         return stream;
      }
   }
}


text:
using System;
using Newtonsoft.Json;

namespace VaultSharp.V1.SystemBackend
{
    /// <summary>
    /// Lease info.
    /// </summary>
    public class Lease
    {
        /// <summary>
        /// Gets or sets the lease identifier.
        /// </summary>
        [JsonProperty("id")]
        public string Id { get; set; }

        /// <summary>
        /// Gets or sets the issue time.
        /// </summary>
        [JsonProperty("issue_time")]
        public DateTimeOffset IssueTime { get; set; }

        /// <summary>
        /// Gets or sets the expiry time.
        /// </summary>
        [JsonProperty("expire_time")]
        public DateTimeOffset ExpiryTime { get; set; }

        /// <summary>
        /// Gets or sets the last renewal time.
        /// </summary>
        [JsonProperty("last_renewal_time")]
        public DateTimeOffset? LastRenewalTime { get; set; }

        /// <summary>
        /// Gets or sets the flag indicating if this lease is renewable.
        /// </summary>
        [JsonProperty("renewable")]
        public bool Renewable { get; set; }

        /// <summary>
        /// Gets or sets the time to live for the lease.
        /// </summary>
        [JsonProperty("ttl", DefaultValueHandling = DefaultValueHandling.Ignore)]
        public int TimeToLive { get; set; }
    }
}


text:
@interface DFIUITableViewDelegateProxy : DFITableViewDelegateProxy

- (instancetype)initWithTableViewConfiguration:(id<DFITableViewConfigurationInternal>)tableViewConfiguration;

@end


text:
package com.netty5.chapter08.server;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import org.apache.commons.lang.StringUtils;

import com.netty5.chapter08.protobuf.SubscribeReqProto;
import com.netty5.chapter08.protobuf.SubscribeRespProto;

public class SubReqServerHandler extends ChannelHandlerAdapter{

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		SubscribeReqProto.SubscribeReq req = (SubscribeReqProto.SubscribeReq) msg;
		if(StringUtils.equals("cc", req.getUserName())) {
			System.out.println("Service accept client subscribe req : [" + req.toString() + "]");
			ctx.writeAndFlush(resp(req.getSubReqID()));
		}
	}

	private SubscribeRespProto.SubscribeResp resp(int subReqID) {
		SubscribeRespProto.SubscribeResp.Builder builder =
				SubscribeRespProto.SubscribeResp.newBuilder();
		builder.setSubReqID(subReqID);
		builder.setDesc("2222222");
		builder.setRespCode("0");
		return builder.build();
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		ctx.close();
	}

}


text:
import sys

LICENSE_STRING = 'licenses(["notice"])  # Apache 2\n'
ENVOY_PACKAGE_STRING = (
    'load("//bazel:envoy_build_system.bzl", "envoy_package")\n'
    '\n'
    'envoy_package()\n')

def FixBuild(path):
  with open(path, 'r') as f:
    outlines = [LICENSE_STRING]
    in_load = False
    seen_ebs = False
    seen_epkg = False
    for line in f:
      if line.startswith('package(') and not path.endswith(
          'bazel/BUILD') and not path.endswith(
          'ci/prebuilt/BUILD') and not path.endswith(
          'bazel/osx/BUILD') and not path.endswith('bazel/osx/crosstool/BUILD'):
        continue
      if in_load == False and line.startswith('load('):
        in_load = True
      if in_load:
        if 'envoy_build_system.bzl' in line:
          seen_ebs = True
        if 'envoy_package' in line:
          seen_epkg = True
        if line.rstrip().endswith(')'):
          in_load = None  # investigate only first load() directive
          if seen_ebs:
            if not seen_epkg:
              outlines.append(line.rstrip()[:-1] + ', "envoy_package")\n')
              outlines.append('\nenvoy_package()\n')
              continue
          else:
            outlines.append(line)
            outlines.append(ENVOY_PACKAGE_STRING)
            continue
      if not line.startswith('licenses'):
        outlines.append(line)

  return ''.join(outlines)

if __name__ == '__main__':
  if len(sys.argv) == 2:
    sys.stdout.write(FixBuild(sys.argv[1]))
    sys.exit(0)
  elif len(sys.argv) == 3:
    reorderd_source = FixBuild(sys.argv[1])
    with open(sys.argv[2], 'w') as f:
      f.write(reorderd_source)
    sys.exit(0)
  print 'Usage: %s <source file path> [<destination file path>]' % sys.argv[0]
  sys.exit(1)


text:
<?php

namespace Sylius\Bundle\CoreBundle\DataFixtures\ORM;

use Doctrine\Common\Persistence\ObjectManager;
use Sylius\Bundle\CoreBundle\DataFixtures\DataFixture;
use Sylius\Component\Currency\Model\CurrencyInterface;

/**
 * Default currency fixtures.
 *
 * @author Saša Stamenković <umpirsky@gmail.com>
 */
class LoadCurrencyData extends DataFixture
{
    const BASE_CURRENCY = 'EUR';

    /**
     * @var array
     */
    protected $currencies = [
        'EUR' => 1.00,
        'USD' => 1.30,
        'GBP' => 0.85,
    ];

    /**
     * {@inheritdoc}
     */
    public function load(ObjectManager $manager)
    {
        $currencyFactory = $this->getCurrencyFactory();

        foreach ($this->currencies as $code => $rate) {
            $currency = $currencyFactory->createNew();

            $currency->setCode($code);
            $currency->setExchangeRate($rate);
            $currency->setEnabled(true);
            if (self::BASE_CURRENCY === $code) {
                $currency->setBase(true);
            }

            $this->setReference('Sylius.Currency.'.$code, $currency);

            $manager->persist($currency);
        }

        $manager->flush();
    }

    /**
     * {@inheritdoc}
     */
    public function getOrder()
    {
        return 10;
    }
}


text:
<?php

namespace core;
use core\generic\DbDriver;
use core\generic\SingletonInterface;

/**
 * Class Database
 * @package core
 */
class DatabaseManager implements SingletonInterface
{
    /**
     * Array of DbDriver objects
     * @var array
     */
    private $connection_pool = [];

    /**
     * @var null|DbDriver
     */
    private $default_conn = null;

    /**
     * It is singleton
     */
    protected static $instance;
    private function __construct() {}
    private function __clone() {}

    /**
     * @return array
     */
    public function getConnectionPool()
    {
        return $this->connection_pool;
    }

    /**
     * @return DatabaseManager
     */
    public static function getInstance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Add DbDriver object to internal array
     * @param string $dsn
     * @param \core\generic\DbDriver $conn
     * @param bool $default
     */
    public function add($dsn, DbDriver $conn, $default = false)
    {
        $this->connection_pool[$dsn] = $conn;
        if ($default) {
            $this->default_conn = $conn;
        }
    }

    /**
     * Returns connection specified by $dsn from pull
     * @param string $dsn
     * @return \core\generic\DbDriver
     * @throws \InvalidArgumentException
     */
    public function getConn($dsn = '')
    {
        if ($dsn === '') {
            if ($this->default_conn === null) {
                if (count($this->connection_pool) == 1) {
                    reset($this->connection_pool);
                    return current($this->connection_pool);
                }
                throw new \InvalidArgumentException("Default connection not defined in config file");
            }
            return $this->default_conn;
        }
        if (!isset($this->connection_pool[$dsn])) {
            throw new \InvalidArgumentException("Invalid database $dsn");
        }
        return $this->connection_pool[$dsn];
    }
}


text:
order: 6
zh-CN:
	title: 禁用
	disabledProperty: 属性禁用
	disabledComponent: 兼容Disabled组件
en-US:
	title: Disabled
	disabledProperty: Property 'disabled'
	disabledComponent: Compatible with Disabled Component
---

```jsx
import { ColorPicker, Disabled } from 'zent';

class Simple extends React.Component {
	state = {
		color: '#5197FF',
	};

	handleChange = color => {
		this.setState({
			color,
		});
	};

	render() {
		const { color } = this.state;
		return (
			<div>
				<ColorPicker color={color} disabled />
				<div style={{ color, marginTop: 5 }}>{i18n.disabledProperty}</div>
				<br />
				<Disabled>
					<ColorPicker color={color} />
					<div className="color-picker-demo" />
					<ColorPicker color={color} disabled={false} />
				</Disabled>
				<div style={{ color, marginTop: 5 }}>{i18n.disabledComponent}</div>
			</div>
		);
	}
}

ReactDOM.render(<Simple />, mountNode);
```

<style>
.color-picker-demo {
	margin-bottom: 5px;
}
</style>


text:
package org.cometd.benchmark;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.eclipse.jetty.util.BlockingArrayQueue;
import org.eclipse.jetty.util.thread.QueuedThreadPool;

public class MonitoringQueuedThreadPool extends QueuedThreadPool {
    private final AtomicLong tasks = new AtomicLong();
    private final AtomicLong maxTaskLatency = new AtomicLong();
    private final AtomicLong totalTaskLatency = new AtomicLong();
    private final MonitoringBlockingArrayQueue queue;
    private final AtomicLong maxQueueLatency = new AtomicLong();
    private final AtomicLong totalQueueLatency = new AtomicLong();
    private final AtomicInteger threads = new AtomicInteger();
    private final AtomicInteger maxThreads = new AtomicInteger();

    public MonitoringQueuedThreadPool(int maxThreads) {
        // Use a very long idle timeout to avoid creation/destruction of threads
        super(maxThreads, maxThreads, 24 * 3600 * 1000, new MonitoringBlockingArrayQueue(maxThreads, 256));
        queue = (MonitoringBlockingArrayQueue)getQueue();
        setStopTimeout(2000);
    }

    @Override
    public void execute(Runnable job) {
        long begin = System.nanoTime();
        super.execute(newJob(job, begin));
    }

    @Override
    public boolean tryExecute(Runnable job) {
        long begin = System.nanoTime();
        return super.tryExecute(newJob(job, begin));
    }

    private Runnable newJob(Runnable job, long begin) {
        return new Runnable() {
            @Override
            public void run() {
                long queueLatency = System.nanoTime() - begin;
                tasks.incrementAndGet();
                Atomics.updateMax(maxQueueLatency, queueLatency);
                totalQueueLatency.addAndGet(queueLatency);
                Atomics.updateMax(maxThreads, threads.incrementAndGet());
                long start = System.nanoTime();
                try {
                    job.run();
                } finally {
                    long taskLatency = System.nanoTime() - start;
                    threads.decrementAndGet();
                    Atomics.updateMax(maxTaskLatency, taskLatency);
                    totalTaskLatency.addAndGet(taskLatency);
                }
            }

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

    public void reset() {
        tasks.set(0);
        maxTaskLatency.set(0);
        totalTaskLatency.set(0);
        queue.reset();
        maxQueueLatency.set(0);
        totalQueueLatency.set(0);
        threads.set(0);
        maxThreads.set(0);
    }

    public long getTasks() {
        return tasks.get();
    }

    public int getMaxActiveThreads() {
        return maxThreads.get();
    }

    public int getMaxQueueSize() {
        return queue.maxSize.get();
    }

    public long getAverageQueueLatency() {
        long count = tasks.get();
        return count == 0 ? -1 : totalQueueLatency.get() / count;
    }

    public long getMaxQueueLatency() {
        return maxQueueLatency.get();
    }

    public long getMaxTaskLatency() {
        return maxTaskLatency.get();
    }

    public long getAverageTaskLatency() {
        long count = tasks.get();
        return count == 0 ? -1 : totalTaskLatency.get() / count;
    }

    public static class MonitoringBlockingArrayQueue extends BlockingArrayQueue<Runnable> {
        private final AtomicInteger size = new AtomicInteger();
        private final AtomicInteger maxSize = new AtomicInteger();

        public MonitoringBlockingArrayQueue(int capacity, int growBy) {
            super(capacity, growBy);
        }

        public void reset() {
            size.set(0);
            maxSize.set(0);
        }

        @Override
        public void clear() {
            reset();
            super.clear();
        }

        @Override
        public boolean offer(Runnable job) {
            boolean added = super.offer(job);
            if (added) {
                increment();
            }
            return added;
        }

        private void increment() {
            Atomics.updateMax(maxSize, size.incrementAndGet());
        }

        @Override
        public Runnable poll() {
            Runnable job = super.poll();
            if (job != null) {
                decrement();
            }
            return job;
        }

        @Override
        public Runnable poll(long time, TimeUnit unit) throws InterruptedException {
            Runnable job = super.poll(time, unit);
            if (job != null) {
                decrement();
            }
            return job;
        }

        @Override
        public Runnable take() throws InterruptedException {
            Runnable job = super.take();
            decrement();
            return job;
        }

        private void decrement() {
            size.decrementAndGet();
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>ruler-compass-geometry: Error</title>
    <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
    <link href="../../../../../bootstrap.min.css" rel="stylesheet">
    <link href="../../../../../bootstrap-custom.css" rel="stylesheet">
    <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">

             Coq bench

clean / extra-dev

dev / ruler-compass-geometry - dev

            « Up

              ruler-compass-geometry

                dev
                Error

 (2019-11-30 21:22:11 UTC)

Context

# Packages matching: installed
# Name              # Installed # Synopsis
base-bigarray       base
base-threads        base
base-unix           base
conf-findutils      1           Virtual package relying on findutils
conf-m4             1           Virtual package relying on m4
coq                 dev         Formal proof management system
num                 1.3         The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml               4.09.0      The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.0      Official release 4.09.0
ocaml-config        1           OCaml Switch Configuration
ocamlfind           1.8.1       A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "dev@clarus.me"
homepage: "https://github.com/coq-contribs/ruler-compass-geometry"
license: "GNU Lesser Public License"
build: [
  ["coq_makefile" "-f" "Make" "-o" "Makefile"]
  [make "-j%{jobs}%"]
]
install: [make "install"]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/RulerCompassGeometry"]
depends: [
  "ocaml"
  "coq" {= "dev"}
]
tags: [ "keyword:geometry" "keyword:plane geometry" "keyword:ruler and compass geometry" "keyword:euclidean geometry" "keyword:hilbert's axioms" "category:Mathematics/Geometry/General" "date:2007-11" ]
authors: [ "Jean Duprat <Jean.Duprat@ens-lyon.fr>" ]
synopsis: "Ruler and compass geometry axiomatization."
description: """
This library contains an axiomatization of the ruler and
compass euclidian geometry. Files A1 to A6 contain the axioms and the
basic constructions. The other files build the proof that this
axiomatization induces the whole plane geometry except the continuity
axiom. For that the proofs of the Hilbert's axioms conclude this work in
the files E1 to E5."""
flags: light-uninstall
url {
  src:
    "git+https://github.com/coq-contribs/ruler-compass-geometry.git#master"
}

Lint

Command

true

Return code

0

Dry install

Dry install with the current Coq version:

Command

opam install -y --show-action coq-ruler-compass-geometry.dev coq.dev

Return code

0

Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:

Command

true

Return code

0

Install dependencies

Command

opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-ruler-compass-geometry.dev coq.dev

Return code

0

Duration

3 s

Install

Command

opam list; echo; ulimit -Sv 4000000; timeout 1h opam install -y coq-ruler-compass-geometry.dev coq.dev

Return code

7936

Duration

40 s

Output

# Packages matching: installed
# Name              # Installed # Synopsis
base-bigarray       base
base-threads        base
base-unix           base
conf-findutils      1           Virtual package relying on findutils
conf-m4             1           Virtual package relying on m4
coq                 dev         Formal proof management system
num                 1.3         The legacy Num library for arbitrary-precision integer and rational arithmetic
ocaml               4.09.0      The OCaml compiler (virtual package)
ocaml-base-compiler 4.09.0      Official release 4.09.0
ocaml-config        1           OCaml Switch Configuration
ocamlfind           1.8.1       A library manager for OCaml
[NOTE] Package coq is already installed (current version is dev).
The following actions will be performed:
  - install coq-ruler-compass-geometry dev
<><> Gathering sources ><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
[coq-ruler-compass-geometry.dev] synchronised from git+https://github.com/coq-contribs/ruler-compass-geometry.git#master
<><> Processing actions <><><><><><><><><><><><><><><><><><><><><><><><><><><><>
[ERROR] The compilation of coq-ruler-compass-geometry failed at "/home/bench/.opam/opam-init/hooks/sandbox.sh build make -j4".
#=== ERROR while compiling coq-ruler-compass-geometry.dev =====================#
# context              2.0.5 | linux/x86_64 | ocaml-base-compiler.4.09.0 | file:///home/bench/run/opam-coq-archive/extra-dev
# path                 ~/.opam/ocaml-base-compiler.4.09.0/.opam-switch/build/coq-ruler-compass-geometry.dev
# command              ~/.opam/opam-init/hooks/sandbox.sh build make -j4
# exit-code            2
# env-file             ~/.opam/log/coq-ruler-compass-geometry-25250-0a5907.env
# output-file          ~/.opam/log/coq-ruler-compass-geometry-25250-0a5907.out
### output ###
# [...]
# File "./D2_Axe.v", line 5, characters 0-21:
# Warning: Use of "Require" inside a section is deprecated.
# [require-in-section,deprecated]
# File "./D2_Axe.v", line 55, characters 0-9:
# Error:
# Anomaly "File "clib/int.ml", line 46, characters 14-20: Assertion failed."
# Please report at http://coq.inria.fr/bugs/.
#
# Makefile:672: recipe for target 'D2_Axe.vo' failed
# make[1]: *** [D2_Axe.vo] Error 129
# Makefile:326: recipe for target 'all' failed
# make: *** [all] Error 2
<><> Error report <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
+- The following actions failed
| - build coq-ruler-compass-geometry dev
+-
- No changes have been performed
# Run eval $(opam env) to update the current shell environment

Installation size

No files were installed.

Uninstall

Command

true

Return code

0

Missing removes

                none

Wrong removes

                none

          Sources are on GitHub. © Guillaume Claret.


text:
module Petergate
  module ActionController
    module Base
      module ClassMethods
        def const_missing(const_name)
          if [:AllRest, :ALLREST].include?(const_name)
            warn "`AllRest` and `ALLREST` has been deprecated. Use :all instead."
            return ALLRESTDEP
          else
            return super
          end
        end

        def all_actions
          ->{self.action_methods.to_a.map(&:to_sym) - [:check_access, :title]}.call
        end

        def except_actions(arr = [])
          all_actions - arr
        end

        def access(rules = {}, &block)
          if block
            b_rules = block.call
            rules = rules.merge(b_rules) if b_rules.is_a?(Hash)
          end

          instance_eval do
            @_controller_rules = rules
            @_controller_message = rules.delete(:message)

            def controller_rules
              @_controller_rules
            end

            def controller_message
              @_controller_message || "Permission Denied"
            end

            def inherited(subclass)
              super
              subclass.instance_variable_set("@_controller_rules", instance_variable_get("@_controller_rules"))
              subclass.instance_variable_set("@_controller_message", instance_variable_get("@_controller_message"))
            end
          end

          before_action do
            unless logged_in?(:root_admin)
              message = permissions(self.class.controller_rules)
              if message == false || message.is_a?(String)
                if current_user || @user
                  forbidden! message
                else
                  unauthorized!
                end
              end
            end
          end
        end
      end

      ALLRESTDEP = [:show, :index, :new, :edit, :update, :create, :destroy]

      def self.included(base)
        base.extend(ClassMethods)
        base.helper_method :logged_in?, :forbidden!, :unauthorized!
      end

      def parse_permission_rules(rules)
        rules = rules.inject({}) do |h, (k, v)|
          special_values = case v.class.to_s
                           when "Symbol"
                             v == :all ? self.class.all_actions : raise("No action for: #{v}")
                           when "Hash"
                             v[:except].present? ? self.class.except_actions(v[:except]) : raise("Invalid values for except: #{v.values}")
                           when "Array"
                             v
                           else
                             raise("No action for: #{v}")
                           end

          h.merge({k => special_values})
        end
        # Allows Array's of keys for the same hash.
        rules = rules.inject({}){|h, (k, v)| k.class == Array ? h.merge(Hash[k.map{|kk| [kk, v]}]) : h.merge(k => v) }
      end

      def permissions(rules = {all: [:index, :show], customer: [], wiring: []})
        rules = parse_permission_rules(rules)
        allowances = [rules[:all]]
        current_user.roles.each do |role|
          allowances << rules[role]
        end if user_logged_in?
        allowances.flatten.compact.include?(action_name.to_sym)
      end

      def logged_in?(*roles)
        current_user && current_user.has_roles?(*roles)
      end

      def user_logged_in?
        !!current_user
      end

      def custom_message
        defined?(self.class.controller_message) ? self.class.controller_message : 'Permission Denied'
      end

      def unauthorized!
        respond_to do |format|
          format.any(:js, :json, :xml) do
            head(:unauthorized)
          end
          format.html do
            return authenticate_user!
          end
        end
      end

      def forbidden!(msg = nil)
        respond_to do |format|
          format.any(:js, :json, :xml) do
            head(:forbidden)
          end
          format.html do
            destination = current_user.present? ? request.headers['Referrer'] || after_sign_in_path_for(current_user) : root_path
            redirect_to destination, notice: (msg || request.headers['msg'] || custom_message)
          end
        end
      end
    end
  end
end

class ActionController::Base
  include Petergate::ActionController::Base
end


text:
import { Component } from '@angular/core';
import { SessionService } from 'services/session';
import { environment } from 'environments/environment';

@Component({
  selector: 'app-sidenav',
  templateUrl: './sidenav.html',
  styleUrls: ['./sidenav.scss']
})
export class SidenavComponent {
  get addToHomeScreenEnabled(): boolean { return !!this.sessionService.currentSession.installPrompt; }
  get termsAndPrivacyEnabled(): boolean { return environment.pages.termsAndPrivacy.enabled; }

  constructor(private sessionService: SessionService) {
  }

  onAddToHomeScreenClick() {
    this.sessionService.currentSession.installPrompt.prompt();
    this.sessionService.currentSession.installPrompt.userChoice.then(() => {
      this.sessionService.currentSession.installPrompt = null;
    });
  }
}


text:
function Controller() {
    function __alloyId18(e) {
        if (e && e.fromAdapter) return;
        __alloyId18.opts || {};
        var models = filterData(__alloyId17);
        var len = models.length;
        var rows = [];
        for (var i = 0; len > i; i++) {
            var __alloyId11 = models[i];
            __alloyId11.__transform = transData(__alloyId11);
            var __alloyId13 = Ti.UI.createTableViewRow({
                _id: "undefined" != typeof __alloyId11.__transform["alloy_id"] ? __alloyId11.__transform["alloy_id"] : __alloyId11.get("alloy_id")
            });
            rows.push(__alloyId13);
            doneConfirm ? __alloyId13.addEventListener("click", doneConfirm) : __defers["__alloyId13!click!doneConfirm"] = true;
            var __alloyId14 = Ti.UI.createView({
                width: Ti.UI.FILL,
                height: Ti.UI.SIZE,
                top: "6dp",
                right: "11dp",
                bottom: "6dp",
                left: "11dp",
                layout: "horizontal"
            });
            __alloyId13.add(__alloyId14);
            var __alloyId15 = Ti.UI.createLabel({
                width: Ti.UI.FILL,
                height: Ti.UI.SIZE,
                textAlign: "left",
                font: {
                    fontSize: "18sp",
                    fontWeight: "bold"
                },
                text: "undefined" != typeof __alloyId11.__transform["task"] ? __alloyId11.__transform["task"] : __alloyId11.get("task")
            });
            __alloyId14.add(__alloyId15);
            var __alloyId16 = Ti.UI.createLabel({
                width: Ti.UI.FILL,
                height: Ti.UI.SIZE,
                textAlign: "left",
                font: {
                    fontSize: "14sp"
                },
                text: "undefined" != typeof __alloyId11.__transform["limitTime"] ? __alloyId11.__transform["limitTime"] : __alloyId11.get("limitTime")
            });
            __alloyId14.add(__alloyId16);
        }
        $.__views.tasks.setData(rows);
    }
    function addQ() {
        var addWin, index;
        alert("資格を登録します");
        if (void 0 === Alloy.Globals.currentTab) {
            index = Alloy.createController("index");
            Alloy.Globals.currentTab = index.getView("listTab");
        }
        addWin = Alloy.createController("Add").getView("addQ");
        Alloy.Globals.currentTab.open(addQ);
    }
    function transData(model) {
        var transform, limitTime;
        transform = model.toJSON();
        limitTime = transform.limitTime;
        transform.limitTime = moment(Number(limitTime)).format("YYYY/MM/DD");
        return transform;
    }
    function filterData(collection) {
        return collection.where({
            done: 0
        });
    }
    function doneConfirm(e) {
        dialogs.confirm({
            message: "Done?",
            callback: function() {
                var model = Alloy.Collections.Todo.where({
                    alloy_id: e.rowData._id
                })[0];
                model.set({
                    done: 1
                }).save();
            }
        });
    }
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "List";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    var __defers = {};
    $.__views.List = Ti.UI.createWindow({
        backgroundColor: "#FFFFFF",
        title: "Tasks",
        id: "List"
    });
    $.__views.List && $.addTopLevelView($.__views.List);
    $.__views.tasks = Ti.UI.createTableView({
        id: "tasks"
    });
    $.__views.List.add($.__views.tasks);
    var __alloyId17 = Alloy.Collections["Todo"] || Todo;
    __alloyId17.on("fetch destroy change add remove reset", __alloyId18);
    exports.destroy = function() {
        __alloyId17.off("fetch destroy change add remove reset", __alloyId18);
    };
    _.extend($, $.__views);
    $.addQ = addQ;
    var moment = require("alloy/moment");
    var dialogs = require("alloy/dialogs");
    __defers["$.__views.addButton!click!addQ"] && $.__views.addButton.addEventListener("click", addQ);
    __defers["__alloyId13!click!doneConfirm"] && __alloyId13.addEventListener("click", doneConfirm);
    _.extend($, exports);
}

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

module.exports = Controller;


text:
[//]: # (title: SDK)

<!-- Copyright 2000-2022 JetBrains s.r.o. and other contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. -->

<tldr>

**Product Help:** [SDKs](https://www.jetbrains.com/help/idea/working-with-sdks.html)

</tldr>

Every project uses a Software Development Kit (SDK).
For Java projects, the SDK is referred to as the JDK (Java Development Kit).
The SDK determines which API library is used to build the project.
If a project is multi-module, the project SDK by default is common for all modules within the project.
Optionally, individual SDKs for each module can be configured.

## Getting Project SDK Information
The information about the project SDK is accessed via [`ProjectRootManager`](%gh-ic%/platform/projectModel-api/src/com/intellij/openapi/roots/ProjectRootManager.java) like the following example shows

```java
Sdk projectSdk = ProjectRootManager.getInstance(project).getProjectSdk();
```

## Getting and Setting Project SDK Attributes

* To get the project-level SDK:

  ```java
  Sdk projectSdk = ProjectRootManager.getInstance(project).getProjectSdk();
  ```

* To get the project-level SDK name:

  ```java
  String projectSdkName = ProjectRootManager.getInstance(project).getProjectSdkName();
  ```

* To set the project-level SDK:

  ```java
  ProjectRootManager.getInstance(project).setProjectSdk(sdk);
  ```

* To set the project-level SDK name:

  ```java
  ProjectRootManager.getInstance(project).setProjectSdkName(name);
  ```

See the [project_model](%gh-sdk-samples%/project_model/src/main/java/org/intellij/sdk/project/model/ProjectSdkAction.java) code sample to get more familiar with SDK manipulation toolset.

## Available SDKs

[`ProjectJdkTable`](%gh-ic%/platform/projectModel-api/src/com/intellij/openapi/projectRoots/ProjectJdkTable.java) can be used to query and modify configured SDKs.

## Working with a Custom SDK

To create a custom SDK, provide a class extending [`SdkType`](%gh-ic%/platform/lang-core/src/com/intellij/openapi/projectRoots/SdkType.java), leave `saveAdditionalData()` blank, and register it in the `com.intellij.sdkType` extension point.

To make SDK settings persistent, override `setupSdkPaths()` and save settings by `modificator.commitChanges()`:

```java
@Override
public boolean setupSdkPaths(@NotNull Sdk sdk, @NotNull SdkModel sdkModel) {
  SdkModificator modificator = sdk.getSdkModificator();
  modificator.setVersionString(getVersionString(sdk));
  modificator.commitChanges(); // save
  return true;
}
```

To let a user select an SDK, see [`ProjectJdksEditor`](%gh-ic%/java/idea-ui/src/com/intellij/openapi/projectRoots/ui/ProjectJdksEditor.java).

However, it is not recommended to use "SDK" in non-IntelliJ IDEA IDEs.
Although "SDK" is available in most JetBrains products, `ProjectJdksEditor` is specific to Java, making the operation around "SDK" difficult.
The recommended way of managing "SDK" settings is to create a [`CustomStepProjectGenerator`](%gh-ic%/platform/lang-impl/src/com/intellij/ide/util/projectWizard/CustomStepProjectGenerator.java) implementation and save settings in a [`PersistentStateComponent`](persisting_state_of_components.md).

## Assisting in Setting Up an SDK

Prompting the user with a notification to set up an SDK can help them get up-and-running with a plugin faster.
Use `com.intellij.projectSdkSetupValidator` extension point to register an implementation of [`ProjectSdkSetupValidator`](%gh-ic%/platform/lang-impl/src/com/intellij/codeInsight/daemon/ProjectSdkSetupValidator.java) to notify the user if they are missing an SDK.

The following is a simplified example that checks whether an instance of "DemoSdk" has been configured in the project when the user opens a "DemoFileType":

```kotlin
class DemoProjectSdkSetupValidator : ProjectSdkSetupValidator {
  override fun isApplicableFor(project: Project, file: VirtualFile): Boolean {
    return file.fileType == DemoFileType
  }

  override fun getErrorMessage(project: Project, file: VirtualFile): String? {
    if (ProjectJdkTable.getInstance().getSdksOfType(DemoSdkType.getInstance()).isEmpty()) {
      return "No DemoSdks are configured for this project!"
    }
    return null
  }

  override fun getFixHandler(project: Project, file: VirtualFile):
        EditorNotificationPanel.ActionHandler {
    return SdkPopupFactory.newBuilder()
        .withProject(project)
        .withSdkTypeFilter { it is DemoSdkType }
        .updateSdkForFile(file)
        .buildEditorNotificationPanelHandler()
  }
}
```

Within `DemoProjectSdkSetupValidator`:

* `isApplicableFor()` checks what condition(s) should be met to run the validation.
* `getErrorMessage()` runs the validation and return an appropriate error message if the validation fails.
* If the validation is successful, then it should return null.
* `getFixHandler()` returns an `EditorNotificationPanel.ActionHandler` that enables the user to execute a quick-fix to resolve the validation issue.

> `ProjectSdkSetupValidator` will not work in IntelliJ Platform-based IDEs such as PyCharm.
> In such cases, you should register an implementation of [`EditorNotifications.Provider`](%gh-ic%/platform/platform-api/src/com/intellij/ui/EditorNotifications.java) at the `com.intellij.editorNotificationProvider` extension point and override the `createNotificationPanel()` method with the conditionality and panel setup you want.
>
{style="warning"}


text:
package org.springframework.transaction.interceptor;

import org.aopalliance.aop.Advice;

import org.springframework.aop.ClassFilter;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * Advisor driven by a {@link TransactionAttributeSource}, used to include
 * a {@link TransactionInterceptor} only for methods that are transactional.
 *
 * <p>Because the AOP framework caches advice calculations, this is normally
 * faster than just letting the TransactionInterceptor run and find out
 * itself that it has no work to do.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @see #setTransactionInterceptor
 * @see TransactionProxyFactoryBean
 */
@SuppressWarnings("serial")
public class TransactionAttributeSourceAdvisor extends AbstractPointcutAdvisor {

	@Nullable
	private TransactionInterceptor transactionInterceptor;

	private final TransactionAttributeSourcePointcut pointcut = new TransactionAttributeSourcePointcut() {
		@Override
		@Nullable
		protected TransactionAttributeSource getTransactionAttributeSource() {
			return (transactionInterceptor != null ? transactionInterceptor.getTransactionAttributeSource() : null);
		}
	};

	/**
	 * Create a new TransactionAttributeSourceAdvisor.
	 */
	public TransactionAttributeSourceAdvisor() {
	}

	/**
	 * Create a new TransactionAttributeSourceAdvisor.
	 * @param interceptor the transaction interceptor to use for this advisor
	 */
	public TransactionAttributeSourceAdvisor(TransactionInterceptor interceptor) {
		setTransactionInterceptor(interceptor);
	}

	/**
	 * Set the transaction interceptor to use for this advisor.
	 */
	public void setTransactionInterceptor(TransactionInterceptor interceptor) {
		this.transactionInterceptor = interceptor;
	}

	/**
	 * Set the {@link ClassFilter} to use for this pointcut.
	 * Default is {@link ClassFilter#TRUE}.
	 */
	public void setClassFilter(ClassFilter classFilter) {
		this.pointcut.setClassFilter(classFilter);
	}

	@Override
	public Advice getAdvice() {
		Assert.state(this.transactionInterceptor != null, "No TransactionInterceptor set");
		return this.transactionInterceptor;
	}

	@Override
	public Pointcut getPointcut() {
		return this.pointcut;
	}

}


text:
package org.xbib.elasticsearch.jdbc.strategy.mock;

import org.elasticsearch.common.unit.TimeValue;
import org.xbib.elasticsearch.common.keyvalue.KeyValueStreamListener;
import org.xbib.elasticsearch.common.util.SQLCommand;
import org.xbib.elasticsearch.common.util.SourceMetric;
import org.xbib.elasticsearch.jdbc.strategy.JDBCSource;
import org.xbib.elasticsearch.jdbc.strategy.Source;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.ParseException;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

/**
 * @author Piotr Śliwa
 */
public class MockJDBCSource implements JDBCSource<MockContext> {

    @Override
    public String strategy() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> newInstance() {
        return new MockJDBCSource();
    }

    @Override
    public JDBCSource<MockContext> setContext(MockContext context) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public MockContext getContext() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void beforeFetch() throws Exception {
    }

    @Override
    public void afterFetch() throws Exception {
    }

    @Override
    public void fetch() throws SQLException, IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> setUrl(String url) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> setUser(String user) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> setPassword(String password) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> setScale(int scale) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setRounding(String rounding) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setStatements(List<SQLCommand> sql) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setAutoCommit(boolean autocommit) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setMaxRows(int maxRows) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setFetchSize(int fetchSize) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setRetries(int retries) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setMaxRetryWait(TimeValue maxretrywait) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setResultSetType(String resultSetType) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setResultSetConcurrency(String resultSetConcurrency) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> shouldIgnoreNull(boolean shouldIgnoreNull) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> shouldPrepareResultSetMetadata(boolean shouldPrepareResultSetMetadata) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> shouldPrepareDatabaseMetadata(boolean shouldPrepareDatabaseMetadata) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setQueryTimeout(int queryTimeout) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setConnectionProperties(Map<String, Object> connectionProperties) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setColumnNameMap(Map<String, Object> columnNameMap) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> shouldTreatBinaryAsString(boolean shouldTreatBinaryAsString) {
        return this;
    }

    @Override
    public Connection getConnectionForReading() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Connection getConnectionForWriting() throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public PreparedStatement prepareQuery(String sql) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public PreparedStatement prepareUpdate(String sql) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> bind(PreparedStatement statement, List<Object> values) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> register(CallableStatement statement, Map<String, Object> values) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ResultSet executeQuery(PreparedStatement statement) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public ResultSet executeQuery(Statement statement, String sql) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> executeUpdate(PreparedStatement statement) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> executeUpdate(Statement statement, String sql) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void beforeRows(ResultSet result, KeyValueStreamListener listener) throws SQLException, IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void beforeRows(SQLCommand command, ResultSet result, KeyValueStreamListener listener) throws SQLException, IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean nextRow(ResultSet result, KeyValueStreamListener listener) throws SQLException, IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean nextRow(SQLCommand command, ResultSet result, KeyValueStreamListener listener) throws SQLException, IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void afterRows(ResultSet result, KeyValueStreamListener listener) throws SQLException, IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void afterRows(SQLCommand command, ResultSet result, KeyValueStreamListener listener) throws SQLException, IOException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public Object parseType(ResultSet result, Integer num, int type, Locale locale) throws SQLException, IOException, ParseException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> close(ResultSet result) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> close(Statement statement) throws SQLException {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> closeReading() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> closeWriting() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public JDBCSource<MockContext> setLocale(Locale locale) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setTimeZone(TimeZone timezone) {
        return this;
    }

    @Override
    public void shutdown() throws IOException {
    }

    @Override
    public Source setMetric(SourceMetric metric) {
        return this;
    }

    @Override
    public SourceMetric getMetric() {
        return null;
    }

	@Override
	public JDBCSource<MockContext> setRowDefault(Map<String, Object> row) {
		// TODO Auto-generated method stub
		return this;
	}

    @Override
    public JDBCSource<MockContext> setRowExtend(Map<String, Object> params) {
        return this;
    }

    @Override
    public JDBCSource<MockContext> setRowMax(Map<String, Object> init) {
        return this;
    }

}


text:
package gamerules

import (
	. "github.com/huin/chunkymonkey/types"
	"log"
	"math/rand"
)

// Behaviour of a sapling block, takes care of growing or dying depending on
// world conditions.
func makeSaplingAspect() (aspect IBlockAspect) {
	return &SaplingAspect{}
}

type SaplingAspect struct {
	StandardAspect
}

func (aspect *SaplingAspect) Name() string {
	return "Sapling"
}

func (aspect *SaplingAspect) Tick(instance *BlockInstance) bool {
	// TODO: Use a random number that is reproduceable from merely the chunk
	// location so that the world seed produces consistent worlds.
	if rand.Intn(1e4) >= 1e4-1 {
		// Turn this block into a tree
		return aspect.makeTree(instance)
	}
	return true
}

func (aspect *SaplingAspect) makeTree(instance *BlockInstance) bool {
	loc := instance.SubLoc
	minheight := 3
	maxheight := 6
	height := minheight + rand.Intn(maxheight-minheight)
	maxy := loc.Y + SubChunkCoord(height)

	for y := loc.Y; y < maxy; y++ {
		loc.Y = y
		index, ok := loc.BlockIndex()
		if !ok {
			// TODO: Can't place a block outside chunk boundaries
			log.Printf("Couldn't place a tree block (%v,%v,%v)", loc.X, loc.Y, loc.Z)
		} else {
			instance.Chunk.SetBlockByIndex(index, BlockId(17), byte(0))
		}
	}

	// Store the location at the top block of the tree
	treex, treey, treez := int(loc.X), int(loc.Y), int(loc.Z)
	cradius := height / 2

	// Start one block above the tree and move down
	for y := treey + 1; y >= treey-1; y-- {
		var radius int

		// Slightly round out the canopy
		if y > treey {
			radius = cradius - 1
		} else if y == treey {
			radius = cradius
		} else if y < treey {
			radius = cradius - 1
		}

		for x := treex - radius; x <= treex+radius; x++ {
			for z := treez - radius; z <= treez+radius; z++ {
				if y > treey || x != treex || z != treez {
					loc.X = SubChunkCoord(x)
					loc.Y = SubChunkCoord(y)
					loc.Z = SubChunkCoord(z)
					index, ok := loc.BlockIndex()
					if !ok {
						// TODO: Can't place a block outside chunk boundaries
						log.Printf("Couldn't place a leaf block (%v,%v,%v)", loc.X, loc.Y, loc.Z)
					} else {
						instance.Chunk.SetBlockByIndex(index, BlockId(18), byte(0))
					}
				}
			}
		}
	}

	return true
}


text:
"""Common entity class for Version integration."""

from homeassistant.helpers.device_registry import DeviceEntryType
from homeassistant.helpers.entity import DeviceInfo, EntityDescription
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN, HOME_ASSISTANT
from .coordinator import VersionDataUpdateCoordinator

class VersionEntity(CoordinatorEntity[VersionDataUpdateCoordinator]):
    """Common entity class for Version integration."""

    _attr_device_info = DeviceInfo(
        name=f"{HOME_ASSISTANT} {DOMAIN.title()}",
        identifiers={(HOME_ASSISTANT, DOMAIN)},
        manufacturer=HOME_ASSISTANT,
        entry_type=DeviceEntryType.SERVICE,
    )

    def __init__(
        self,
        coordinator: VersionDataUpdateCoordinator,
        entity_description: EntityDescription,
    ) -> None:
        """Initialize version entities."""
        super().__init__(coordinator)
        self.entity_description = entity_description
        self._attr_unique_id = (
            f"{coordinator.config_entry.entry_id}_{entity_description.key}"
        )


text:
'''rudimentary command-line interface for keyword search functionality

.. This software is released under an MIT/X11 open source license.
   Copyright 2012-2014 Diffeo, Inc.
'''
from __future__ import absolute_import
from streamcorpus_pipeline._kvlayer_table_names import STREAM_ITEM_TABLE_DEFS
from streamcorpus_pipeline._kvlayer_keyword_search import keyword_indexer
import kvlayer
import yakonfig

def main():
    import streamcorpus_pipeline
    import argparse
    parser = argparse.ArgumentParser(description='basic command-line tool for checking indexes built by streamcorpus_pipeline._to_kvlayer.  Accepts a query string as input and print stream_ids of documents that match *any* of the terms')
    parser.add_argument('query_string', nargs='+', help='enter one or more query words; will be combined with OR')

    modules = [yakonfig, kvlayer]
    args = yakonfig.parse_args(parser, modules)
    config = yakonfig.get_global_config()

    kvl = kvlayer.client()
    kvl.setup_namespace(STREAM_ITEM_TABLE_DEFS)

    indexer = keyword_indexer(kvl)

    for si in indexer.search(' '.join(args.query_string)):
        print si.stream_id


text:
class MemoryLeakDetector : public testing::EmptyTestEventListener {

public:
    virtual void OnTestStart(const testing::TestInfo&) override {
        _CrtMemCheckpoint(&memState_);
    }

    virtual void OnTestEnd(const testing::TestInfo& test_info) override {
        if (test_info.result()->Passed()) {
            _CrtMemState stateNow, stateDiff;
            _CrtMemCheckpoint(&stateNow);
            int diffResult = _CrtMemDifference(&stateDiff, &memState_, &stateNow);
            if (diffResult) {
                //_CrtDumpMemoryLeaks();
                FAIL() << "Memory leak of " << stateDiff.lSizes[1] << " byte(s) detected.";
            }
        }
    }

private:
    _CrtMemState memState_;
};

class MutexAllocator {
public:
    // The function must have a type in order to create the g_gmock_mutex in UntypedFunctionMockerBase
    MOCK_METHOD1(doStuff, void(float));
};

#endif

int main(int argc, char** argv) {
    testing::InitGoogleTest(&argc, argv);

#ifdef _WIN32
    // We call log in order to allocate the g_log_mutex
    testing::internal::Log(testing::internal::kWarning, "Allocating Mutexes\n", -1);

    auto mutexAllocator = new MutexAllocator();
    // We need an expectation to allocate the g_gmock_implicit_sequence
    // NB as this is allocated in a ThreadLocal variable this fix might not work for multithreaded tests
    EXPECT_CALL(*mutexAllocator, doStuff(testing::_)).Times(0);
    delete mutexAllocator;

    testing::UnitTest::GetInstance()->listeners().Append(new MemoryLeakDetector());
#endif

    return RUN_ALL_TESTS();

}


text:
package org.apache.ignite.internal.processors.cache.ttl;

import org.apache.ignite.cache.CacheMode;

/**
 * TTL test with offheap.
 */
public class CacheTtlOffheapTransactionalLocalSelfTest extends CacheTtlOffheapTransactionalAbstractSelfTest {
    /** {@inheritDoc} */
    @Override protected CacheMode cacheMode() {
        return CacheMode.LOCAL;
    }

    /** {@inheritDoc} */
    @Override protected int gridCount() {
        return 1;
    }
}


text:
<?php
namespace common\models;

use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
use yii\helpers\ArrayHelper;

/**
 * User model
 *
 * @property integer $id
 * @property string $username
 * @property string $password_hash
 * @property string $password_reset_token
 * @property string $email
 * @property string $auth_key
 * @property integer $status
 * @property integer $created_at
 * @property integer $updated_at
 * @property string $password write-only password
 */
class User extends ActiveRecord implements IdentityInterface
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 10;

    const ROLE_USER = 'User';
    const ROLE_MANAGER = 'Manager';

    const ROLE_ADMINISTRATOR = 'Admin';

    const SCENARIO_USERMANAGE = 'default';
    const SCENARIO_REGISTER ='register';

    public $password;
    public $confirm_password;
    public $role;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%user}}';
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            //['status', 'required'],
            ['status', 'default', 'value' => self::STATUS_ACTIVE],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DELETED]],

            ['username', 'filter', 'filter' => 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'มีชื่อผู้ใช้งานนี้อยู่ในระบบแล้ว ..!'],
            ['username', 'string', 'min' => 2, 'max' => 255],

            ['email', 'filter', 'filter' => 'trim'],
            //['email', 'required'],
            ['email', 'email'],
            ['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'มีอีเมล์นี้อยู่ในระบบแล้ว.'],

            ['password', 'required'],
            ['password', 'string', 'min' => 6],

            ['confirm_password', 'required'],
            ['confirm_password', 'string', 'min' => 6],
            ['confirm_password', 'compare','compareAttribute'=>'password'],

            ['role', 'safe'],

        ];
    }
    public function attributeLabels()
    {
        return [
            'confirm_password' => 'ยืนยันรหัสผ่าน',
            'username' => 'ชื่อผู้ใช้งาน',
            'password' => 'รหัสผ่าน',
            'status' => 'สถานะ',
            'email'=>'อีเมล์',
            'created_at'=>'วันที่สร้าง',

        ];
    }
    public function scenarios()
    {
        return [
            self::SCENARIO_USERMANAGE => ['username', 'password','confirm_password','email','status','role'],
            self::SCENARIO_REGISTER => ['username', 'email'],
        ];
    }
    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token)
    {
        if (empty($token)) {
            return false;
        }

        $timestamp = (int) substr($token, strrpos($token, '_') + 1);
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }

    public function getItemStatus(){
        return [
          self::STATUS_ACTIVE => 'Active',
          self::STATUS_DELETED => 'Deleted'
        ];
      }
      public function getStatusName()
      {
        $items = $this->getItemStatus();
        return array_key_exists($this->status, $items) ? $items[$this->status] : '';
      }

      public function getAllRoles(){
        $auth = $auth = Yii::$app->authManager;
        return ArrayHelper::map($auth->getRoles(),'name','name');
      }

      public function getRoleByUser(){
        $auth = Yii::$app->authManager;
        $rolesUser = $auth->getRolesByUser($this->id);
        $roleItems = $this->getAllRoles();
        $roleSelect=[];

        foreach ($roleItems as $key => $roleName) {
          foreach ($rolesUser as $role) {
            if($key==$role->name){
              $roleSelect[$key]=$roleName;
            }
          }
        }
        $this->role = $roleSelect;
      }

      public function assignment(){
          $auth = Yii::$app->authManager;
          $roleUser = $auth->getRolesByUser($this->id);
          $auth->revokeAll($this->id);
          foreach ($this->role as $key => $roleName) {
            $auth->assign($auth->getRole($roleName),$this->id);
          }
      }
//////////////////////////////////
    public function getSchool(){
        return $this->hasMany(Student::className(), ['id' => 'user_id'])
            ->via('school');
    }
    public function getStudent(){
        return $this->hasMany(Student::className(),['id'=>'user_id']);
    }

}


text:
class ProfilePdfController < ApplicationController
  include ApplicationHelper

  before_action :authorize!

  def student_report
    set_up_student_report_data

    # KR: not sure why, but JS isn't running locally for me or on Travis, so
    # disabling this check since we aren't testing anything generated by JS
    # anyway.
    wait_for_js = if params[:disable_js] && Rails.env.test? then
      {}
    else
      { window_status: 'READY' }
    end

    respond_to do |format|
      format.pdf do
        render(wait_for_js.merge({
          pdf: 'student_report',
          title: 'Student Report',
          footer: { center: footer_text_template, font_name: 'Open Sans', font_size: 9},
          show_as_html: params.key?('debug')
        }))
      end
    end
  end

  private
  def authorize!
    student = Student.find(params[:id])
    raise Exceptions::EducatorNotAuthorized unless current_educator.is_authorized_for_student(student)
  end

  def footer_text_template
    todays_date = Time.now.in_time_zone('Eastern Time (US & Canada)').to_date
    "#{PerDistrict.new.district_name} Student Report -- Generated #{format_date_for_student_report(todays_date)} by #{current_educator.full_name} -- Page [page] of [topage]"
  end

  # Only allow access if they have authorization and explicitly express intention
  def filter_for_restricted_notes(current_educator, params)
    authorization = current_educator.can_view_restricted_notes?
    intention = (params.fetch(:include_restricted_notes, 'false').downcase == 'true')
    if authorization && intention
      [true, false]
    else
      [false]
    end
  end

  def set_up_student_report_data
    @student = Student.find(params[:id])
    @current_educator = current_educator
    @sections = (params[:sections] || "").split(",")

    @filter_from_date = params[:from_date] ? Date.strptime(params[:from_date],  "%m/%d/%Y") : Date.today
    @filter_to_date = (params[:from_date] ? Date.strptime(params[:to_date],  "%m/%d/%Y") : Date.today).advance(days: 1) # so we include the current day

    # Load event notes for the student for the filtered dates, possibly including restricted notes
    @event_notes = @student.event_notes
      .where(is_restricted: filter_for_restricted_notes(current_educator, params))
      .where(recorded_at: @filter_from_date..@filter_to_date)

    # Load services for the student for the filtered dates
    @services = @student.services.where("date_started <= ? AND (discontinued_at >= ? OR discontinued_at IS NULL)", @filter_to_date, @filter_from_date).order('date_started, discontinued_at')

    # Load student school years for the filtered dates
    @student_school_years = events_by_student_school_years(@student, @filter_from_date, @filter_to_date)

    # Sort the discipline incidents by occurrance date
    @discipline_incidents = @student.discipline_incidents.sort_by(&:occurred_at).select do |hash|
      hash[:occurred_at] >= @filter_from_date && hash[:occurred_at] <= @filter_to_date
    end

    # This is a hash with the test name as the key and an array of date-sorted student assessment objects as the value
    student_assessments_by_date = @student.student_assessments.order_by_date_taken_asc.includes(:assessment).where(date_taken: @filter_from_date..@filter_to_date)

    @student_assessments = student_assessments_by_date.each_with_object({}) do |student_assessment, hash|
      test = student_assessment.assessment
      test_name = "#{test.family} #{test.subject}"

      hash[test_name] ||= []

      result = case test.family
        when "MCAS" then student_assessment.scale_score
        when "Next Gen MCAS" then student_assessment.scale_score
        else student_assessment.scale_score
      end

      hash[test_name].push([student_assessment.date_taken, result])
    end.sort.to_h

    @star_math_results = @student.star_math_results.order(date_taken: :asc)
                                 .where(date_taken: @filter_from_date..@filter_to_date)
                                 .map { |star| [star.date_taken, star.percentile_rank] }
    @star_reading_results = @student.star_reading_results.order(date_taken: :asc)
                                 .where(date_taken: @filter_from_date..@filter_to_date)
                                 .map { |star| [star.date_taken, star.percentile_rank] }

    @student_assessments['STAR Math Percentile'] = @star_math_results
    @student_assessments['STAR Reading Percentile'] = @star_reading_results

    @dibels_results = @student.dibels_results.order(date_taken: :asc)
                              .where(date_taken: @filter_from_date..@filter_to_date)
                              .map { |dibels| [dibels.date_taken, dibels.benchmark] }

    @student_assessments['DIBELS'] = @dibels_results

    @serialized_data = {
      graph_date_range: {
        filter_from_date: @filter_from_date.to_time,
        filter_to_date: @filter_to_date
      },
      attendance_data: {
        discipline_incidents: @student.discipline_incidents.order(occurred_at: :desc),
        tardies: @student.tardies.order(occurred_at: :desc),
        absences: @student.absences.order(occurred_at: :desc)
      }
    }
  end

  def events_by_student_school_years(student, filter_to_date, filter_from_date)
    sorter = ProfilePdf::StudentSchoolYearSorter.new(student: student)

    sorter.sort_and_filter(filter_to_date, filter_from_date)
  end

  # Add this as a helper method that the ERB template can call
  helper_method :format_date_for_student_report
  def format_date_for_student_report(date)
    date.strftime("%-m/%-d/%Y")
  end

  helper_method :educator_pretty_first_name_first
  def educator_pretty_first_name_first(educator)
    educator.full_name.split(', ').reverse.join(' ')
  end
end


text:
/*
 * Jakarta Bean Validation: constrain once, validate everywhere.
 *
 * License: Apache License, Version 2.0
 * See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
 */
package org.beanvalidation.specexamples.constraintdefinition.constraintcomposition;

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;

//tag::include[]
@Pattern(regexp = "[0-9]*")
@Size(min = 5, max = 5)
@Constraint(validatedBy = FrenchZipCodeValidator.class)
@Documented
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
public @interface FrenchZipCode {

	String message() default "Wrong zip code";

	Class<?>[] groups() default {};

	Class<? extends Payload>[] payload() default {};

	@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
	@Retention(RUNTIME)
	@Documented
	@interface List {
		FrenchZipCode[] value();
	}
}
//end::include[]