text:
package com.facebook.buck.cli;

import com.facebook.buck.java.JavaLibrary;
import com.facebook.buck.java.MavenPublishable;
import com.facebook.buck.maven.Publisher;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.parser.BuildTargetSpec;
import com.facebook.buck.parser.TargetNodeSpec;
import com.facebook.buck.rules.BuildRule;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Predicate;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;

import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.deployment.DeployResult;
import org.eclipse.aether.deployment.DeploymentException;
import org.kohsuke.args4j.Option;

import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;

import javax.annotation.Nullable;

public class PublishCommand extends BuildCommand {
  public static final String REMOTE_REPO_LONG_ARG = "--remote-repo";
  public static final String REMOTE_REPO_SHORT_ARG = "-r";
  public static final String INCLUDE_SOURCE_LONG_ARG = "--include-source";
  public static final String INCLUDE_SOURCE_SHORT_ARG = "-s";
  public static final String TO_MAVEN_CENTRAL_LONG_ARG = "--to-maven-central";
  public static final String DRY_RUN_LONG_ARG = "--dry-run";

  @Option(
      name = REMOTE_REPO_LONG_ARG,
      aliases = REMOTE_REPO_SHORT_ARG,
      usage = "A url of the remote repository to publish artifact(s) to")
  @Nullable
  private URL remoteRepo = null;

  @Option(
      name = TO_MAVEN_CENTRAL_LONG_ARG,
      usage = "Same as \"" + REMOTE_REPO_LONG_ARG + " " + Publisher.MAVEN_CENTRAL_URL + "\"")
  private boolean toMavenCentral = false;

  @Option(
      name = INCLUDE_SOURCE_LONG_ARG,
      aliases = INCLUDE_SOURCE_SHORT_ARG,
      usage = "Publish source code as well")
  private boolean includeSource = false;

  @Option(
      name = DRY_RUN_LONG_ARG,
      usage = "Just print the artifacts to be published")
  private boolean dryRun = false;

  @Override
  public int runWithoutHelp(CommandRunnerParams params) throws IOException, InterruptedException {

    // Input validation
    if (remoteRepo == null && !toMavenCentral) {
      printError(params, "Please specify a remote repository to publish to.\n" +
              "Use " + REMOTE_REPO_LONG_ARG + " <URL> or " + TO_MAVEN_CENTRAL_LONG_ARG);
      return 1;
    }

    // Build the specified target(s).
    int exitCode = super.runWithoutHelp(params);
    if (exitCode != 0) {
      return exitCode;
    }

    // Publish given targets
    boolean success = true;
    for (BuildTarget buildTarget : getBuildTargets()) {
      success &= publishTarget(buildTarget, params);
    }

    return success ? 0 : 1;
  }

  /**
   * @return whether successful
   */
  private boolean publishTarget(BuildTarget buildTarget, CommandRunnerParams params) {
    BuildRule buildRule = Preconditions.checkNotNull(
        getBuild().getActionGraph().findBuildRuleByTarget(buildTarget));

    if (!(buildRule instanceof MavenPublishable)) {
      printError(
          params,
          "Cannot publish rule of type " + buildRule.getClass().getName());
      return false;
    }

    Publisher publisher = new Publisher(
        params.getCell().getFilesystem(),
        Optional.fromNullable(remoteRepo),
        dryRun);

    try {
      DeployResult deployResult = publisher.publish((MavenPublishable) buildRule);
      printArtifactsInformation(params, deployResult);
    } catch (DeploymentException e) {
      params.getConsole().printBuildFailureWithoutStacktraceDontUnwrap(e);
      return false;
    }
    return true;
  }

  private static void printArtifactsInformation(
      CommandRunnerParams params,
      DeployResult deployResult) {
    params.getConsole().getStdOut().println(
        "\nPublished artifacts:\n" +
            Joiner.on('\n').join(
                FluentIterable
                    .from(deployResult.getArtifacts())
                    .transform(
                        new Function<Artifact, String>() {
                          @Override
                          public String apply(Artifact input) {
                            return atrifactToString(input);
                          }
                        })));
    params.getConsole().getStdOut().println("\nDeployRequest:\n" + deployResult.getRequest());
  }

  private static void printError(CommandRunnerParams params, String errorMessage) {
    params.getConsole().printErrorText(errorMessage);
  }

  private static String atrifactToString(Artifact artifact) {
    return artifact.toString() + " < " + artifact.getFile();
  }

  @Override
  public ImmutableList<TargetNodeSpec> parseArgumentsAsTargetNodeSpecs(
      BuckConfig config, ImmutableSet<Path> ignorePaths, Iterable<String> targetsAsArgs) {
    ImmutableList<TargetNodeSpec> specs = super.parseArgumentsAsTargetNodeSpecs(
        config,
        ignorePaths,
        targetsAsArgs);

    if (includeSource) {
      specs = ImmutableList.<TargetNodeSpec>builder()
          .addAll(specs)
          .addAll(FluentIterable
              .from(specs)
              .filter(
                  new Predicate<TargetNodeSpec>() {
                    @Override
                    public boolean apply(TargetNodeSpec input) {
                      if (!(input instanceof BuildTargetSpec)) {
                        throw new IllegalArgumentException(
                            "Targets must be explicitly defined when using " +
                                INCLUDE_SOURCE_LONG_ARG);
                      }
                      return !((BuildTargetSpec) input)
                          .getBuildTarget()
                          .getFlavors()
                          .contains(JavaLibrary.SRC_JAR);
                    }
                  })
              .transform(
                  new Function<TargetNodeSpec, BuildTargetSpec>() {
                    @Override
                    public BuildTargetSpec apply(TargetNodeSpec input) {
                      return BuildTargetSpec.of(
                          ((BuildTargetSpec) input)
                              .getBuildTarget()
                              .withFlavors(JavaLibrary.SRC_JAR),
                          input.getBuildFileSpec());
                    }
                  }))
          .build();
    }

    // Append "maven" flavor
    specs = FluentIterable
        .from(specs)
        .transform(
            new Function<TargetNodeSpec, TargetNodeSpec>() {
              @Nullable
              @Override
              public TargetNodeSpec apply(@Nullable TargetNodeSpec input) {
                if (!(input instanceof BuildTargetSpec)) {
                  throw new IllegalArgumentException(
                      "Need to specify build targets explicitly when publishing. " +
                          "Cannot modify " + input);
                }
                BuildTargetSpec buildTargetSpec = (BuildTargetSpec) input;
                BuildTarget buildTarget =
                    Preconditions.checkNotNull(buildTargetSpec.getBuildTarget());
                return buildTargetSpec.withBuildTarget(
                    BuildTarget
                        .builder(buildTarget)
                        .addFlavors(JavaLibrary.MAVEN_JAR)
                        .build());
              }
            })
        .toList();

    return specs;
  }

  @Override
  public String getShortDescription() {
    return "builds and publishes a library to a central repository";
  }
}


text:
package com.thedeanda.ajaxproxy.config.model.proxy;

import java.util.ArrayList;
import java.util.List;

import com.thedeanda.ajaxproxy.config.model.StringVariable;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ProxyConfigRequest implements ProxyConfig {
	@Builder.Default
	private String protocol = "http";
	@Builder.Default
	private StringVariable host = new StringVariable();
	@Builder.Default
	private int port = 80;
	@Builder.Default
	private StringVariable path = new StringVariable();
	private boolean enableCache;
	/** cache duration in seconds */
	@Builder.Default
	private int cacheDuration = 500;
	private String hostHeader;
	@Builder.Default
	private List<HttpHeader> headers = new ArrayList<>();

}

redpajama_set_name: RedPajamaGithub


text:
package org.broad.igv.sam.lite;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;

/**
 * Created by jrobinso on 3/10/17.
 */
public class BGUnzip {
    public static final int BGZIP_HEADER_LENGTH = 18;

    // Uncompress data,  assumed to be series of bgzipped blocks

    public static byte[] blockUnzip(byte[] data, int lim) throws IOException {

        Inflater inflater = new Inflater(true);

        int ptr = 0;

        if (lim <= 0) lim = data.length - BGZIP_HEADER_LENGTH;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);

        while (ptr < lim) {

            int xlen =  unpackInt16(data, 10);
            int si1 = data[ptr + 12];
            int si2 = data[ptr + 13];
            int slen =  unpackInt16(data, 14);
            int bsize = unpackInt16(data, ptr + 16) + 1;
            int uncLength = unpackInt32(data, ptr + bsize - 4);

            int start = BGZIP_HEADER_LENGTH + ptr;    // Start of CDATA
            int remainder = data.length - start;
            if (remainder < (bsize + 8)) break;

            inflater.reset();
            inflater.setInput(data, start, remainder);

            byte [] output = new byte[uncLength];
            final int inflatedBytes;
            try {
                inflatedBytes = inflater.inflate(output, 0, uncLength);
            } catch (DataFormatException e) {
                // Can happen near end of file;
                break;
            }

            outputStream.write(output, 0, inflatedBytes);

            ptr += bsize;    // Advance to next block

        }

        return outputStream.toByteArray();
    }

    private static int unpackInt16(final byte[] buffer, final int offset) {
        return ((buffer[offset] & 0xFF) |
                ((buffer[offset+1] & 0xFF) << 8));
    }

    private static int unpackInt32(final byte[] buffer, final int offset) {
        return ((buffer[offset] & 0xFF) |
                ((buffer[offset + 1] & 0xFF) << 8) |
                ((buffer[offset + 2] & 0xFF) << 16) |
                ((buffer[offset + 3] & 0xFF) << 24));
    }
}


text:
function out = myIf(test,true_result,false_result);

if(test)
    out  = true_result;
else
    out = false_result;
end


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class txml.parser.XQueryParser.UndirectStepContext (TXml 1.0.0 API)</title>
<meta name="date" content="2016-05-11">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
txml.parser.XQueryParser.UndirectStepContext

Packages that use XQueryParser.UndirectStepContext

Package
Description

txml.parser

Contains antlr classes (http://www.antlr.org/).

Uses of XQueryParser.UndirectStepContext in txml.parser

Methods in txml.parser that return XQueryParser.UndirectStepContext

Modifier and Type
Method and Description

XQueryParser.UndirectStepContext
XQueryParser.undirectStep()

XQueryParser.UndirectStepContext
XQueryParser.StepsContext.undirectStep()

Methods in txml.parser with parameters of type XQueryParser.UndirectStepContext

Modifier and Type
Method and Description

void
XQueryListener.enterUndirectStep(XQueryParser.UndirectStepContext ctx)

Enter a parse tree produced by XQueryParser.undirectStep().

void
XQueryBaseListener.enterUndirectStep(XQueryParser.UndirectStepContext ctx)

Enter a parse tree produced by XQueryParser.undirectStep().

void
XQueryInterpreter.enterUndirectStep(XQueryParser.UndirectStepContext ctx)

void
XQueryListener.exitUndirectStep(XQueryParser.UndirectStepContext ctx)

Exit a parse tree produced by XQueryParser.undirectStep().

void
XQueryBaseListener.exitUndirectStep(XQueryParser.UndirectStepContext ctx)

Exit a parse tree produced by XQueryParser.undirectStep().

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016. All rights reserved.


text:
<?php

namespace Distill\Strategy;

use Distill\FileInterface;

/**
 * Minimum size strategy.
 *
 * The goal of this strategy is to try to use compressed files with better
 * compression ratio.
 *
 * @author Raul Fraile <raulfraile@gmail.com>
 */
class MinimumSize extends AbstractStrategy
{
    /**
     * {@inheritdoc}
     */
    public static function getName()
    {
        return 'minimum_size';
    }

    /**
     * {@inheritdoc}
     */
    protected function getPriorityValueForFile(FileInterface $file, array $methods)
    {
        $formatChain = $file->getFormatChain();

        return $formatChain->getCompressionRatioLevel() + ($this->getMaxUncompressionSpeedFormatChain($formatChain, $methods) / 10);
    }
}


text:
from lib import primes_up_to
import itertools
from fractions import Fraction

# The ratio of n and phi simplifies to
# abc/(a-1)(b-1)(c-1), for prime factors a b and c
# Therefore, the less prime factors the better.
#
# We cannot have a single factor (i.e. n cannot be prime),
# because the totient will never be a permuation of n.
# The totient of a prime number p is p-1.
#
# We thus know that we have exactly two prime factors.
# The bigger those factors, the smaller the ratio.
# The biggest that the two factors can be is around sqrt(10000000),
# which is thus the search area that we explore
def compute():
	min_ratio = Fraction(2, 1)
	min_num = -1
	primes = filter(lambda x: x > 2000, primes_up_to(5000))
	for i, j in itertools.product(primes, repeat=2):
		num = i * j
		if num < 10000000:
			num_coprimes = int(num * Fraction(i - 1, i) * Fraction(j - 1, j))
			if digits(num) == digits(num_coprimes) and Fraction(num, num_coprimes) < min_ratio:
				min_num = num
				min_ratio = Fraction(num, num_coprimes)

	return min_num

def digits(n):
	s = []
	while n != 0:
		s.append(n % 10)
		n /= 10
	s = sorted(s)
	return s

if __name__ == "__main__":
	print(compute())


text:
<!DOCTYPE html>

		<meta charset="utf-8"/>
		<title>Alta Usuario - MI TIENDA</title>

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

		<link rel="stylesheet" href="./css/estilos.css"/>

		<?php
			session_start();

		?>

			<?php
			if (isset ($_SESSION['role'])){
						if ($_SESSION['role'] == "usuario"){
							include("menuUser.inc.php");
						}
						elseif ($_SESSION['role'] == "administrador"){
							include("menuAdmin.inc.php");
						}
			}
			else{
				include("menu.inc.php");
			}
			?>

			<?php
			if (isset ($_POST['pass']) && 	$_POST['pass'] == $_POST['repass']){

				$nombre=$_POST['user'];
				echo $nombre;
				$password= md5($_POST['pass']);
				echo $password;
				#incluyo mi fichero de conexion
				include("mysql.inc.php");

				#lanzo la conexion de MYSQL server
				conecta($c);

				if($c==null){
					echo "Fallo en la conexion con la DB";
				}
				else{
					# selecciono mi base de datos
					$nombredb="mitienda";
					mysqli_select_db($c,$nombredb);
					// aqui vienen los comandos SQL

						$sql="SELECT login FROM usuario WHERE login = '$nombre'";
						// antes lo tenia puesto con LIKE
						echo $sql;
						#para que tenga en cuenta caracteres especiales UTF8 hay que poner antes
						mysqli_query($c,"SET NAMES 'utf8'");
						# ejecuto la orden SQL
						$nombreEsta=mysqli_query($c,$sql);

						if($nombreEsta){

									$comparacion=mysqli_affected_rows($c);

								if($comparacion == 0 || $comparacion == null){
									#el usuario NO EXISTE en la db lo podemos meter
									$sql2="INSERT INTO usuario (login, pass) VALUES ('$nombre','$password')";
									#para que tenga en cuenta caracteres especiales UTF8 hay que poner antes
										mysqli_query($c,"SET NAMES 'utf8'");
									# ejecuto la orden SQL
										$nombreIngresado=mysqli_query($c,$sql2);
									echo $sql2;

									}
									else {
										echo "ERROR EL USUARIO YA EXISTE EN LA DB";
									}
						}
						else {
						#orden SQL incorrecta
							#incluido el fallo de clave duplicada Duplicate Key
							$error=mysqli_error($c);
							echo $error;

					}

				}
		}
		else{
			echo ("PASS incorrecto");
			echo "Vuelve a Registrarte";
		}

		?>

		<?php include("footer.php"); ?>


text: /usr/bin/lynx -source http://example.com/cron.php > /dev/null 2>&1


text:
<?php namespace Arcanesoft\Auth\ViewComposers\Dashboard;

use Arcanesoft\Auth\Models\User;
use Arcanesoft\Auth\ViewComposers\ViewComposer;
use Carbon\Carbon;
use Illuminate\Contracts\View\View;

/**
 * Class     OnlineUsersCountComposer
 *
 * @package  Arcanesoft\Auth\ViewComposers\Dashboard
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class OnlineUsersCountComposer extends ViewComposer
{
    /* -----------------------------------------------------------------
     |  Constants
     | -----------------------------------------------------------------
     */
    const VIEW = 'auth::admin._composers.dashboard.online-users-count-box';

    /* -----------------------------------------------------------------
     |  Main Methods
     | -----------------------------------------------------------------
     */
    /**
     * Compose the view.
     *
     * @param  \Illuminate\Contracts\View\View  $view
     */
    public function compose(View $view)
    {
        $view->with('onlineUsersCount', $this->getOnlineUsers()->count());
    }

    /* -----------------------------------------------------------------
     |  Other Methods
     | -----------------------------------------------------------------
     */
    /**
     * Get the online users.
     *
     * @return \Illuminate\Database\Eloquent\Collection
     */
    private function getOnlineUsers()
    {
        $date = Carbon::now()->subMinutes(
            config('arcanesoft.auth.track-activity.minutes', 5)
        );

        return $this->getCachedUsers()->filter(function (User $user) use ($date) {
            return ! is_null($user->last_activity) && $user->last_activity->gte($date);
        });
    }
}


text:
"""Tests for clicking on messages."""

import re

from rust_test_common import *

REPLACEMENT_TESTS = [
    ('tests/error-tests/tests/cast-to-unsized-trait-object-suggestion.rs', None,
        # Before
        ((11, '    &1 as dyn Send;'),
         (15, '    Box::new(1) as dyn Send;')),
        # After
        ((11, '    &1 as &dyn Send;'),
         (15, '    Box::new(1) as Box<dyn Send>;')),
    ),
    ('tests/error-tests/tests/impl-generic-mismatch.rs', '>=1.28.0-beta',
        # Before
        ((20, '    fn foo<U: Debug>(&self, _: &U) { }'),
         (39, '    fn bar(&self, _: &impl Debug) { }')),
        # After
        ((20, '    fn foo(&self, _: &U) { }'),
         (20, '    fn foo(&self, _: &impl Debug) { }'),
         (39, '    fn bar(&self, _: &U) { }'),
         (39, '    fn bar<U: Debug>(&self, _: &U) { }')),
    ),
]

class TestClickHandler(TestBase):

    def test_accept_replacement(self):
        rustc_version = util.get_rustc_version(sublime.active_window(), plugin_path)
        for filename, version, before, after in REPLACEMENT_TESTS:
            if not version or semver.match(rustc_version, version):
                self._with_open_file(filename,
                    self._test_accept_replacement, before=before, after=after)

    def _test_accept_replacement(self, view, before, after):
        def get_line(lineno):
            pt = view.text_point(lineno, 0)
            line_r = view.line(pt)
            return view.substr(line_r)

        with UiIntercept(passthrough=True) as ui:
            e = plugin.SyntaxCheckPlugin.RustSyntaxCheckEvent()
            self._cargo_clean(view)
            e.on_post_save(view)
            self._get_rust_thread().join()
            for lineno, text in before:
                self.assertEqual(get_line(lineno), text)
            phantoms = ui.phantoms[view.file_name()]
            phantoms.sort(key=lambda x: x['region'])
            # Filter out just the "Accept Replacement" phantoms.
            click_urls = []
            for phantom in phantoms:
                click_urls.extend(re.findall(r'<a .*href="(replace:[^"]+)"',
                    phantom['content']))
            self.assertEqual(len(click_urls), len(after))
            for url, (lineno, expected_line) in zip(click_urls, after):
                phantom['on_navigate'](url)
                self.assertEqual(get_line(lineno), expected_line)


text:
module Highbrow
  module Neural
    module Trainer
      module Plugin
        # Represents base plugin
        class Base
          attr_accessor :trainer

          def init
          end

          def pre_epoch
          end

          def post_epoch
          end

          def pre_train
          end

          def post_train
          end
        end
      end
    end
  end
end


text:
package net.greghaines.jesque.meta.dao.impl;

import static net.greghaines.jesque.ConfigBuilder.DEFAULT_NAMESPACE;
import static net.greghaines.jesque.utils.ResqueConstants.COLON;
import static net.greghaines.jesque.utils.ResqueConstants.QUEUES;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import net.greghaines.jesque.Config;
import net.greghaines.jesque.ConfigBuilder;
import net.greghaines.jesque.Job;
import net.greghaines.jesque.json.ObjectMapperFactory;
import net.greghaines.jesque.meta.KeyType;
import net.greghaines.jesque.meta.QueueInfo;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.concurrent.Synchroniser;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.fasterxml.jackson.core.JsonProcessingException;

import redis.clients.jedis.Jedis;
import redis.clients.util.Pool;

public class TestQueueInfoDAORedisImpl {

    private static final String QUEUES_KEY = DEFAULT_NAMESPACE + COLON + QUEUES;

    private Mockery mockCtx;
    private Pool<Jedis> pool;
    private Jedis jedis;
    private QueueInfoDAORedisImpl qInfoDAO;

    @SuppressWarnings("unchecked")
    @Before
    public void setUp() {
        this.mockCtx = new JUnit4Mockery();
        this.mockCtx.setImposteriser(ClassImposteriser.INSTANCE);
        this.mockCtx.setThreadingPolicy(new Synchroniser());
        this.pool = this.mockCtx.mock(Pool.class);
        this.jedis = this.mockCtx.mock(Jedis.class);
        this.qInfoDAO = new QueueInfoDAORedisImpl(new ConfigBuilder().build(), this.pool);
    }

    @After
    public void tearDown() {
        this.mockCtx.assertIsSatisfied();
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructor_NullConfig() {
        new QueueInfoDAORedisImpl(null, null);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructor_NullPool() {
        final Config config = new ConfigBuilder().build();
        new QueueInfoDAORedisImpl(config, null);
    }

    @Test
    public void testGetQueueNames() {
        final Set<String> queueSet = new HashSet<String>(Arrays.asList("queue1", "queue2"));
        final List<String> origQueueNames = new ArrayList<String>(queueSet);
        Collections.sort(origQueueNames);
        this.mockCtx.checking(new Expectations(){{
            oneOf(pool).getResource(); will(returnValue(jedis));
            oneOf(jedis).smembers(QUEUES_KEY); will(returnValue(queueSet));
            oneOf(pool).returnResource(jedis);
        }});
        final List<String> queueNames = this.qInfoDAO.getQueueNames();
        Assert.assertNotNull(queueNames);
        Assert.assertEquals(queueSet.size(), queueNames.size());
        Assert.assertTrue(queueNames.containsAll(queueSet));
        Assert.assertEquals(origQueueNames, queueNames);
    }

    @Test
    public void testGetPendingCount() {
        final Map<String,Long> queueCountMap = new HashMap<String,Long>(2);
        queueCountMap.put("queue1", 3L);
        queueCountMap.put("queue2", 5L);
        final Map<String,String> queueTypeMap = new HashMap<String,String>(2);
        queueTypeMap.put("queue1", KeyType.LIST.toString());
        queueTypeMap.put("queue2", KeyType.ZSET.toString());
        this.mockCtx.checking(new Expectations(){{
            exactly(2).of(pool).getResource(); will(returnValue(jedis));
            oneOf(jedis).smembers(QUEUES_KEY); will(returnValue(queueCountMap.keySet()));
            for (final Entry<String,String> e : queueTypeMap.entrySet()) {
                final String queueKey = "resque:queue:" + e.getKey();
                oneOf(jedis).type(queueKey); will(returnValue(e.getValue()));
                if (KeyType.ZSET.toString().equals(e.getValue())) {
                    oneOf(jedis).zcard(queueKey); will(returnValue(queueCountMap.get(e.getKey())));
                } else {
                    oneOf(jedis).llen(queueKey); will(returnValue(queueCountMap.get(e.getKey())));
                }
            }
            exactly(2).of(pool).returnResource(jedis);
        }});
        final long pendingCount = this.qInfoDAO.getPendingCount();
        Assert.assertEquals(8, pendingCount);
    }

    @Test
    public void testGetProcessedCount() {
        final Long count = 5L;
        this.mockCtx.checking(new Expectations(){{
            oneOf(pool).getResource(); will(returnValue(jedis));
            oneOf(jedis).get("resque:stat:processed"); will(returnValue(Long.toString(count)));
            oneOf(pool).returnResource(jedis);
        }});
        final long processedCount = this.qInfoDAO.getProcessedCount();
        Assert.assertEquals(count, (Long)processedCount);
    }

    @Test
    public void testGetProcessedCount_Null() {
        this.mockCtx.checking(new Expectations(){{
            oneOf(pool).getResource(); will(returnValue(jedis));
            oneOf(jedis).get("resque:stat:processed"); will(returnValue(null));
            oneOf(pool).returnResource(jedis);
        }});
        final long processedCount = this.qInfoDAO.getProcessedCount();
        Assert.assertEquals(0L, processedCount);
    }

    @Test
    public void testRemoveQueue() {
        final String queue = "queue1";
        this.mockCtx.checking(new Expectations(){{
            oneOf(pool).getResource(); will(returnValue(jedis));
            oneOf(jedis).srem(QUEUES_KEY, queue);
            oneOf(jedis).del("resque:queue:" + queue);
            oneOf(pool).returnResource(jedis);
        }});
        this.qInfoDAO.removeQueue(queue);
    }

    @Test
    public void testGetQueueInfos() {
        final Map<String,Long> queueCountMap = new HashMap<String,Long>(2);
        queueCountMap.put("queue1", 3L);
        queueCountMap.put("queue2", 5L);
        final Map<String,String> queueTypeMap = new HashMap<String,String>(2);
        queueTypeMap.put("queue1", KeyType.LIST.toString());
        queueTypeMap.put("queue2", KeyType.ZSET.toString());
        this.mockCtx.checking(new Expectations(){{
            exactly(2).of(pool).getResource(); will(returnValue(jedis));
            oneOf(jedis).smembers(QUEUES_KEY); will(returnValue(queueCountMap.keySet()));
            for (final Entry<String,String> e : queueTypeMap.entrySet()) {
                final String queueKey = "resque:queue:" + e.getKey();
                oneOf(jedis).type(queueKey); will(returnValue(e.getValue()));
                if (KeyType.ZSET.toString().equals(e.getValue())) {
                    oneOf(jedis).zcard(queueKey); will(returnValue(queueCountMap.get(e.getKey())));
                } else {
                    oneOf(jedis).llen(queueKey); will(returnValue(queueCountMap.get(e.getKey())));
                }
            }
            exactly(2).of(pool).returnResource(jedis);
        }});
        final List<QueueInfo> queueInfos = this.qInfoDAO.getQueueInfos();
        Assert.assertNotNull(queueInfos);
        Assert.assertEquals(queueCountMap.size(), queueInfos.size());
        for (final QueueInfo queueInfo : queueInfos) {
            Assert.assertTrue(queueCountMap.containsKey(queueInfo.getName()));
            Assert.assertEquals(queueCountMap.get(queueInfo.getName()), queueInfo.getSize());
        }
    }

    @Test
    public void testGetQueueInfo_List() throws JsonProcessingException {
        final String name = "queue1";
        final String queueKey = "resque:queue:" + name;
        final long jobOffset = 1;
        final long jobCount = 2;
        final long size = 4;
        final Collection<String> payloads = new ArrayList<String>();
        payloads.add(ObjectMapperFactory.get().writeValueAsString(new Job("foo")));
        payloads.add(ObjectMapperFactory.get().writeValueAsString(new Job("bar")));
        this.mockCtx.checking(new Expectations(){{
            oneOf(pool).getResource(); will(returnValue(jedis));
            exactly(2).of(jedis).type(queueKey); will(returnValue(KeyType.LIST.toString()));
            oneOf(jedis).llen(queueKey); will(returnValue(size));
            oneOf(jedis).lrange(queueKey, jobOffset, jobOffset + jobCount - 1); will(returnValue(payloads));
            oneOf(pool).returnResource(jedis);
        }});
        final QueueInfo queueInfo = this.qInfoDAO.getQueueInfo(name, jobOffset, jobCount);
        Assert.assertNotNull(queueInfo);
        Assert.assertEquals(name, queueInfo.getName());
        Assert.assertEquals((Long) size, queueInfo.getSize());
        final List<Job> jobs = queueInfo.getJobs();
        Assert.assertNotNull(jobs);
        Assert.assertEquals(payloads.size(), jobs.size());
    }

    @Test
    public void testGetQueueInfo_ZSet() throws JsonProcessingException {
        final String name = "queue1";
        final String queueKey = "resque:queue:" + name;
        final long jobOffset = 1;
        final long jobCount = 2;
        final long size = 4;
        final Collection<String> payloads = new HashSet<String>();
        payloads.add(ObjectMapperFactory.get().writeValueAsString(new Job("foo")));
        payloads.add(ObjectMapperFactory.get().writeValueAsString(new Job("bar")));
        this.mockCtx.checking(new Expectations(){{
            oneOf(pool).getResource(); will(returnValue(jedis));
            exactly(2).of(jedis).type(queueKey); will(returnValue(KeyType.ZSET.toString()));
            oneOf(jedis).zcard(queueKey); will(returnValue(size));
            oneOf(jedis).zrange(queueKey, jobOffset, jobOffset + jobCount - 1); will(returnValue(payloads));
            oneOf(pool).returnResource(jedis);
        }});
        final QueueInfo queueInfo = this.qInfoDAO.getQueueInfo(name, jobOffset, jobCount);
        Assert.assertNotNull(queueInfo);
        Assert.assertEquals(name, queueInfo.getName());
        Assert.assertEquals((Long) size, queueInfo.getSize());
        final List<Job> jobs = queueInfo.getJobs();
        Assert.assertNotNull(jobs);
        Assert.assertEquals(payloads.size(), jobs.size());
    }
}


text:
template<class ExecutionPolicy>
void test()
{
  using execution_policy_type = ExecutionPolicy;

  {
    // bulk_invoke with no parameters

    execution_policy_type policy;
    auto exec = policy.executor();

    auto result = agency::bulk_invoke(policy(10),
      [](typename execution_policy_type::execution_agent_type& self) -> agency::single_result<int>
    {
      if(self.index() == 0)
      {
        return 7;
      }

      return std::ignore;
    });

    assert(result == 7);
  }

  {
    // bulk_invoke with one parameter

    execution_policy_type policy;

    int val = 13;

    auto result = agency::bulk_invoke(policy(10),
      [](typename execution_policy_type::execution_agent_type& self, int val) -> agency::single_result<int>
    {
      if(self.index() == 0)
      {
        return val;
      }

      return std::ignore;
    },
    val);

    assert(result == 13);
  }

  {
    // bulk_invoke with one shared parameter

    execution_policy_type policy;

    int val = 13;

    auto result = agency::bulk_invoke(policy(10),
      [](typename execution_policy_type::execution_agent_type& self, int& val) -> agency::single_result<int>
    {
      if(self.index() == 0)
      {
        return val;
      }

      return std::ignore;
    },
    agency::share(val));

    assert(result == 13);
  }
}

int main()
{
  test<agency::sequenced_execution_policy>();
  test<agency::concurrent_execution_policy>();
  test<agency::parallel_execution_policy>();

  std::cout << "OK" << std::endl;

  return 0;
}


text: Your new password is "<?php echo $password; ?>".


text:
$(function() {
    $('.js-datepicker').datepicker({
        format: "dd/mm/yyyy",
        endDate: "today",
        language: "fr",
        orientation: "bottom auto",
        autoclose: true
    });
});


text:
var debug = false;

var movingWithHead = false;
var headStartPosition, headStartDeltaPitch, headStartFinalPitch, headStartRoll, headStartYaw;

var HEAD_MOVE_DEAD_ZONE = 0.0;
var HEAD_STRAFE_DEAD_ZONE = 0.0;
var HEAD_ROTATE_DEAD_ZONE = 0.0;
var HEAD_THRUST_FWD_SCALE = 12000.0;
var HEAD_THRUST_STRAFE_SCALE = 2000.0;
var HEAD_YAW_RATE = 1.0;
var HEAD_PITCH_RATE = 1.0;
var HEAD_ROLL_THRUST_SCALE = 75.0;
var HEAD_PITCH_LIFT_THRUST = 3.0;
var WALL_BOUNCE = 4000.0;

//  If these values are set to something
var maxVelocity = 1.25;
var noFly = true;

//var roomLimits = { xMin: 618, xMax: 635.5, zMin: 528, zMax: 552.5 };
var roomLimits = { xMin: -1, xMax: 0, zMin: 0, zMax: 0 };

function isInRoom(position) {
    var BUFFER = 2.0;
    if (roomLimits.xMin < 0) {
        return false;
    }
    if ((position.x > (roomLimits.xMin - BUFFER)) &&
        (position.x < (roomLimits.xMax + BUFFER)) &&
        (position.z > (roomLimits.zMin - BUFFER)) &&
        (position.z < (roomLimits.zMax + BUFFER)))
    {
        return true;
    } else {
        return false;
    }
}

function moveWithHead(deltaTime) {
    var thrust = { x: 0, y: 0, z: 0 };
    var position = MyAvatar.position;
    if (movingWithHead) {
        var deltaYaw = MyAvatar.getHeadFinalYaw() - headStartYaw;
        var deltaPitch = MyAvatar.getHeadDeltaPitch() - headStartDeltaPitch;
        var deltaRoll = MyAvatar.getHeadFinalRoll() - headStartRoll;
        var velocity = MyAvatar.getVelocity();
        var bodyLocalCurrentHeadVector = Vec3.subtract(MyAvatar.getHeadPosition(), MyAvatar.position);
        bodyLocalCurrentHeadVector = Vec3.multiplyQbyV(Quat.angleAxis(-deltaYaw, {x:0, y: 1, z:0}), bodyLocalCurrentHeadVector);
        var headDelta = Vec3.subtract(bodyLocalCurrentHeadVector, headStartPosition);
        headDelta = Vec3.multiplyQbyV(Quat.inverse(Camera.getOrientation()), headDelta);
        headDelta.y = 0.0;   //  Don't respond to any of the vertical component of head motion

        var forward = Quat.getFront(Camera.getOrientation());
        var right = Quat.getRight(Camera.getOrientation());
        var up = Quat.getUp(Camera.getOrientation());
        if (noFly) {
            forward.y = 0.0;
            forward = Vec3.normalize(forward);
            right.y = 0.0;
            right = Vec3.normalize(right);
            up = { x: 0, y: 1, z: 0};
        }

        //  Thrust based on leaning forward and side-to-side
        if (Math.abs(headDelta.z) > HEAD_MOVE_DEAD_ZONE) {
            if (Math.abs(Vec3.dot(velocity, forward)) < maxVelocity) {
                thrust = Vec3.sum(thrust, Vec3.multiply(forward, -headDelta.z * HEAD_THRUST_FWD_SCALE * deltaTime));
            }
        }
        if (Math.abs(headDelta.x) > HEAD_STRAFE_DEAD_ZONE) {
            if (Math.abs(Vec3.dot(velocity, right)) < maxVelocity) {
                thrust = Vec3.sum(thrust, Vec3.multiply(right, headDelta.x * HEAD_THRUST_STRAFE_SCALE * deltaTime));
            }
        }
        if (Math.abs(deltaYaw) > HEAD_ROTATE_DEAD_ZONE) {
            var orientation = Quat.multiply(Quat.angleAxis((deltaYaw + deltaRoll) * HEAD_YAW_RATE * deltaTime, {x:0, y: 1, z:0}), MyAvatar.orientation);
            MyAvatar.orientation = orientation;
        }
        //  Thrust Up/Down based on head pitch
        if (!noFly) {
            if ((Math.abs(Vec3.dot(velocity, up)) < maxVelocity)) {
                thrust = Vec3.sum(thrust, Vec3.multiply({ x:0, y:1, z:0 }, (MyAvatar.getHeadFinalPitch() - headStartFinalPitch) * HEAD_PITCH_LIFT_THRUST * deltaTime));
            }
        }
        //  For head trackers, adjust pitch by head pitch
        MyAvatar.headPitch += deltaPitch * HEAD_PITCH_RATE * deltaTime;

    }
    if (isInRoom(position)) {
        // Impose constraints to keep you in the space
        if (position.x < roomLimits.xMin) {
            thrust.x += (roomLimits.xMin - position.x) * WALL_BOUNCE * deltaTime;
        } else if (position.x > roomLimits.xMax) {
            thrust.x += (roomLimits.xMax - position.x) * WALL_BOUNCE * deltaTime;
        }
        if (position.z < roomLimits.zMin) {
            thrust.z += (roomLimits.zMin - position.z) * WALL_BOUNCE * deltaTime;
        } else if (position.z > roomLimits.zMax) {
            thrust.z += (roomLimits.zMax - position.z) * WALL_BOUNCE * deltaTime;
        }
    }

    // Check against movement box limits

    MyAvatar.addThrust(thrust);
}

Controller.keyPressEvent.connect(function(event) {
    if (event.text == "SPACE" && !movingWithHead) {
        movingWithHead = true;
        headStartPosition = Vec3.subtract(MyAvatar.getHeadPosition(), MyAvatar.position);
        headStartDeltaPitch = MyAvatar.getHeadDeltaPitch();
        headStartFinalPitch = MyAvatar.getHeadFinalPitch();
        headStartRoll = MyAvatar.getHeadFinalRoll();
        headStartYaw = MyAvatar.getHeadFinalYaw();
    }
});
Controller.keyReleaseEvent.connect(function(event) {
    if (event.text == "SPACE") {
        movingWithHead = false;
    }
});

Script.update.connect(moveWithHead);


text:
package com.pdfjet;

class LangSysRecord {
    byte[] langSysTag;  // 4-byte LangSysTag identifier
    int langSysOffset;  // Offset to LangSys table-from beginning of Script table
}


text:
package br.com.touchtec.mockspi;

public interface Thrower<E extends Exception> {

	public void run() throws E;

}


text:
<?php $this->load->view('admin/support/_common'); ?>

	<form class="form" id="form" action="<?php echo $action; ?>" method="post">
		<fieldset>

					<img src="<?php echo public_url('admin'); ?>/images/icons/dark/add.png" class="titleIcon" />

<?php echo lang('edit'); ?> <?php echo lang('mod_support'); ?>

					<?php echo lang('name'); ?>:*

						<input name="name" id="param_name" value='<?php echo $info->name?>' _autocheck="true" type="text" />

					<?php echo lang('phone'); ?>:*

						<input name="phone" id="param_phone" value='<?php echo $info->phone?>'  _autocheck="true" type="text" />

					<?php echo lang('yahoo'); ?>:

						<input name="yahoo" id="param_yahoo" value='<?php echo $info->yahoo?>'  type="text" />

					<?php echo lang('email'); ?>:

						<input name="gmail" id="param_gmail" value='<?php echo $info->gmail?>'  type="text" />

					<?php echo lang('skype'); ?>:

						<input name="skype" id="param_skype" value='<?php echo $info->skype?>'  type="text" />

					<?php echo lang('sort_order'); ?>:

						<input name="sort_order" id="param_sort_order"  class="left" value='<?php echo $info->sort_order?>'  style="width:100px;" type="text" />

           			<input type="submit" value="<?php echo lang('button_update'); ?>" class="redB" />
           			<input type="reset" value="<?php echo lang('button_reset'); ?>" class="basic" />

		</fieldset>
	</form>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Okada, Seifert, Takematsu, Miyazaki & Tubaki, Can. J. Bot. 76(9): 1504 (1999)

#### Original name
Ceratocystis columnaris Olchow. & J. Reid

### Remarks
null


text:
#include <inviwo/qt/editor/inviwoaboutwindow.h>
#include <inviwo/qt/editor/inviwomainwindow.h>
#include <inviwo/core/util/stdextensions.h>
#include <inviwo/core/util/stringconversion.h>
#include <inviwo/core/util/systemcapabilities.h>
#include <inviwo/core/common/inviwomodulefactoryobject.h>
#include <modules/qtwidgets/inviwoqtutils.h>
#include <inviwo/core/util/document.h>
#include <inviwo/core/util/filesystem.h>
#include <inviwo/core/common/inviwomodule.h>
#include <modules/qtwidgets/inviwoqtutils.h>

#include <warn/push>
#include <warn/ignore/all>
#include <QFrame>
#include <QVBoxLayout>
#include <QString>
#include <QTextBrowser>
#include <QByteArray>
#include <QBuffer>
#include <QImage>
#include <QUrl>
#include <QUrlQuery>
#include <warn/pop>

namespace inviwo {

namespace {
class AboutBrowser : public QTextBrowser {
public:
    AboutBrowser(QWidget* parent) : QTextBrowser(parent) {}
    virtual ~AboutBrowser() = default;

protected:
    // Override this to circumvent a warning message from QTextBrowser::loadResource
    // QTextBrowser has an internal QTextDocument that has a loadResource function that does the
    // right thing, but first it calls the overload from it's parent QTextBrowers which fails with a
    // message. We overload that and just return an empty QVariant and let QTextDocument handle it.
    virtual QVariant loadResource(int, const QUrl&) override { return QVariant{}; }
};

}  // namespace

InviwoAboutWindow::InviwoAboutWindow(InviwoMainWindow* mainwindow)
    : InviwoDockWidget("About", mainwindow, "AboutWidget") {

    setAllowedAreas(Qt::LeftDockWidgetArea | Qt::RightDockWidgetArea);
    resize(utilqt::emToPx(this, QSizeF(60, 60)));  // default size

    auto centralWidget = new QWidget();
    auto vLayout = new QVBoxLayout(centralWidget);
    vLayout->setSpacing(utilqt::refSpacePx(this));
    vLayout->setContentsMargins(0, 0, 0, 0);

    auto app = mainwindow->getInviwoApplication();

    auto textdoc = new AboutBrowser(this);
    vLayout->addWidget(textdoc);
    centralWidget->setLayout(vLayout);
    setWidget(centralWidget);

    textdoc->setReadOnly(true);
    textdoc->setUndoRedoEnabled(false);
    textdoc->setAcceptRichText(false);
    textdoc->setOpenExternalLinks(true);

    auto& syscap = app->getSystemCapabilities();
    auto buildYear = syscap.getBuildInfo().year;

    using P = Document::PathComponent;
    using H = utildoc::TableBuilder::Header;

    auto escape = [](const std::string& str) -> std::string {
        return utilqt::fromQString(utilqt::toQString(str).toHtmlEscaped());
    };

    auto makeImg = [](QString path, int size) {
        const auto img = QImage(path);
        QByteArray imgData;
        QBuffer buffer(&imgData);
        buffer.open(QIODevice::WriteOnly);
        const auto scaledImg = img.scaledToHeight(size, Qt::SmoothTransformation);
        scaledImg.save(&buffer, "PNG");
        return std::unordered_map<std::string, std::string>{
            {"width", std::to_string(scaledImg.size().width())},
            {"height", std::to_string(scaledImg.size().height())},
            {"src", "data:image/png;base64," + std::string(imgData.toBase64().data())}};
    };

    auto makeBody = [](Document& doc) {
        auto html = doc.append("html");
        html.append("head").append(
            "style",
            "a { color: #c8ccd0; font-weight: normal; text-decoration:none;}\n"
            "body, table, div, p, dl "
            "{color: #9d9995; background-color: #323235; font: 400 14px/18px"
            "Calibra, sans-serif;}\n "
            "h1, h2, h3, h4 {color: #c8ccd0; margin-bottom:3px;}");
        return html.append("body", "", {{"style", "margin: 7px;"}});
    };

    Document doc;
    auto body = makeBody(doc);
    {
        auto table = body.append("table").append("tr");

        table.append("td").append("img", "", makeImg(":/inviwo/inviwo-logo-light-600px.png", 128));

        auto cell = table.append("td");
        cell.append("h1", "Inviwo", {{"style", "color:white;"}});
        cell.append("p", "Interactive Visualization Workshop. Version " + IVW_VERSION);
        cell.append("p", "© 2012-" + toString(buildYear) + " The Inviwo Foundation");
        cell.append("a", "http://www.inviwo.org", {{"href", "http://www.inviwo.org"}});
        cell.append("p",
                    "Inviwo is a rapid prototyping environment for interactive "
                    "visualizations. It is licensed under the Simplified BSD license.");
    }
    {
        auto h = body.append("p");
        h.append("h3", "Core Team:");
        h.append("br");
        h.append("span",
                 "Peter Steneteg, Erik Sundén, Daniel Jönsson, Martin Falk, "
                 "Rickard Englund, Sathish Kottravel, Timo Ropinski");
    }
    {
        auto h = body.append("p");
        h.append("h3", "Contributors:");
        h.append("br");
        h.append("span",
                 "Robin Skånberg, Jochen Jankowai, Tino Weinkauf, "
                 "Wiebke Köpp, Anke Friederici, Dominik Engel, "
                 "Alexander Johansson, Andreas Valter, Johan Norén, Emanuel Winblad, "
                 "Hans-Christian Helltegen, Viktor Axelsson");
    }
    {
        auto h = body.append("p");
        h.append("h3", "Sponsors:");
        h.append("br");
        h.append("span",
                 "This work was supported by Linköping University, KTH Royal Institute of "
                 "Technology, Ulm University, and through grants from the Swedish e-Science "
                 "Research Centre (SeRC).");
        h.append("br");
        auto p = h.append("p");

        auto liu = p.append("a", "", {{"href", "http://www.liu.se"}});
        liu.append("img", "", makeImg(":/images/liu-white-crop.png", 50));

        auto kth = p.append("a", "", {{"href", "http://www.kth.se"}});
        kth.append("img", "", makeImg(":/images/kth.png", 50));

        auto serc = p.append("a", "", {{"href", "http://www.e-science.se"}});
        serc.append("img", "", makeImg(":/images/serc.png", 50));

        auto uulm = p.append("a", "", {{"href", "http://www.uni-ulm.de/en/"}});
        uulm.append("img", "", makeImg(":/images/uulm.png", 50));
    }
    {
        const auto& bi = syscap.getBuildInfo();
        auto h = body.append("p");
        h.append("h3", "Build Info: ");
        utildoc::TableBuilder tb(h, P::end());
        tb(H("Date"), bi.getDate());
        tb(H("Configuration"), bi.configuration);
        tb(H("Generator"), bi.generator);
        tb(H("Compiler"), bi.compiler + " " + bi.compilerVersion);
    }
    {
        auto h = body.append("p");
        h.append("h3", "Repos:");
        utildoc::TableBuilder tb(h, P::end());
        for (auto item : syscap.getBuildInfo().githashes) {
            tb(H(item.first), item.second);
        }
    }
    {
        auto h = body.append("p");
        h.append("h3", "Modules: ");
        h.append("br");
        const auto& mfos = app->getModuleManager().getModuleFactoryObjects();
        auto names = util::transform(
            mfos, [](const std::unique_ptr<InviwoModuleFactoryObject>& mfo) { return mfo->name; });
        std::sort(names.begin(), names.end());
        h.append("span", joinString(names, ", "));
    }
    {
        auto h = body.append("div");
        h.append("h3", "Qt Version: ");
        h.append("span", QT_VERSION_STR);
    }
    {
        auto h = body.append("p");
        h.append("h3", "Libraries: ");
        auto dl = h.append("dl");
        const auto& mfos = app->getModuleManager().getModuleFactoryObjects();
        for (auto& mfo : mfos) {
            for (auto& license : mfo->licenses) {
                QUrl url;
                url.setScheme("file");
                url.setHost("license.txt");
                QUrlQuery query;
                query.addQueryItem("module", utilqt::toQString(mfo->name));
                query.addQueryItem("id", utilqt::toQString(license.id));
                url.setQuery(query);
                auto dt = dl.append("dt");
                dt.append("b", license.name);
                dt += " ";
                dt.append("a", license.type, {{"href", utilqt::fromQString(url.url())}});
                auto dd = dl.append("dd", "", {{"style", "margin-bottom:10px;"}});
                if (!license.url.empty()) {
                    dd.append("a", license.url, {{"href", license.url}});
                    dd += " ";
                }
                if (license.version != Version{0, 0, 0, 0}) {
                    dd += toString(license.version);
                    dd += " ";
                }
                dd += "(" + license.module + ")";
            }
        }
    }

    std::string str = doc;
    textdoc->setHtml(utilqt::toQString(str));

    auto showLicense = [str, textdoc, app, escape, makeBody](const QUrl& url) {
        if (url.hasQuery()) {
            QUrlQuery query(url);
            auto module = utilqt::fromQString(query.queryItemValue("module"));
            auto id = utilqt::fromQString(query.queryItemValue("id"));

            const auto& mfos = app->getModuleManager().getModuleFactoryObjects();
            auto mit = util::find_if(mfos, [&](auto& m) { return m->name == module; });
            if (mit != mfos.end()) {
                auto it = util::find_if((*mit)->licenses, [&](auto& l) { return l.id == id; });
                if (it != (*mit)->licenses.end()) {
                    Document doc;
                    auto body = makeBody(doc);
                    auto li = body.append("div");
                    li.append("p").append("a", "Back", {{"href", "file://home.txt"}});
                    li.append("br");
                    li.append("b", it->name);
                    if (it->version != Version{0, 0, 0, 0}) {
                        li += toString(it->version);
                    }
                    if (!it->url.empty()) {
                        li.append("a", it->url, {{"href", it->url}});
                    }
                    auto mod = app->getModuleByIdentifier(module);
                    if (!mod) return;
                    auto path = mod->getPath();
                    for (auto& file : it->files) {
                        auto licfile = path + "/" + file;
                        if (!filesystem::fileExists(licfile)) {
                            // Look for an installed file
                            licfile = path + "/licenses/" + it->id + "-" +
                                      filesystem::getFileNameWithExtension(file);
                        }

                        auto f = filesystem::ifstream(licfile);
                        std::stringstream buffer;
                        buffer << f.rdbuf();
                        li.append("pre", escape(buffer.str()), {{"style", "font: 12px;"}});
                    }
                    textdoc->setHtml(utilqt::toQString(doc));
                    return;
                }
            }
        }
        textdoc->setHtml(utilqt::toQString(str));
    };

    connect(textdoc, &QTextBrowser::anchorClicked, this, showLicense);
}

}  // namespace inviwo


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

<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
All Classes (Apache Hadoop Auth Examples 2.3.0 API)
</TITLE>

<META NAME="date" CONTENT="2015-03-06">

<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">

All Classes

RequestLoggerFilter

WhoClient

WhoServlet


text:
package org.unitils.inject;

import static org.junit.Assert.assertSame;

import java.util.Properties;

import org.junit.Before;
import org.junit.Test;
import org.unitils.core.ConfigurationLoader;
import org.unitils.inject.annotation.InjectIntoStatic;

/**
 * Test for the static injection behavior of the {@link InjectModule}
 *
 * @author Filip Neven
 * @author Tim Ducheyne
 */
public class InjectModuleInjectIntoStaticTest {

    /* Tested object */
    InjectModule injectModule;

    TestInjectIntoStatic_simpleSetter testInjectIntoStatic_simpleSetter = new TestInjectIntoStatic_simpleSetter();
    TestInjectIntoStatic_simpleField testInjectIntoStatic_simpleField = new TestInjectIntoStatic_simpleField();
    TestInjectIntoStatic_compositeSetter testInjectIntoStatic_compositeSetter = new TestInjectIntoStatic_compositeSetter();
    TestInjectIntoStatic_compositeField testInjectIntoStatic_compositeField = new TestInjectIntoStatic_compositeField();

    /**
     * Initializes the test and test fixture.
     */
    @Before
    public void setUp() throws Exception {
        Properties configuration = new ConfigurationLoader().loadConfiguration();
        injectModule = new InjectModule();
        injectModule.init(configuration);
    }

    @Test
    public void testInject_simpleSetter() {
        injectModule.injectObjects(testInjectIntoStatic_simpleSetter);
        assertSame(testInjectIntoStatic_simpleSetter.toInject, InjectOnStatic.getToInject());
    }

    @Test
    public void testInject_simpleField() {
        injectModule.injectObjects(testInjectIntoStatic_simpleField);
        assertSame(testInjectIntoStatic_simpleField.toInject, InjectOnStatic.getToInjectField());
    }

    @Test
    public void testInject_compositeSetter() {
        injectModule.injectObjects(testInjectIntoStatic_compositeSetter);
        assertSame(testInjectIntoStatic_compositeSetter.toInject, InjectOnStatic.getTestObject().getToInject());
    }

    @Test
    public void testInject_compositeField() {
        injectModule.injectObjects(testInjectIntoStatic_compositeField);
        assertSame(testInjectIntoStatic_compositeField.toInject, InjectOnStatic.getTestObjectField().getToInject());
    }

    public class TestInjectIntoStatic_simpleSetter {

        @InjectIntoStatic(target = InjectOnStatic.class, property = "toInject")
        private ToInject toInject;

        public TestInjectIntoStatic_simpleSetter() {
            toInject = new ToInject();
        }
    }

    public class TestInjectIntoStatic_simpleField {

        @InjectIntoStatic(target = InjectOnStatic.class, property = "toInjectField")
        private ToInject toInject;

        public TestInjectIntoStatic_simpleField() {
            toInject = new ToInject();
        }
    }

    public class TestInjectIntoStatic_compositeSetter {

        @InjectIntoStatic(target = InjectOnStatic.class, property = "testObject.toInject")
        private ToInject toInject;

        public TestInjectIntoStatic_compositeSetter() {
            toInject = new ToInject();
        }
    }

    public class TestInjectIntoStatic_compositeField {

        @InjectIntoStatic(target = InjectOnStatic.class, property = "testObjectField.toInject")
        private ToInject toInject;

        public TestInjectIntoStatic_compositeField() {
            toInject = new ToInject();
        }
    }

    private static class InjectOnStatic {

        private static ToInject toInject;

        private static ToInject toInjectField;

        private static TestObject testObject;

        private static TestObject testObjectField;

        static {
            testObject = new TestObject();
            testObjectField = new TestObject();
        }

        public static void setToInject(ToInject toInject) {
            InjectOnStatic.toInject = toInject;
        }

        public static void setTestObject(TestObject testObject) {
            InjectOnStatic.testObject = testObject;
        }

        public static ToInject getToInject() {
            return toInject;
        }

        public static ToInject getToInjectField() {
            return toInjectField;
        }

        public static TestObject getTestObject() {
            return testObject;
        }

        public static TestObject getTestObjectField() {
            return testObjectField;
        }
    }

    public static class TestObject {

        private ToInject toInject;

        public void setToInject(ToInject toInject) {
            this.toInject = toInject;
        }

        public ToInject getToInject() {
            return toInject;
        }
    }

    public static class ToInject {
    }

}


text:
package server

import (
	pb "github.com/micro/micro/v3/proto/config"
	"github.com/micro/micro/v3/service"
	"github.com/micro/micro/v3/service/config/handler"
	"github.com/micro/micro/v3/service/logger"
	"github.com/micro/micro/v3/service/store"
	"github.com/urfave/cli/v2"
)

const (
	name    = "config"
	address = ":8001"
)

var (
	// Flags specific to the config service
	Flags = []cli.Flag{
		&cli.StringFlag{
			Name:    "watch_topic",
			EnvVars: []string{"MICRO_CONFIG_SECRET_KEY"},
			Usage:   "watch the change event.",
		},
	}
)

// Run micro config
func Run(c *cli.Context) error {
	srv := service.New(
		service.Name(name),
		service.Address(address),
	)

	store.DefaultStore.Init(store.Table("config"))

	// register the handler
	pb.RegisterConfigHandler(srv.Server(), handler.NewConfig(c.String("config_secret_key")))
	// register the subscriber
	//srv.Subscribe(watchTopic, new(watcher))

	if err := srv.Run(); err != nil {
		logger.Fatal(err)
	}
	return nil
}


text:
<resources>
    <string name="app_name">CrmSdk2015</string>
</resources>


text:
local ccpaw = {}

local sCache = "/var/cache/cc-paw/sources/"
local iCache = "/var/cache/cc-paw/installed/"
local logFile = "/var/log/cc-paw.log"
local errFile = "/var/log/cc-paw-errors.log"

local function p(...)
  local args = {...}
  local out = ""

  for i = 1, #args do
    out = out .. "\t" .. args[i]
  end

  local file = fs.open(logFile, fs.exists(logFile) and 'a' or 'w')

  file.write(out .."\n")
  file.close()
end

local function e(msg)
  local file = fs.open(errFile, fs.exists(errFile) and 'a' or 'w')

  file.write(msg.."\n")
  file.close()

  error(msg)
end

local function a(truthy, errMsg)
  if truthy then
    return truthy
  else
    e(errMsg)
  end
end

local function open(file, mode)
  return a(fs.open(file, mode), 'Could not open "'..file..'" in "'..mode..'" mode.')
end

local function write(fName, data)
  p("Writing to \"" .. fName .. "\"...")
  local file = open(fName, 'w')
  file.write(data)
  file.close()
end

local function get(url)
  local response = a(http.get(url, {["User-Agent"] = "cc-paw installer"}), 'Error opening "' .. url .. '"')

  local status = response.getResponseCode()
  if status == 200 then
    local result = response.readAll()
    response.close()
    return result
  else
    e('GET ' .. url .. ' : ' .. status)
  end
end

function ccpaw.install(pkgName, version)
  local root, pkgVersion = "https://cc-paw.github.io/cc-paw/releases/", version

  if not version then
    local file = open(sCache.."1", 'r')

    local line = file.readLine()
    while line do
      if line:sub(1, line:find("=")-1) == pkgName then
        pkgVersion = line:sub(line:find("=")+1)
        break
      end
      line = file.readLine()
    end

    file.close()
  end

  local pkgData = get(root..pkgName.."/"..pkgVersion.."/pkg.lua")
  local package = textutils.unserialize(pkgData)

  a(package.confVersion > 1, "Something impossible happened, start over entirely: https://cc-paw.github.io/")
  a(package.confVersion == 2, "You must download a newer installer: https://cc-paw.github.io/")

  if package.depends then
    for pkg, vers in pairs(package.depends) do
      ccpaw.install(pkg)
    end
  end

  if package.preinst then
    ok, result, msg = pcall(loadstring(package.preinst)())

    if not ok then
      e('Pre-install script errored: "'..result..'"\nAborting installation.')
    end
    if not result == 0 then
      e('Pre-install script failed: "'..msg..'"\nAborting installation.')
    end
  end

  if package.files then
    for fName, location in pairs(package.files) do
      local data = get(root..pkgName.."/"..pkgVersion.."/"..location)
      write(fName, data)
    end
  end

  if package.filesOnce then
    for fName, location in pairs(package.filesOnce) do
      if not fs.exists(fName) then
        local data = get(root..pkgName.."/"..pkgVersion.."/"..location)
        write(fName, data)
      end
    end
  end

  if package.postinst then
    ok, result, msg = pcall(loadstring(package.postinst)())

    if not ok then
      e('Post-install script errored: "'..result..'"\nAborting installation.')
    end
    if not result == 0 then
      e('Post-install script failed: "'..msg..'"\nAborting installation.')
    end
  end

  write(iCache..pkgName, pkgData)
end

function ccpaw.update()
  local data = get("https://cc-paw.github.io/cc-paw/releases/packages.list")
  write(sCache.."1", data)
end

print "Installing CC-PAW..."
ccpaw.update()
ccpaw.install("cc-paw", ...)
shell.run("/startup")
print "Done. :D"
print "(It is recommended to run 'cc-paw install cc-paw-installer' to get a copy of the installer script for recovering from CC-PAW issues.)"


text:
package org.hisp.dhis.hibernate;

import java.util.Properties;

import org.springframework.beans.factory.FactoryBean;

/**
 * @author Lars Helge Overland
 * @version $Id$
 */
public class HibernatePropertiesFactoryBean
    implements FactoryBean<Properties>
{
    // -------------------------------------------------------------------------
    // Dependencies
    // -------------------------------------------------------------------------

    private HibernateConfigurationProvider hibernateConfigurationProvider;

    public void setHibernateConfigurationProvider( HibernateConfigurationProvider hibernateConfigurationProvider )
    {
        this.hibernateConfigurationProvider = hibernateConfigurationProvider;
    }

    // -------------------------------------------------------------------------
    // FactoryBean implementation
    // -------------------------------------------------------------------------

    @Override
    public Properties getObject()
        throws Exception
    {
        return hibernateConfigurationProvider.getConfiguration().getProperties();
    }

    @Override
    public Class<Properties> getObjectType()
    {
        return Properties.class;
    }

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


text:
layout 'normal'

# Set a custom var for use in our layout
@page_title = 'A sample page'


text:
package de.heikoseeberger.akkasse

import org.scalatest.prop.GeneratorDrivenPropertyChecks
import org.scalatest.{ Matchers, WordSpec }

class ServerSentEventSpec
    extends WordSpec
    with Matchers
    with GeneratorDrivenPropertyChecks {

  "Creating a ServerSentEvent" should {
    "throw an IllegalArgumentException if the event type contains a \n or \r character" in {
      an[IllegalArgumentException] should be thrownBy ServerSentEvent(
        Some("data"),
        Some("event-type\n")
      )
      an[IllegalArgumentException] should be thrownBy ServerSentEvent(
        Some("data"),
        Some("event-type\revent-type")
      )
      an[IllegalArgumentException] should be thrownBy ServerSentEvent(
        Some("data"),
        id = Some("id\n")
      )
      an[IllegalArgumentException] should be thrownBy ServerSentEvent(
        Some("data"),
        retry = Some(-1)
      )
    }
  }

  "Calling toString" should {
    "return a single data line for single line message" in {
      val event = ServerSentEvent(Some(" "))
      event.toString shouldBe "data:  \n\n"
    }

    "return multiple data lines for a multi-line message" in {
      val event = ServerSentEvent(Some("line1\nline2\n"))
      event.toString shouldBe "data: line1\ndata: line2\ndata: \n\n"
    }

    "return multiple data lines and an event line for a multi-line message with a defined event type" in {
      val event = ServerSentEvent(Some("line1\nline2"), Some("event-type"))
      event.toString shouldBe "data: line1\ndata: line2\nevent: event-type\n\n"
    }

    "return a single id field after the data fields" in {
      val event = ServerSentEvent(Some("line1"), None, Some("1"))
      event.toString shouldBe "data: line1\nid: 1\n\n"
    }

    "return a single retry field after the data fields" in {
      val event = ServerSentEvent(Some("line1"), None, None, Some(42))
      event.toString shouldBe "data: line1\nretry: 42\n\n"
    }
  }

  "Calling toByteString" should {
    "return a correctly converted ByteString" in {
      forAll { (data: String) =>
        val event = ServerSentEvent(Some(data))
        event.encode.utf8String shouldBe event.toString
      }
    }
  }
}


text:
class BasicTessellation : public D3DApp
{
public:
	BasicTessellation(HINSTANCE hInstance);
	~BasicTessellation();

	bool Init();
	void OnResize();
	void UpdateScene(float dt);
	void DrawScene();

	void OnMouseDown(WPARAM btnState, int x, int y);
	void OnMouseUp(WPARAM btnState, int x, int y);
	void OnMouseMove(WPARAM btnState, int x, int y);

private:
	void BuildQuadPatchBuffer();

private:
	ID3D11Buffer* mQuadPatchVB;

	XMFLOAT4X4 mView;
	XMFLOAT4X4 mProj;

	XMFLOAT3 mEyePosW;

	float mTheta;
	float mPhi;
	float mRadius;

	POINT mLastMousePos;
};

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance,
				   PSTR cmdLine, int showCmd)
{
	// Enable run-time memory check for debug builds.
#if defined(DEBUG) | defined(_DEBUG)
	_CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif

	BasicTessellation theApp(hInstance);

	if( !theApp.Init() )
		return 0;

	return theApp.Run();
}

BasicTessellation::BasicTessellation(HINSTANCE hInstance)
: D3DApp(hInstance), mQuadPatchVB(0),
  mEyePosW(0.0f, 0.0f, 0.0f), mTheta(1.3f*MathHelper::Pi), mPhi(0.4f*MathHelper::Pi), mRadius(80.0f)
{
	mMainWndCaption = L"Bezier Surface Demo";
	mEnable4xMsaa = false;

	mLastMousePos.x = 0;
	mLastMousePos.y = 0;

	XMMATRIX I = XMMatrixIdentity();
	XMStoreFloat4x4(&mView, I);
	XMStoreFloat4x4(&mProj, I);
}

BasicTessellation::~BasicTessellation()
{
	md3dImmediateContext->ClearState();
	ReleaseCOM(mQuadPatchVB);

	Effects::DestroyAll();
	InputLayouts::DestroyAll();
	RenderStates::DestroyAll();
}

bool BasicTessellation::Init()
{
	if(!D3DApp::Init())
		return false;

	// Must init Effects first since InputLayouts depend on shader signatures.
	Effects::InitAll(md3dDevice);
	InputLayouts::InitAll(md3dDevice);
	RenderStates::InitAll(md3dDevice);

	BuildQuadPatchBuffer();

	return true;
}

void BasicTessellation::OnResize()
{
	D3DApp::OnResize();

	XMMATRIX P = XMMatrixPerspectiveFovLH(0.25f*MathHelper::Pi, AspectRatio(), 1.0f, 1000.0f);
	XMStoreFloat4x4(&mProj, P);
}

void BasicTessellation::UpdateScene(float dt)
{
	// Convert Spherical to Cartesian coordinates.
	float x = mRadius*sinf(mPhi)*cosf(mTheta);
	float z = mRadius*sinf(mPhi)*sinf(mTheta);
	float y = mRadius*cosf(mPhi);

	mEyePosW = XMFLOAT3(x, y, z);

	// Build the view matrix.
	XMVECTOR pos    = XMVectorSet(x, y, z, 1.0f);
	XMVECTOR target = XMVectorZero();
	XMVECTOR up     = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);

	XMMATRIX V = XMMatrixLookAtLH(pos, target, up);
	XMStoreFloat4x4(&mView, V);
}

void BasicTessellation::DrawScene()
{
	md3dImmediateContext->ClearRenderTargetView(mRenderTargetView, reinterpret_cast<const float*>(&Colors::Silver));
	md3dImmediateContext->ClearDepthStencilView(mDepthStencilView, D3D11_CLEAR_DEPTH|D3D11_CLEAR_STENCIL, 1.0f, 0);

	md3dImmediateContext->IASetInputLayout(InputLayouts::Basic32);
    md3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

	float blendFactor[] = {0.0f, 0.0f, 0.0f, 0.0f};

	XMMATRIX view  = XMLoadFloat4x4(&mView);
	XMMATRIX proj  = XMLoadFloat4x4(&mProj);
	XMMATRIX viewProj = view*proj;

	md3dImmediateContext->IASetInputLayout(InputLayouts::Pos);
    md3dImmediateContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_16_CONTROL_POINT_PATCHLIST);

	UINT stride = sizeof(Vertex::Pos);
    UINT offset = 0;

	// Set per frame constants.
	Effects::BezierTessellationFX->SetEyePosW(mEyePosW);
	Effects::BezierTessellationFX->SetFogColor(Colors::Silver);
	Effects::BezierTessellationFX->SetFogStart(15.0f);
	Effects::BezierTessellationFX->SetFogRange(175.0f);

	D3DX11_TECHNIQUE_DESC techDesc;
	Effects::BezierTessellationFX->TessTech->GetDesc( &techDesc );

    for(UINT p = 0; p < techDesc.Passes; ++p)
    {
		md3dImmediateContext->IASetVertexBuffers(0, 1, &mQuadPatchVB, &stride, &offset);

		// Set per object constants.
		XMMATRIX world = XMMatrixIdentity();
		XMMATRIX worldInvTranspose = MathHelper::InverseTranspose(world);
		XMMATRIX worldViewProj = world*view*proj;

		Effects::BezierTessellationFX->SetWorld(world);
		Effects::BezierTessellationFX->SetWorldInvTranspose(worldInvTranspose);
		Effects::BezierTessellationFX->SetWorldViewProj(worldViewProj);
		Effects::BezierTessellationFX->SetTexTransform(XMMatrixIdentity());
		//Effects::BezierTessellationFX->SetMaterial(0);
		Effects::BezierTessellationFX->SetDiffuseMap(0);

		Effects::BezierTessellationFX->TessTech->GetPassByIndex(p)->Apply(0, md3dImmediateContext);

		md3dImmediateContext->RSSetState(RenderStates::WireframeRS);
		md3dImmediateContext->Draw(16, 0);
	 }

	HR(mSwapChain->Present(0, 0));
}

void BasicTessellation::OnMouseDown(WPARAM btnState, int x, int y)
{
	mLastMousePos.x = x;
	mLastMousePos.y = y;

	SetCapture(mhMainWnd);
}

void BasicTessellation::OnMouseUp(WPARAM btnState, int x, int y)
{
	ReleaseCapture();
}

void BasicTessellation::OnMouseMove(WPARAM btnState, int x, int y)
{
	if( (btnState & MK_LBUTTON) != 0 )
	{
		// Make each pixel correspond to a quarter of a degree.
		float dx = XMConvertToRadians(0.25f*static_cast<float>(x - mLastMousePos.x));
		float dy = XMConvertToRadians(0.25f*static_cast<float>(y - mLastMousePos.y));

		// Update angles based on input to orbit camera around box.
		mTheta += dx;
		mPhi   += dy;

		// Restrict the angle mPhi.
		mPhi = MathHelper::Clamp(mPhi, 0.1f, MathHelper::Pi-0.1f);
	}
	else if( (btnState & MK_RBUTTON) != 0 )
	{
		float dx = 0.2f*static_cast<float>(x - mLastMousePos.x);
		float dy = 0.2f*static_cast<float>(y - mLastMousePos.y);

		// Update the camera radius based on input.
		mRadius += dx - dy;

		// Restrict the radius.
		mRadius = MathHelper::Clamp(mRadius, 5.0f, 300.0f);
	}

	mLastMousePos.x = x;
	mLastMousePos.y = y;
}

void BasicTessellation::BuildQuadPatchBuffer()
{
	D3D11_BUFFER_DESC vbd;
    vbd.Usage = D3D11_USAGE_IMMUTABLE;
	vbd.ByteWidth = sizeof(XMFLOAT3) * 16;
    vbd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    vbd.CPUAccessFlags = 0;
    vbd.MiscFlags = 0;

	XMFLOAT3 vertices[16] =
	{
		// Row 0
		XMFLOAT3(-10.0f, -10.0f, +15.0f),
		XMFLOAT3(-5.0f,  0.0f, +15.0f),
		XMFLOAT3(+5.0f,  0.0f, +15.0f),
		XMFLOAT3(+10.0f, 0.0f, +15.0f),

		// Row 1
		XMFLOAT3(-15.0f, 0.0f, +5.0f),
		XMFLOAT3(-5.0f,  0.0f, +5.0f),
		XMFLOAT3(+5.0f,  20.0f, +5.0f),
		XMFLOAT3(+15.0f, 0.0f, +5.0f),

		// Row 2
		XMFLOAT3(-15.0f, 0.0f, -5.0f),
		XMFLOAT3(-5.0f,  0.0f, -5.0f),
		XMFLOAT3(+5.0f,  0.0f, -5.0f),
		XMFLOAT3(+15.0f, 0.0f, -5.0f),

		// Row 3
		XMFLOAT3(-10.0f, 10.0f, -15.0f),
		XMFLOAT3(-5.0f,  0.0f, -15.0f),
		XMFLOAT3(+5.0f,  0.0f, -15.0f),
		XMFLOAT3(+25.0f, 10.0f, -15.0f)
	};

    D3D11_SUBRESOURCE_DATA vinitData;
    vinitData.pSysMem = vertices;
    HR(md3dDevice->CreateBuffer(&vbd, &vinitData, &mQuadPatchVB));
}


text:
<!DOCTYPE html>

		<meta charset="utf-8"/>
		<meta http-equiv="X-UA-COMPATIBLE" content="IE=edge"/>
		<meta name="viewport" content="width=device-width, initial-scale=1"/>

		<link data-require="bootstrap@3.3.6" data-semver="3.3.6" rel="stylesheet"
				href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>

		<link rel="stylesheet" href="style.css"/>

		<title>Status Type Page CNM</title>

Stream Line CNM

Status Type

					<form class="form-horizontal">

								Status Type Id

									<input type="statusType" class="form-control" id="inputStatusType3" placeholder="Status Type Id">

								Status Type Name

									<input type="statusTypeName" class="form-control" id="inputStatusTypeName3" placeholder="StatusTypeName">

								<button type="enter" class="btn btn-default">Enter</button>

					</form>


text:
package com.utabitwallet.exceptions;

public class BRKeystoreErrorException extends Exception {
    public static final String TAG = BRKeystoreErrorException.class.getName();

    public BRKeystoreErrorException(String message) {
        super(message);
    }
}


text:
package org.cice.jesh.managers;

import org.cice.jesh.persistence.dao.impl.UserDaoImpl;
import org.cice.jesh.persistence.entities.UserDto;
import org.cice.jesh.utils.ParserUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by toni on 20/04/16.
 */
public class UserManager {

    UserDaoImpl userDaoImpl = new UserDaoImpl();
    OrderManager orderManager = new OrderManager();

    public UserManager() {

    }

    public Map<Object, Object> getAllUsers() {

        Map<Object, Object> result = new HashMap<>();

        List<UserDto> usersList = userDaoImpl.findAll();
        List<UserDto> SecureUsersList = new ArrayList<>();

        if (usersList.size() > 0) {
            for (UserDto item : usersList) {
                item.setPassword("");
                SecureUsersList.add(item);
            }
            result.put("statusCode", 200);
            result.put("response", SecureUsersList);
        } else {
            result.put("statusCode", 200);
            result.put("response", usersList);
        }

        return result;
    }

    public Map<Object, Object> getUser(String id) throws Exception {

        Map<Object, Object> result = new HashMap<>();

        if (id == null) {

            result.put("statusCode", 400);
            result.put("response", "The user ID can not be empty");
        } else {

            Integer userId = ParserUtil.stringToInteger(id);
            UserDto originalUser = getUserById(userId);

            if (originalUser == null) {
                result.put("statusCode", 404);
                result.put("response", "User not found");
            } else {

                originalUser.setPassword("");
                originalUser.setOrders(orderManager.getAllOrders(userId));

                result.put("statusCode", 200);
                result.put("response", originalUser);
            }
        }

        return result;
    }

    public Map<Object, Object> create(UserDto user) {

        Map<Object, Object> result = new HashMap<>();

        if (user == null || user.getName() == null || user.getSurname() == null || user.getEmail() == null || user.getAddress() == null || user.getBankAccount() == null || user.getPassword() == null) {

            result.put("statusCode", 400);
            result.put("response", "All user data is required");
        } else if (userDaoImpl.exist("email", user.getEmail()) != null) {
            result.put("statusCode", 400);
            result.put("response", "This email is already registered.");
        } else {
            UserDto userToReturn = userDaoImpl.create(user);

            userToReturn.setPassword("");

            result.put("statusCode", 200);
            result.put("response", userToReturn);
        }

        return result;
    }

    public Map<Object, Object> update(String id, UserDto user) throws Exception {

        Map<Object, Object> result = new HashMap<>();

        if (id == null || user == null || user.getName() == null || user.getSurname() == null || user.getEmail() == null || user.getAddress() == null || user.getBankAccount() == null) {

            result.put("statusCode", 400);
            result.put("response", "All user data is required, except password");
        } else {

            Integer userId = ParserUtil.stringToInteger(id);

            if(user.getPassword() == null){
                UserDto originalUser = getUserById(userId);
                user.setPassword(originalUser.getPassword());
            }

            user.setId(userId);

            UserDto userToReturn = userDaoImpl.update(user);

            userToReturn.setPassword("");

            result.put("statusCode", 200);
            result.put("response", userToReturn);
        }

        return result;
    }

    public Map<Object, Object> delete(String id) throws Exception {

        Map<Object, Object> result = new HashMap<>();

        if (id == null) {

            result.put("statusCode", 400);
            result.put("response", "The user ID can not be empty");
        } else {

            Integer userId = ParserUtil.stringToInteger(id);
            UserDto originalUser = getUserById(userId);

            if (originalUser == null) {
                result.put("statusCode", 404);
                result.put("response", "User not found");
            } else {

                userDaoImpl.delete(originalUser);

                result.put("statusCode", 200);
                result.put("response", "User deleted");
            }
        }

        return result;

    }

    public UserDto getUserById(Integer id){
        return userDaoImpl.getUser(id);
    }
}


text:
import uuid

from django.conf import settings
from django.conf.urls.defaults import patterns, url
from django.contrib.auth import authenticate, login
from django.core.urlresolvers import reverse
from django.core.mail import EmailMessage
from django.http import Http404
from django.shortcuts import render, redirect
from django.template import Context, loader
from django.utils.translation import ugettext as _

from organizations.backends.tokens import RegistrationTokenGenerator
from organizations.backends.forms import (UserRegistrationForm,
        OrganizationRegistrationForm)
from organizations.models import get_user_model
from organizations.utils import create_organization
from organizations.utils import model_field_attr

# Backend classes should provide common interface

class BaseBackend(object):
    """Base backend class for registering and inviting users to an organization
    """

    def __init__(self, *args, **kwargs):
        self.user_model = get_user_model()

    def get_urls(self):
        raise NotImplementedError

    def get_success_url(self):
        """Will return the class's `success_url` attribute unless overridden"""
        raise NotImplementedError

    def get_form(self, **kwargs):
        """Returns the form for registering or inviting a user"""
        if not hasattr(self, 'form_class'):
            raise AttributeError(_("You must define a form_class"))
        return self.form_class(**kwargs)

    def get_token(self, user, **kwargs):
        """Returns a unique token for the given user"""
        return RegistrationTokenGenerator().make_token(user)

    def get_username(self):
        """Returns an UUID based 'random' and unique username"""
        return unicode(uuid.uuid4())[:model_field_attr(self.user_model, 'username', 'max_length')]

    def activate_view(self, request, user_id, token):
        """
        Activates the given User by setting `is_active` to true if the provided
        information is verified.
        """
        try:
            user = self.user_model.objects.get(id=user_id, is_active=False)
        except self.user_model.DoesNotExist:
            raise Http404(_("Your URL may have expired."))
        if not RegistrationTokenGenerator().check_token(user, token):
            raise Http404(_("Your URL may have expired."))
        form = self.get_form(data=request.POST or None, instance=user)
        if form.is_valid():
            form.instance.is_active = True
            user = form.save()
            user.set_password(form.cleaned_data['password'])
            user.save()
            for org in user.organization_set.filter(is_active=False):
                org.is_active = True
                org.save()
            user = authenticate(username=form.cleaned_data['username'],
                    password=form.cleaned_data['password'])
            login(request, user)
            return redirect(self.get_success_url())
        return render(request, 'organizations/register_form.html',
                {'form': form})

    def send_reminder(self, user, sender=None, **kwargs):
        """Sends a reminder email to the specified user"""
        if user.is_active:
            return False
        token = RegistrationTokenGenerator().make_token(user)
        kwargs.update({'token': token})
        self._send_email(user, self.reminder_subject, self.reminder_body,
                sender, **kwargs)

    def _send_email(self, user, subject_template, body_template,
            sender=None, **kwargs):
        """Utility method for sending emails to new users"""
        if sender:
            from_email = "%s %s <%s>" % (sender.first_name, sender.last_name,
                    settings.DEFAULT_FROM_EMAIL)
            reply_to = "%s %s <%s>" % (sender.first_name, sender.last_name,
                    sender.email)
        else:
            from_email = settings.DEFAULT_FROM_EMAIL
            reply_to = {}

        headers = {'Reply-To': reply_to}

        kwargs.update({'sender': sender, 'user': user})
        ctx = Context(kwargs)

        subject_template = loader.get_template(subject_template)
        body_template = loader.get_template(body_template)
        subject = subject_template.render(ctx).strip() # Remove stray newline characters
        body = body_template.render(ctx)
        return EmailMessage(subject, body, from_email, [user.email],
                headers).send()

class RegistrationBackend(BaseBackend):
    """A backend for allowing new users to join the site by creating a new user
    associated with a new organization.
    """
    # NOTE this backend stands to be simplified further, as email verification
    # should be beyond the purview of this app
    activation_subject = 'organizations/email/activation_subject.txt'
    activation_body = 'organizations/email/activation_body.html'
    reminder_subject = 'organizations/email/reminder_subject.txt'
    reminder_body = 'organizations/email/reminder_body.html'
    form_class = UserRegistrationForm

    def get_success_url(self):
        return reverse('registration_success')

    def get_urls(self):
        return patterns('',
            url(r'^complete/$', view=self.success_view,
                name="registration_success"),
            url(r'^(?P<user_id>[\d]+)-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
                view=self.activate_view, name="registration_register"),
            url(r'^$', view=self.create_view, name="registration_create"),
            )

    def register_by_email(self, email, sender=None, request=None, **kwargs):
        """
        Returns a User object filled with dummy data and not active, and sends
        an invitation email.
        """
        try:
            user = self.user_model.objects.get(email=email)
        except self.user_model.DoesNotExist:
            user = self.user_model.objects.create(username=self.get_username(),
                    email=email, password=self.user_model.objects.make_random_password())
            user.is_active = False
            user.save()
        self.send_activation(user, sender, **kwargs)
        return user

    def send_activation(self, user, sender=None, **kwargs):
        """
        Invites a user to join the site
        """
        if user.is_active:
            return False
        token = self.get_token(user)
        kwargs.update({'token': token})
        self._send_email(user, self.activation_subject, self.activation_body,
                sender, **kwargs)

    def create_view(self, request):
        """
        Initiates the organization and user account creation process
        """
        if request.user.is_authenticated():
            return redirect("organization_add")
        form = OrganizationRegistrationForm(request.POST or None)
        if form.is_valid():
            try:
                user = self.user_model.objects.get(email=form.cleaned_data['email'])
            except self.user_model.DoesNotExist:
                user = self.user_model.objects.create(username=self.get_username(),
                        email=form.cleaned_data['email'],
                        password=self.user_model.objects.make_random_password())
                user.is_active = False
                user.save()
            else:
                return redirect("organization_add")
            organization = create_organization(user, form.cleaned_data['name'],
                    form.cleaned_data['slug'], is_active=False)
            return render(request, 'organizations/register_success.html',
                    {'user': user, 'organization': organization})
        return render(request, 'organizations/register_form.html',
                {'form': form})

    def success_view(self, request):
        return render(request, 'organizations/register_success.html', {})

class InvitationBackend(BaseBackend):
    """A backend for inviting new users to join the site as members of an
    organization.
    """
    invitation_subject = 'organizations/email/invitation_subject.txt'
    invitation_body = 'organizations/email/invitation_body.html'
    reminder_subject = 'organizations/email/reminder_subject.txt'
    reminder_body = 'organizations/email/reminder_body.html'
    form_class = UserRegistrationForm

    def get_success_url(self):
        return reverse('organization_list')

    def get_urls(self):
        return patterns('',
            url(r'^(?P<user_id>[\d]+)-(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
                view=self.activate_view, name="invitations_register"),
            )

    def invite_by_email(self, email, sender=None, request=None, **kwargs):
        """Creates an inactive user with the information we know and then sends
        an invitation email for that user to complete registration.

        If your project uses email in a different way then you should make to
        extend this method as it only checks the `email` attribute for Users.
        """
        try:
            user = self.user_model.objects.get(email=email)
        except self.user_model.DoesNotExist:
            user = self.user_model.objects.create(username=self.get_username(),
                    email=email, password=self.user_model.objects.make_random_password())
            user.is_active = False
            user.save()
        self.send_invitation(user, sender, **kwargs)
        return user

    def send_invitation(self, user, sender=None, **kwargs):
        """An intermediary function for sending an invitation email that
        selects the templates, generating the token, and ensuring that the user
        has not already joined the site.
        """
        if user.is_active:
            return False
        token = self.get_token(user)
        kwargs.update({'token': token})
        self._send_email(user, self.invitation_subject, self.invitation_body,
                sender, **kwargs)


text:
/* eslint-disable no-shadow, no-use-before-define, prefer-destructuring */
const _ = require('lodash');
const fs = require('fs');
const fstools = require('fs-tools');
const processSco = require('../lib/processSco.js');
const test = require('tap').test;

const pathToCopyFiles = 'tests/fixtures/processScoTests/tmp';

test('Errors when you don\'t pass any parameters', (t) => {
  processSco(null, (err) => {
    t.ok(err, 'Should error');
    t.equal(err, 'Requires a path to the SCO manifest');
    t.end();
  });
});

test('Errors when you don\'t pass the path of the manifest', (t) => {
  processSco({}, (err) => {
    t.ok(err, 'Should error');
    t.equal(err, 'Requires a path to the SCO manifest');
    t.end();
  });
});

test('Does not error when referencing a SCO that doesn\'t have the Storyline mobile/player_compiled.js', (t) => {
  t.test('Should copy files for processing', _.curry(copyFilesToProcessingLocation)('tests/fixtures/processScoTests/nonSpecificOutput'));

  t.test('Does not error when referencing a SCO that doesn\'t have the Storyline mobile/player_compiled.js', (t) => {
    processSco({ pathOfManifest: `${pathToCopyFiles}/imsmanifest.xml` }, (err) => {
      t.notOk(err, 'Should not error');
      t.end();
    });
  });

  t.test('Should remove temporary files copied for processing', removeTempProcessingLocation);
  t.end();
});

test('Successfully modifies a SCO that has the Storyline mobile/player_compiled.js', (t) => {
  t.test('Should copy files for processing', _.curry(copyFilesToProcessingLocation)('tests/fixtures/processScoTests/storylineHtml5Output'));

  t.test('Should have code that\'s prior to processing', (t) => {
    const playerCompiledJsString = fs.readFileSync(`${pathToCopyFiles}/mobile/player_compiled.js`, { encoding: 'utf8' });
    t.ok(playerCompiledJsString.indexOf('var k=j-window.innerHeight') >= 0, 'Should still have this code');
    t.ok(playerCompiledJsString.indexOf('if(self!=top)a=a.replace("framewrap","portrait .framewrap").replace("interstitial","portrait .interstitial"),player.rotatePortraitFramedStyleSheet=document.createElement("style"),player.rotatePortraitFramedStyleSheet.innerHTML=a,document.body.appendChild(player.rotatePortraitFramedStyleSheet)') >= 0, 'Should still have this code');
    t.end();
  });

  t.test('Should find modfied text in the Storyline mobile/player_compiled.js', (t) => {
    processSco({ pathOfManifest: `${pathToCopyFiles}/imsmanifest.xml` }, (err) => {
      t.notOk(err, 'Should not error');
      const playerCompiledJsString = fs.readFileSync(`${pathToCopyFiles}/mobile/player_compiled.js`, { encoding: 'utf8' });
      t.ok(playerCompiledJsString.indexOf('var scoParserTop=self;') >= 0, 'Should find JS added at beginning of the file');
      t.ok(playerCompiledJsString.lastIndexOf('scoParserTop.') > 0 && playerCompiledJsString.indexOf('scoParserTop.') !== playerCompiledJsString.lastIndexOf('scoParserTop.'), 'Should find other instances of scoParserTop from the replacement later in the file');
      t.end();
    });
  });

  t.test('Should remove temporary files copied for processing', removeTempProcessingLocation);
  t.end();
});

test('Does not error when referencing a SCO that doesn\'t have the Captivate SCORM_utilities.js', (t) => {
  t.test('Should copy files for processing', _.curry(copyFilesToProcessingLocation)('tests/fixtures/processScoTests/nonSpecificOutput'));

  t.test('Does not error when referencing a SCO that doesn\'t have the Captivate SCORM_utilities.js', (t) => {
    processSco({ pathOfManifest: `${pathToCopyFiles}/imsmanifest.xml` }, (err) => {
      t.notOk(err, 'Should not error');
      t.end();
    });
  });

  t.test('Should remove temporary files copied for processing', removeTempProcessingLocation);
  t.end();
});

test('Successfully modifies a SCO that has the Captivate SCORM_utilities.js', (t) => {
  t.test('Should copy files for processing', _.curry(copyFilesToProcessingLocation)('tests/fixtures/processScoTests/captivateOutput'));

  t.test('Should find modified text in the Captivate SCORM_utilities.js', (t) => {
    processSco({ pathOfManifest: `${pathToCopyFiles}/imsmanifest.xml` }, (err) => {
      t.notOk(err, 'Should not error');
      const playerCompiledJsString = fs.readFileSync(`${pathToCopyFiles}/SCORM_utilities.js`, { encoding: 'utf8' });
      t.ok(playerCompiledJsString.indexOf('WMODE : "opaque"') >= 0, 'Should find wmode config now set to opaque');
      t.end();
    });
  });

  t.test('Should remove temporary files copied for processing', removeTempProcessingLocation);
  t.end();
});

test('Successfully modifies a SCO that has the Captivate htm/html file that contains the CaptivateContent ID on one of its elements', (t) => {
  t.test('Should copy files for processing', _.curry(copyFilesToProcessingLocation)('tests/fixtures/processScoTests/captivateOutput'));

  t.test('Should find modfied text in the Captivate SCORM_utilities.js', (t) => {
    processSco({ pathOfManifest: `${pathToCopyFiles}/imsmanifest.xml` }, (err) => {
      t.notOk(err, 'Should not error');
      const modifiedHtml = fs.readFileSync(`${pathToCopyFiles}/captivate_noquiz_SWFandHTML5output.htm`, { encoding: 'utf8' });
      t.ok(modifiedHtml.match(/<head>\s*<style>\s*html\s*\{\s*height:\s*100%\s*\}\s*body\s*\{\s*height:\s*100%;\s*width:\s*100%;\s*display:\s*table;\s*margin:\s*0\s*\}\s*#CaptivateContent\s*\{\s*display:\s*table-cell\s*;\s*height:\s*100%\s*;\s*vertical-align:\s*middle\s*}\s*<\/style>/), 'Should find CSS added to the head');
      t.end();
    });
  });

  t.test('Should remove temporary files copied for processing', removeTempProcessingLocation);
  t.end();
});

test('Does not error when referencing a SCO that doesn\'t have the Storyline story.html', (t) => {
  t.test('Should copy files for processing', _.curry(copyFilesToProcessingLocation)('tests/fixtures/processScoTests/nonSpecificOutput'));

  t.test('Does not error when referencing a SCO that doesn\'t have the Storyline story.html', (t) => {
    processSco({ pathOfManifest: `${pathToCopyFiles}/imsmanifest.xml` }, (err) => {
      t.notOk(err, 'Should not error');
      t.end();
    });
  });

  t.test('Should remove temporary files copied for processing', removeTempProcessingLocation);
  t.end();
});

test('Successfully modifies a SCO that has the Storyline story.html', (t) => {
  t.test('Should copy files for processing', _.curry(copyFilesToProcessingLocation)('tests/fixtures/processScoTests/storylineHtml5Output'));

  t.test('Should find modfied text in the Storyline story.html', (t) => {
    processSco({ pathOfManifest: `${pathToCopyFiles}/imsmanifest.xml` }, (err, result) => {
      t.notOk(err, 'Should not error');
      t.equal(result, 'storyline_mobile');
      const playerCompiledJsString = fs.readFileSync(`${pathToCopyFiles}/story.html`, { encoding: 'utf8' });
      t.ok(playerCompiledJsString.indexOf('g_strWMode = "opaque"') >= 0, 'Should find g_strWMode config now set to opaque');
      t.end();
    });
  });

  t.test('Should remove temporary files copied for processing', removeTempProcessingLocation);
  t.end();
});

test('Successfully modifies a SCO that has the Articulate Rise content', (t) => {
  t.test('Should copy files for processing', _.curry(copyFilesToProcessingLocation)('tests/fixtures/processScoTests/articulateRiseOutput'));

  t.test('Should find modified text in the Rise scormdriver.js file', (t) => {
    processSco({ pathOfManifest: `${pathToCopyFiles}/imsmanifest.xml` }, (err, result) => {
      t.notOk(err, 'Should not error');
      t.equal(result, 'articulate_rise');
      const playerCompiledJsString = fs.readFileSync(`${pathToCopyFiles}/scormdriver/scormdriver.js`, { encoding: 'utf8' });
      t.ok(playerCompiledJsString.indexOf('scoParserTop.') >= 0, 'Should find sco parser top');
      t.end();
    });
  });

  t.test('Should remove temporary files copied for processing', removeTempProcessingLocation);
  t.end();
});

test('Successfully checks for a camtasia SCO without a quiz', (t) => {
  t.test('Should copy files for processing', _.curry(copyFilesToProcessingLocation)('tests/fixtures/processScoTests/camtasiaOutput'));

  t.test('Should return the camtasia type of content', (t) => {
    processSco({ pathOfManifest: `${pathToCopyFiles}/imsmanifest.xml` }, (err, result) => {
      t.notOk(err, 'Should not error');
      t.equal(result, 'camtasia');
      t.end();
    });
  });

  t.test('Should remove temporary files copied for processing', removeTempProcessingLocation);
  t.end();
});

test('Successfully checks for a camtasia SCO with a quiz', (t) => {
  t.test('Should copy files for processing', _.curry(copyFilesToProcessingLocation)('tests/fixtures/processScoTests/camtasiaOutput_withQuiz'));

  t.test('Should return the camtasia type of content', (t) => {
    processSco({ pathOfManifest: `${pathToCopyFiles}/imsmanifest.xml` }, (err, result) => {
      t.notOk(err, 'Should not error');
      t.equal(result, 'camtasia_quiz');
      t.end();
    });
  });

  t.test('Should remove temporary files copied for processing', removeTempProcessingLocation);
  t.end();
});

function copyFilesToProcessingLocation(pathOfTestFiles, t) {
  fstools.copy(pathOfTestFiles, pathToCopyFiles, (err) => {
  if (err) t.fail('Failed to copy files to process');
    t.end();
  });
}

function removeTempProcessingLocation(t) {
  fstools.remove(pathToCopyFiles, (err) => {
    if (err) t.fail('Failed to remove copied files for processing');
    t.end();
  });
}


text:
from django.db import models

class City(models.Model):
    id = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=50)

class Country(models.Model):
    id = models.SmallAutoField(primary_key=True)
    name = models.CharField(max_length=50)

class District(models.Model):
    city = models.OneToOneField(City, models.CASCADE, primary_key=True)
    name = models.CharField(max_length=50)

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()
    facebook_user_id = models.BigIntegerField(null=True)
    raw_data = models.BinaryField(null=True)
    small_int = models.SmallIntegerField()
    interval = models.DurationField()

    class Meta:
        unique_together = ('first_name', 'last_name')

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    body = models.TextField(default='')
    reporter = models.ForeignKey(Reporter, models.CASCADE)
    response_to = models.ForeignKey('self', models.SET_NULL, null=True)
    unmanaged_reporters = models.ManyToManyField(Reporter, through='ArticleReporter', related_name='+')

    class Meta:
        ordering = ('headline',)
        index_together = [
            ["headline", "pub_date"],
            ['headline', 'response_to', 'pub_date', 'reporter'],
        ]

class ArticleReporter(models.Model):
    article = models.ForeignKey(Article, models.CASCADE)
    reporter = models.ForeignKey(Reporter, models.CASCADE)

    class Meta:
        managed = False

class Comment(models.Model):
    ref = models.UUIDField(unique=True)
    article = models.ForeignKey(Article, models.CASCADE, db_index=True)
    email = models.EmailField()
    pub_date = models.DateTimeField()
    body = models.TextField()

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['article', 'email', 'pub_date'], name='article_email_pub_date_uniq'),
        ]
        indexes = [
            models.Index(fields=['email', 'pub_date'], name='email_pub_date_idx'),
        ]

class CheckConstraintModel(models.Model):
    up_votes = models.PositiveIntegerField()
    voting_number = models.PositiveIntegerField(unique=True)

    class Meta:
        required_db_features = {
            'supports_table_check_constraints',
        }
        constraints = [
            models.CheckConstraint(name='up_votes_gte_0_check', check=models.Q(up_votes__gte=0)),
        ]

class UniqueConstraintConditionModel(models.Model):
    name = models.CharField(max_length=255)
    color = models.CharField(max_length=32, null=True)

    class Meta:
        required_db_features = {'supports_partial_indexes'}
        constraints = [
            models.UniqueConstraint(
                fields=['name'],
                name='cond_name_without_color_uniq',
                condition=models.Q(color__isnull=True),
            ),
        ]