text:
<?php

namespace ZendTest\I18n\Translator\Loader;

use PHPUnit_Framework_TestCase as TestCase;
use Locale;
use Zend\I18n\Translator\Loader\PhpArray as PhpArrayLoader;

class PhpArrayTest extends TestCase
{
    protected $testFilesDir;
    protected $originalLocale;

    public function setUp()
    {
        $this->originalLocale = Locale::getDefault();
        Locale::setDefault('en_EN');

        $this->testFilesDir = realpath(__DIR__ . '/../_files');
    }

    public function tearDown()
    {
        Locale::setDefault($this->originalLocale);
    }

    public function testLoaderFailsToLoadMissingFile()
    {
        $loader = new PhpArrayLoader();
        $this->setExpectedException('Zend\I18n\Exception\InvalidArgumentException', 'Could not open file');
        $loader->load('en_EN', 'missing');
    }

    public function testLoaderFailsToLoadNonArray()
    {
        $loader = new PhpArrayLoader();
        $this->setExpectedException('Zend\I18n\Exception\InvalidArgumentException',
                                    'Expected an array, but received');
        $loader->load('en_EN', $this->testFilesDir . '/failed.php');
    }

    public function testLoaderLoadsEmptyArray()
    {
        $loader = new PhpArrayLoader();
        $textDomain = $loader->load('en_EN', $this->testFilesDir . '/translation_empty.php');
        $this->assertInstanceOf('Zend\I18n\Translator\TextDomain', $textDomain);
    }

    public function testLoaderReturnsValidTextDomain()
    {
        $loader = new PhpArrayLoader();
        $textDomain = $loader->load('en_EN', $this->testFilesDir . '/translation_en.php');

        $this->assertEquals('Message 1 (en)', $textDomain['Message 1']);
        $this->assertEquals('Message 4 (en)', $textDomain['Message 4']);
    }

    public function testLoaderLoadsPluralRules()
    {
        $loader     = new PhpArrayLoader();
        $textDomain = $loader->load('en_EN', $this->testFilesDir . '/translation_en.php');

        $this->assertEquals(2, $textDomain->getPluralRule()->evaluate(0));
        $this->assertEquals(0, $textDomain->getPluralRule()->evaluate(1));
        $this->assertEquals(1, $textDomain->getPluralRule()->evaluate(2));
        $this->assertEquals(2, $textDomain->getPluralRule()->evaluate(10));
    }
}


text:
using System;
using System.IO;
using System.Text;

namespace _11_DeletePrefixWordInTextFile
{
    class DeletePrefixWordInTextFile
    {
        static void Main()
        {
            Console.Title = "Delete prefix word in text file";

            Console.Write("Enter file path: ");
            string filePath = Console.ReadLine();

            try
            {
                DeleteWord(filePath);
                Console.WriteLine("\nDeleting finish successfully...\n");
            }
            catch (IOException e)
            {
                Console.WriteLine(e.Message);
            }
        }

        private static void DeleteWord(string filePath)
        {
            string tempFilePath = filePath + ".txt";

            using (StreamReader reader = new StreamReader(filePath))
            {
                using (StreamWriter writer = new StreamWriter(tempFilePath))
                {
                    while (!reader.EndOfStream)
                    {
                        string str = reader.ReadLine();

                        string replasedString = DeletePrefixWords(str, "test");

                        writer.WriteLine(replasedString);
                    }
                }
            }

            File.Delete(filePath);

            File.Move(tempFilePath, filePath);
        }

        private static string DeletePrefixWords(string str, string prefix)
        {
            StringBuilder word = new StringBuilder();
            StringBuilder replasedString = new StringBuilder();

            for (int i = 0; i < str.Length; i++)
            {
                // get whole word
                if (str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z'
                    || str[i] == '_' || str[i] >= '0' && str[i] <= '9')
                {
                    word.Append(str[i]);
                }
                else
                {
                    if (!word.ToString().StartsWith(prefix))
                    {
                        replasedString.Append(word);
                        replasedString.Append(str[i]);
                    }

                    word.Clear();
                }
            }

            if (!word.ToString().StartsWith(prefix))
            {
                replasedString.Append(word);
            }

            return replasedString.ToString();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import logging
import inspect
import functools

def log(fn):
    @functools.wraps(fn)
    def decorated(*args, **kwargs):
        # get the names of all the args
        arguments = inspect.getcallargs(fn, *args, **kwargs)

        logging.debug("function '{}' called by '{}' with arguments:\n{}".format(
                      fn.__name__,
                      inspect.stack()[1][3],
                      arguments))
        result = fn(*args, **kwargs)
        logging.debug("result: {}\n".format(result))

        return result

    return decorated


text:
<?php

include_once('models/constants.php');

class ClientJob
{
  var $Id;
  var $ScheduleId;
  var $OsId;
  var $SiteId;
  var $StartDate;
  var $EndDate;
  var $Status;
  var $CMakeId;
  var $CompilerId;
  var $Output;

  /** Get ScheduleId */
  // commenting out until it's actually used
  /*
  function GetScheduleId()
    {
    if(!$this->Id)
      {
      add_log("ClientJob::GetScheduleId()","Id not set");
      return;
      }
    $sys = pdo_query("SELECT scheduleid FROM client_job WHERE id=".qnum($this->Id));
    $row = pdo_fetch_array($sys);
    return $row[0];
    }
  */

  /** Get StartingDate */
  function GetStartDate()
    {
    if(!$this->Id)
      {
      add_log("ClientJob::GetStartDate","Id not set");
      return;
      }
    $sys = pdo_query("SELECT startdate FROM client_job WHERE id=".qnum($this->Id));
    $row = pdo_fetch_array($sys);
    return $row[0];
    }

  /** Get End Date */
  function GetEndDate()
    {
    if(!$this->Id)
      {
      add_log("ClientJob::GetEndDate","Id not set");
      return;
      }
    $sys = pdo_query("SELECT enddate FROM client_job WHERE id=".qnum($this->Id));
    $row = pdo_fetch_array($sys);
    return $row[0];
    }

  /** Get Status */
  function GetStatus()
    {
    if(!$this->Id)
      {
      add_log("ClientJob::GetStatus","Id not set");
      return;
      }
    $sys = pdo_query("SELECT status FROM client_job WHERE id=".qnum($this->Id));
    $row = pdo_fetch_array($sys);
    return $row[0];
    }

  /** Get Site */
  function GetSite()
    {
    if(!$this->Id)
      {
      add_log("ClientJob::GetSite","Id not set");
      return;
      }
    $sys = pdo_query("SELECT siteid FROM client_job WHERE id=".qnum($this->Id));
    $row = pdo_fetch_array($sys);
    return $row[0];
    }

  /** Set the job has finished */
  function SetFinished()
    {
    $now = date('Y-m-d H:i:s');
    $sql = "UPDATE client_job SET status=".CDASH_JOB_FINISHED.",enddate='".$now."' WHERE siteid=".$this->SiteId." AND status=".CDASH_JOB_RUNNING;
    pdo_query($sql);
    add_last_sql_error("ClientJob::SetFinished");
    }

  /** Set the job has failed */
  function SetFailed()
    {
    $now = date('Y-m-d H:i:s');
    $sql = "UPDATE client_job SET status=".CDASH_JOB_FAILED.",enddate='".$now."' WHERE siteid=".$this->SiteId." AND status=".CDASH_JOB_RUNNING;
    pdo_query($sql);
    add_last_sql_error("ClientJob::SetFailed");
    }

  /** Save a job */
  function Save()
    {
    $sql = "INSERT INTO client_job (scheduleid,osid,siteid,startdate,enddate,status,output,cmakeid,compilerid)
            VALUES ('".$this->ScheduleId."','".$this->OsId."','".$this->SiteId."','".$this->StartDate."','".$this->EndDate
            ."','".$this->Status."','".$this->Output."','".$this->CMakeId."','".$this->CompilerId."')";
    pdo_query($sql);
    $this->Id = pdo_insert_id('client_job');
    add_last_sql_error("ClientJob::Save");
    }   // end Save

} // end class proJob


text:
package de.behrfried.wikianalyzer.wawebapp.client.util.data;

/**
 * Class for storing six values.
 *
 * @author marcus
 *
 * @param <E>
 *            specifies the type of the first value
 * @param <G>
 *            specifies the type of the second value
 * @param <I>
 *            specifies the type of the third value
 * @param <K>
 *            specifies the type of the fourth value
 * @param <M>
 *            specifies the type of the fifth value
 * @param <O>
 *            specifies the type of the sixth value
 */
public class Tuple6<E, G, I, K, M, O> {

	/**
	 * the first value
	 */
	private final E item1;

	/**
	 * the second value
	 */
	private final G item2;

	/**
	 * the third value
	 */
	private final I item3;

	/**
	 * the fourth value
	 */
	private final K item4;

	/**
	 * the fifth value
	 */
	private final M item5;

	/**
	 * the sixth value
	 */
	private final O item6;

	/**
	 * Creates an Tuple6 with the passed values.
	 *
	 * @param item1
	 *            the first value
	 * @param item2
	 *            the second value
	 * @param item3
	 *            the third value
	 * @param item4
	 *            the fourth value
	 * @param item5
	 *            the fifth value
	 * @param item6
	 *            the sixth value
	 */
	public Tuple6(final E item1, final G item2, final I item3, final K item4, final M item5, final O item6) {
		this.item1 = item1;
		this.item2 = item2;
		this.item3 = item3;
		this.item4 = item4;
		this.item5 = item5;
		this.item6 = item6;
	}

	/**
	 * Returns the first value.
	 *
	 * @return the first value
	 */
	public E getItem1() {
		return this.item1;
	}

	/**
	 * Returns the second value.
	 *
	 * @return the second value
	 */
	public G getItem2() {
		return this.item2;
	}

	/**
	 * Returns the third value.
	 *
	 * @return the third value
	 */
	public I getItem3() {
		return this.item3;
	}

	/**
	 * Returns the fourth value.
	 *
	 * @return the fourth value
	 */
	public K getItem4() {
		return this.item4;
	}

	/**
	 * Returns the fifth value.
	 *
	 * @return the fifth value
	 */
	public M getItem5() {
		return this.item5;
	}

	/**
	 * Returns the sixth value.
	 *
	 * @return the sixth value
	 */
	public O getItem6() {
		return this.item6;
	}

	/**
	 * Calculates a hash code based on each item this Tuple6 contains.
	 *
	 * @return a hash code based on each item this Tuple6 contains
	 */
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + (this.item1 == null ? 0 : this.item1.hashCode());
		result = prime * result + (this.item2 == null ? 0 : this.item2.hashCode());
		result = prime * result + (this.item3 == null ? 0 : this.item3.hashCode());
		result = prime * result + (this.item4 == null ? 0 : this.item4.hashCode());
		result = prime * result + (this.item5 == null ? 0 : this.item5.hashCode());
		result = prime * result + (this.item6 == null ? 0 : this.item6.hashCode());
		return result;
	}

	/**
	 * Compares this Tuple6 with the passed {@link Object}. Only an instance of
	 * Tuple6 can return true.
	 *
	 * @param obj
	 * @return true if 'obj' is an instance of Tuple6 and all items 'equals'
	 *         return true, otherwise false
	 */
	@Override
	public boolean equals(final Object obj) {
		if(this == obj) {
			return true;
		}
		if(obj == null) {
			return false;
		}
		if(this.getClass() != obj.getClass()) {
			return false;
		}
		final Tuple6<?, ?, ?, ?, ?, ?> other = (Tuple6<?, ?, ?, ?, ?, ?>)obj;
		if(this.item1 == null) {
			if(other.item1 != null) {
				return false;
			}
		} else if(!this.item1.equals(other.item1)) {
			return false;
		}
		if(this.item2 == null) {
			if(other.item2 != null) {
				return false;
			}
		} else if(!this.item2.equals(other.item2)) {
			return false;
		}
		if(this.item3 == null) {
			if(other.item3 != null) {
				return false;
			}
		} else if(!this.item3.equals(other.item3)) {
			return false;
		}
		if(this.item4 == null) {
			if(other.item4 != null) {
				return false;
			}
		} else if(!this.item4.equals(other.item4)) {
			return false;
		}
		if(this.item5 == null) {
			if(other.item5 != null) {
				return false;
			}
		} else if(!this.item5.equals(other.item5)) {
			return false;
		}
		if(this.item6 == null) {
			if(other.item6 != null) {
				return false;
			}
		} else if(!this.item6.equals(other.item6)) {
			return false;
		}
		return true;
	}
}


text:
//
// This is a partial header, do not include on it's own!!!
//
// Linear combination for bessel derivatives are defined here
#ifndef BOOST_MATH_SF_DETAIL_BESSEL_DERIVATIVES_LINEAR_HPP
#define BOOST_MATH_SF_DETAIL_BESSEL_DERIVATIVES_LINEAR_HPP

#ifdef _MSC_VER
#pragma once
#endif

namespace boost{ namespace math{ namespace detail{

template <class T, class Tag, class Policy>
inline T bessel_j_derivative_linear(T v, T x, Tag tag, Policy pol)
{
   return (boost::math::detail::cyl_bessel_j_imp<T>(v-1, x, tag, pol) - boost::math::detail::cyl_bessel_j_imp<T>(v+1, x, tag, pol)) / 2;
}

template <class T, class Policy>
inline T bessel_j_derivative_linear(T v, T x, const bessel_int_tag& tag, Policy pol)
{
   return (boost::math::detail::cyl_bessel_j_imp<T>(itrunc(v-1), x, tag, pol) - boost::math::detail::cyl_bessel_j_imp<T>(itrunc(v+1), x, tag, pol)) / 2;
}

template <class T, class Policy>
inline T sph_bessel_j_derivative_linear(unsigned v, T x, Policy pol)
{
   return (v / x) * boost::math::detail::sph_bessel_j_imp<T>(v, x, pol) - boost::math::detail::sph_bessel_j_imp<T>(v+1, x, pol);
}

template <class T, class Policy>
inline T bessel_i_derivative_linear(T v, T x, Policy pol)
{
   return (boost::math::detail::cyl_bessel_i_imp<T>(v-1, x, pol) + boost::math::detail::cyl_bessel_i_imp<T>(v+1, x, pol)) / 2;
}

template <class T, class Tag, class Policy>
inline T bessel_k_derivative_linear(T v, T x, Tag tag, Policy pol)
{
   return (boost::math::detail::cyl_bessel_k_imp<T>(v-1, x, tag, pol) + boost::math::detail::cyl_bessel_k_imp<T>(v+1, x, tag, pol)) / -2;
}

template <class T, class Policy>
inline T bessel_k_derivative_linear(T v, T x, const bessel_int_tag& tag, Policy pol)
{
   return (boost::math::detail::cyl_bessel_k_imp<T>(itrunc(v-1), x, tag, pol) + boost::math::detail::cyl_bessel_k_imp<T>(itrunc(v+1), x, tag, pol)) / -2;
}

template <class T, class Tag, class Policy>
inline T bessel_y_derivative_linear(T v, T x, Tag tag, Policy pol)
{
   return (boost::math::detail::cyl_neumann_imp<T>(v-1, x, tag, pol) - boost::math::detail::cyl_neumann_imp<T>(v+1, x, tag, pol)) / 2;
}

template <class T, class Policy>
inline T bessel_y_derivative_linear(T v, T x, const bessel_int_tag& tag, Policy pol)
{
   return (boost::math::detail::cyl_neumann_imp<T>(itrunc(v-1), x, tag, pol) - boost::math::detail::cyl_neumann_imp<T>(itrunc(v+1), x, tag, pol)) / 2;
}

template <class T, class Policy>
inline T sph_neumann_derivative_linear(unsigned v, T x, Policy pol)
{
   return (v / x) * boost::math::detail::sph_neumann_imp<T>(v, x, pol) - boost::math::detail::sph_neumann_imp<T>(v+1, x, pol);
}

}}} // namespaces

#endif // BOOST_MATH_SF_DETAIL_BESSEL_DERIVATIVES_LINEAR_HPP


text:
<?php
/* ------------------------------------------------------------------------- *
 *	Normal page template
/* ------------------------------------------------------------------------- */

get_header(); ?>

<section class="container<?php ac_mini_disabled() ?> clearfix">

	<?php get_template_part( 'page-templates/template', 'page' ); ?>

</section><!-- END .container -->

<?php get_footer(); ?>


text:
package my.jpa.service;

import my.jpa.models.Item;
import my.jpa.models.parts.BaseBlock;
import my.jpa.repository.*;
import my.jpa.utils.RequestParameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Service;

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

/**
 * Created by Ivan Sliusar on 23.05.2018.
 * Red Line Soft corp.
 */
@Service
public class ValidateItem {
    @Autowired
    public ItemRepository itemRepo;
    @Autowired
    public CarRepository carRepo;
    @Autowired
    public EngineRepository engineRepo;
    @Autowired
    public GearBoxRepository gearRepo;
    @Autowired
    public TransmissionRepository transmissionRepo;

    private ValidateItem() {
    }

    private boolean itemExistInBase(int id) {
        return itemRepo.findById(id).get() != null;
    }

    public boolean add(Item item) {
        itemRepo.save(item);
        return itemExistInBase(item.getId());
    }

    public boolean update(Item item) {
        itemRepo.save(item);
        return itemExistInBase(item.getId());
    }

    public boolean delete(int id) {
        Item deleteItem = itemRepo.findById(Integer.valueOf(id)).get();
        if (deleteItem != null)
            itemRepo.delete(deleteItem);
        return !itemExistInBase(id);
    }

    public List<Item> findAllByFilter(ItemRequestWrapper wrapper) {
        ArrayList<RequestParameter> parameters = wrapper.getParameters();
        if (parameters.size() == 1) {
            RequestParameter parameter = parameters.get(0);
            if (parameter.getKey().equals("withPhoto")) {
                if (Integer.valueOf(parameter.getValue()) == 1)
                    return itemRepo.findByCoverPathIsNotNull();
                else
                    return itemRepo.findByCoverPathIsNull();
            }
            if (parameter.getKey().equals("carId")) {
                Integer carId = Integer.valueOf(parameter.getValue());
                return itemRepo.findAllByCar(carRepo.findById(carId).get());
            }
        } else {
            java.sql.Timestamp eDate = null;
            java.sql.Timestamp sDate = null;
            for (RequestParameter parameter : parameters) {
                if (parameter.getKey().equals("sDate")) {
                    sDate = new Timestamp(Long.parseLong(parameter.getValue()));
                } else if (parameter.getKey().equals("eDate")) {
                    eDate = new Timestamp(Long.parseLong(parameter.getValue()));
                }
            }
            return itemRepo.findByCreatedBetween(sDate, eDate);
        }
        return null;
    }

    public List<Item> findAll() {
        List<Item> items = new ArrayList<>();
        itemRepo.findAll().forEach(item -> items.add(item));
        return items;
    }

    public Item findByID(int id) {
        return itemRepo.findById(id).get();
    }

    public Map<String, List<BaseBlock>> getDopdownList() {
        Map<String, List<BaseBlock>> listMap = new HashMap<>();
        listMap.put("car",
                findAllInSetRepository(carRepo));
        listMap.put("engine",
                findAllInSetRepository(engineRepo));
        listMap.put("gearbox",
                findAllInSetRepository(gearRepo));
        listMap.put("transmission",
                findAllInSetRepository(transmissionRepo));
        return listMap;
    }

    private List<BaseBlock> findAllInSetRepository(CrudRepository repository) {
        List<BaseBlock> blockList = new ArrayList<>();
        repository.findAll().forEach(value -> blockList.add((BaseBlock) value));
        return blockList;
    }
}


text:
@class DVTSourceCodeLanguage;

@interface DVTTextCompletionDataSource : NSObject

@property (retain, nonatomic) DVTSourceCodeLanguage *language;

- (void)generateCompletionsForDocumentLocation:(id)arg1 context:(id)arg2 completionBlock:(id)arg3;

@end


text:
package com.facebook.buck.distributed;

import com.facebook.buck.config.BuckConfig;
import com.facebook.buck.distributed.thrift.BuildMode;
import com.facebook.buck.log.Logger;
import com.facebook.buck.slb.SlbBuckConfig;
import com.facebook.buck.util.config.Config;
import com.facebook.buck.util.config.Configs;
import com.facebook.buck.util.config.RawConfig;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;

public class DistBuildConfig {

  private static final Logger LOG = Logger.get(DistBuildConfig.class);

  public static final String STAMPEDE_SECTION = "stampede";

  private static final String FRONTEND_REQUEST_TIMEOUT_MILLIS = "stampede_timeout_millis";
  private static final long REQUEST_TIMEOUT_MILLIS_DEFAULT_VALUE = TimeUnit.SECONDS.toMillis(60);

  @VisibleForTesting
  static final String ALWAYS_MATERIALIZE_WHITELIST = "always_materialize_whitelist";

  private static final String ENABLE_SLOW_LOCAL_BUILD_FALLBACK = "enable_slow_local_build_fallback";
  private static final boolean ENABLE_SLOW_LOCAL_BUILD_FALLBACK_DEFAULT_VALUE = false;

  private static final String BUILD_MODE = "build_mode";
  private static final BuildMode BUILD_MODE_DEFAULT_VALUE = BuildMode.REMOTE_BUILD;

  private static final String NUMBER_OF_MINIONS = "number_of_minions";
  private static final Integer NUMBER_OF_MINIONS_DEFAULT_VALUE = 2;

  private static final String REPOSITORY = "repository";
  private static final String DEFAULT_REPOSITORY = "";
  private static final String TENANT_ID = "tenant_id";
  private static final String DEFAULT_TENANT_ID = "";

  private static final String BUILD_LABEL = "build_label";
  private static final String DEFAULT_BUILD_LABEL = "";

  private static final String MINION_QUEUE = "minion_queue";

  private static final String MAX_BUILD_NODES_PER_MINION = "max_build_nodes_per_minion";
  private static final int DEFAULT_MAX_BUILD_NODES_PER_MINION = 100;

  private static final String SOURCE_FILE_MULTI_FETCH_BUFFER_PERIOD_MS =
      "source_file_multi_fetch_buffer_period_ms";
  private static final String SOURCE_FILE_MULTI_FETCH_MAX_BUFFER_SIZE =
      "source_file_multi_fetch_max_buffer_size";

  private static final String MATERIALIZE_SOURCE_FILES_ON_DEMAND =
      "materialize_source_files_on_demand";

  @VisibleForTesting static final String SERVER_BUCKCONFIG_OVERRIDE = "server_buckconfig_override";

  private final SlbBuckConfig frontendConfig;
  private final BuckConfig buckConfig;

  public DistBuildConfig(BuckConfig config) {
    this.buckConfig = config;
    this.frontendConfig = new SlbBuckConfig(config, STAMPEDE_SECTION);
  }

  public SlbBuckConfig getFrontendConfig() {
    return frontendConfig;
  }

  public BuckConfig getBuckConfig() {
    return buckConfig;
  }

  public Optional<Long> getSourceFileMultiFetchBufferPeriodMs() {
    return buckConfig.getLong(STAMPEDE_SECTION, SOURCE_FILE_MULTI_FETCH_BUFFER_PERIOD_MS);
  }

  public Optional<Integer> getSourceFileMultiFetchMaxBufferSize() {
    return buckConfig.getInteger(STAMPEDE_SECTION, SOURCE_FILE_MULTI_FETCH_MAX_BUFFER_SIZE);
  }

  public boolean materializeSourceFilesOnDemand() {
    return buckConfig.getBooleanValue(STAMPEDE_SECTION, MATERIALIZE_SOURCE_FILES_ON_DEMAND, false);
  }

  public Optional<ImmutableList<String>> getOptionalPathWhitelist() {
    // Can't use getOptionalPathList here because sparse checkouts may mean we don't have all files
    // in other cells.
    return buckConfig.getOptionalListWithoutComments(
        STAMPEDE_SECTION, ALWAYS_MATERIALIZE_WHITELIST);
  }

  public Config getRemoteConfigWithOverride() {
    Optional<Path> serverConfigPath = getOptionalServerBuckconfigOverride();

    RawConfig.Builder rawConfigBuilder = RawConfig.builder();
    rawConfigBuilder.putAll(buckConfig.getConfig().getRawConfigForDistBuild());
    if (serverConfigPath.isPresent()) {
      try {
        rawConfigBuilder.putAll(Configs.parseConfigFile(serverConfigPath.get()));
        LOG.info("Applied server side config override [%s].", serverConfigPath.get().toString());
      } catch (IOException e) {
        throw new RuntimeException(
            String.format(
                "Unable to parse server-side config file (%s) specified in [%s:%s].",
                serverConfigPath.get().toString(), STAMPEDE_SECTION, SERVER_BUCKCONFIG_OVERRIDE),
            e);
      }
    }
    return new Config(rawConfigBuilder.build());
  }

  public Optional<Path> getOptionalServerBuckconfigOverride() {
    return buckConfig.getPath(STAMPEDE_SECTION, SERVER_BUCKCONFIG_OVERRIDE);
  }

  public long getFrontendRequestTimeoutMillis() {
    return buckConfig
        .getLong(STAMPEDE_SECTION, FRONTEND_REQUEST_TIMEOUT_MILLIS)
        .orElse(REQUEST_TIMEOUT_MILLIS_DEFAULT_VALUE);
  }

  public BuildMode getBuildMode() {
    return buckConfig
        .getEnum(STAMPEDE_SECTION, BUILD_MODE, BuildMode.class)
        .orElse(BUILD_MODE_DEFAULT_VALUE);
  }

  public int getNumberOfMinions() {
    return buckConfig
        .getInteger(STAMPEDE_SECTION, NUMBER_OF_MINIONS)
        .orElse(NUMBER_OF_MINIONS_DEFAULT_VALUE);
  }

  public Optional<String> getMinionQueue() {
    return buckConfig.getValue(STAMPEDE_SECTION, MINION_QUEUE);
  }

  public int getMaxBuildNodesPerMinion() {
    return buckConfig
        .getInteger(STAMPEDE_SECTION, MAX_BUILD_NODES_PER_MINION)
        .orElse(DEFAULT_MAX_BUILD_NODES_PER_MINION);
  }

  public String getRepository() {
    return buckConfig.getValue(STAMPEDE_SECTION, REPOSITORY).orElse(DEFAULT_REPOSITORY);
  }

  public String getTenantId() {
    return buckConfig.getValue(STAMPEDE_SECTION, TENANT_ID).orElse(DEFAULT_TENANT_ID);
  }

  public String getBuildLabel() {
    return buckConfig.getValue(STAMPEDE_SECTION, BUILD_LABEL).orElse(DEFAULT_BUILD_LABEL);
  }

  /**
   * Whether buck distributed build should stop building if remote/distributed build fails (true) or
   * if it should fallback to building locally if remote/distributed build fails (false).
   */
  public boolean isSlowLocalBuildFallbackModeEnabled() {
    return buckConfig.getBooleanValue(
        STAMPEDE_SECTION,
        ENABLE_SLOW_LOCAL_BUILD_FALLBACK,
        ENABLE_SLOW_LOCAL_BUILD_FALLBACK_DEFAULT_VALUE);
  }

  public OkHttpClient createOkHttpClient() {
    return new OkHttpClient.Builder()
        .connectTimeout(getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS)
        .readTimeout(getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS)
        .writeTimeout(getFrontendRequestTimeoutMillis(), TimeUnit.MILLISECONDS)
        .build();
  }
}


text:
{% if article.tags %}
{% for tag in article.tags %}
	{{ tag }}
{% endfor %}
{% endif %}


text:
package com.example.simon.if26.chat.adapters;

import android.content.Context;
import android.graphics.Color;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import com.example.simon.chat.R;
import com.example.simon.if26.chat.models.Message;

import java.util.ArrayList;

/**
 * Created by simon on 29/11/14.
 */
public class MessageAdapter extends ArrayAdapter<Message> {
    public MessageAdapter(Context context, ArrayList<Message> contacts) {
        super(context, 0, contacts);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Message message = getItem(position);

        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_message, parent, false);
        }

        TextView messageContent = (TextView) convertView.findViewById(R.id.message_content);
        TextView messageDate = (TextView) convertView.findViewById(R.id.message_date);

        if (message.isSent()) {
            messageContent.setTextColor(Color.parseColor("#0099cc"));
            messageContent.setGravity(Gravity.RIGHT);
            messageDate.setGravity(Gravity.RIGHT);
        }

        messageContent.setText(message.getContent());
        messageDate.setText(message.getDate());

        return convertView;
    }
}


text:
$(document).ready(function() {
    window['start_time'] = new Date();
    $("#timer").text("00:00:00.00");

    $("#timer").everyTime(10, function() {
        diff = (new Date()).getTime() - window['start_time'].getTime();

        seconds  = parseInt(diff / 1000);
        mseconds = diff % 1000;

        hours   = Math.floor(seconds / 3600);
        seconds = seconds % 3600;

        minutes = Math.floor(seconds / 60);
        seconds = seconds % 60;

        seconds  = seconds.toString();
        mseconds = mseconds.toString().substring(0, 2);
        hours    = hours.toString();
        minutes  = minutes.toString();

        if (seconds.length < 2) {
            seconds = "0" + seconds;
        }
        if (mseconds.length < 2) {
            mseconds = mseconds + "0";
        }
        if (hours.length < 2) {
            hours = "0" + hours;
        }
        if (minutes.length < 2) {
            minutes = "0" + minutes;
        }

        $(this).text(hours + ":" + minutes + ":" + seconds + "." + mseconds);
    });
});


text:
DROP SCHEMA cloudsat CASCADE;
CREATE SCHEMA cloudsat;
SET search_path TO cloudsat, public, pg_temp;
CREATE EXTENSION "uuid-ossp" SCHEMA cloudsat;
CREATE EXTENSION tablefunc SCHEMA cloudsat;

 ------------------------------------------------------------------------------
 -------------------------- Core Types & Functions ----------------------------
 ------------------------------------------------------------------------------

CREATE TABLE messages
( uuid      uuid PRIMARY KEY,
  timestamp timestamp with time zone NOT NULL,
  poster    text NOT NULL CHECK ( octet_length(poster)  <= 256 ),
  chan      text NOT NULL CHECK ( octet_length(chan)    <= 256 ),
  message   text NOT NULL CHECK ( octet_length(message) <= 4096 ) );
CREATE INDEX ON messages (timestamp);
CREATE INDEX ON messages USING hash(poster);
CREATE INDEX ON messages USING hash(chan);
CREATE INDEX ON messages USING gist(to_tsvector('simple', message));
CREATE INDEX ON messages (message);

CREATE TYPE disposition AS ENUM
( 'ignored', 'acknowledged', 'info', 'problem', 'done' );

CREATE TABLE threads
( before      uuid NOT NULL REFERENCES messages(uuid) ON DELETE CASCADE,
  disposition disposition NOT NULL,
  after       uuid NOT NULL REFERENCES messages(uuid) ON DELETE CASCADE );
 -- Foreign key allows us to cascade deletes of old messages.
CREATE INDEX ON threads (before);
CREATE INDEX ON threads USING hash(disposition);
CREATE INDEX ON threads (after);
COMMENT ON TABLE threads IS 'Links messages with their replies.';

CREATE TABLE registered
( nick          text NOT NULL,
  procpid       integer NOT NULL,
  backend_start timestamp with time zone NOT NULL,
  timestamp     timestamp with time zone NOT NULL,
  chans         text[] NOT NULL );
CREATE INDEX ON registered (nick);
CREATE INDEX ON registered (procpid);
CREATE INDEX ON registered (backend_start);
CREATE INDEX ON registered (timestamp);
CREATE INDEX ON registered (chans);
COMMENT ON TABLE registered IS
 'Explicit information about connected clients and their subscriptions.';

CREATE FUNCTION post(poster text, address text, message text)
RETURNS uuid AS $$
DECLARE
  id    uuid := uuid_generate_v1();
  chan  text := norm(address);
  pnorm text := norm(poster);
  t     timestamp with time zone := now();
  s     text := format(id, t, pnorm, chan, message);
BEGIN
  INSERT INTO messages VALUES (id, t, pnorm, chan, message);
  PERFORM pg_notify(chan, s);
  RETURN id;
END;
$$ LANGUAGE plpgsql STRICT SET search_path FROM CURRENT;
COMMENT ON FUNCTION post(poster text, address text, message text) IS
 'Creates a new thread on the message board with an initial message.';

CREATE FUNCTION reply
(poster text, address text, message text, parent uuid, disposition disposition)
RETURNS uuid AS $$
DECLARE
  id uuid;
BEGIN
  id := post(poster, address, message);
  INSERT INTO threads VALUES (parent, disposition, id);
  RETURN id;
END;
$$ LANGUAGE plpgsql STRICT SET search_path FROM CURRENT;
COMMENT ON FUNCTION reply
(poster text, address text, message text, parent uuid, disposition disposition)
IS 'Posts a reply in an existing thread, under the given message.';

CREATE FUNCTION posts(text[])
RETURNS SETOF messages AS $$
SELECT * FROM messages WHERE chan = ANY ($1);
$$ LANGUAGE sql STRICT;
COMMENT ON FUNCTION posts(text[]) IS
 'Searches for posts in the given channels.';

CREATE FUNCTION register(addresses text[])
RETURNS text[] AS $$
DECLARE
  empty    text[] := ARRAY[]::text[];
  nick     text   := addresses[1];
  suffixes text[] := suffixes(addresses);
  pid      integer;
  t        timestamp with time zone;
  stale    text[];
  chan     text;
BEGIN
  SELECT procpid, backend_start
    FROM pg_stat_activity
   WHERE procpid = pg_backend_pid()
    INTO STRICT pid, t;
  SELECT array_agg(pg_listening_channels)
    FROM pg_listening_channels()
   WHERE NOT pg_listening_channels = ANY (suffixes)
    INTO STRICT stale;
  IF NOT stale = empty THEN
    FOREACH chan IN ARRAY stale LOOP
      EXECUTE 'UNLISTEN ' || quote_ident(chan);
    END LOOP;
  END IF;
  IF NOT addresses = empty THEN
    PERFORM subscribe(suffixes);
    INSERT INTO registered VALUES (nick, pid, t, now(), suffixes);
  END IF;
  RETURN suffixes;
END;
$$ LANGUAGE plpgsql STRICT SET search_path FROM CURRENT;
COMMENT ON FUNCTION register(addresses text[]) IS
 'Create subscriptions and register client. The first address shall be taken to
  to be the "name" of the client.';

CREATE FUNCTION subscribe(chans text[])
RETURNS VOID AS $$
DECLARE
  chan text;
BEGIN
  FOREACH chan IN ARRAY chans LOOP
    EXECUTE 'LISTEN ' || quote_ident(chan);
  END LOOP;
END;
$$ LANGUAGE plpgsql STRICT SET search_path FROM CURRENT;
COMMENT ON FUNCTION subscribe(chans text[]) IS
 'Create subscriptions for a list of channels.';

CREATE FUNCTION root(uuid)
RETURNS uuid AS $$
DECLARE
  parent  uuid;
  present uuid := $1;
BEGIN
  LOOP
    SELECT before FROM threads WHERE after = present INTO parent;
    EXIT WHEN NOT FOUND;
    present := parent;
  END LOOP;
  RETURN present;
END;
$$ LANGUAGE plpgsql STRICT SET search_path FROM CURRENT;
COMMENT ON FUNCTION root(uuid) IS
 'Find the root of the thread this message is on. (The first message in a
  thread is its own root).';

 ------------------------------------------------------------------------------
 ----------------------- Utility Views and Functions --------------------------
 ------------------------------------------------------------------------------

CREATE FUNCTION norm(address text)
RETURNS text AS $$
BEGIN
  RETURN trim(leading '.' from lower(trim(trailing '.' from address))) || '.';
END;
$$ LANGUAGE plpgsql IMMUTABLE STRICT;
COMMENT ON FUNCTION norm(address text) IS
 'Normalize an address so it is lowercase and has the final dot.';

CREATE FUNCTION suffixes(address text)
RETURNS text[] AS $$
DECLARE
  str text := norm(address);
  pos int;
  res text[];
  dot text := '.';
BEGIN
  res := res || str;
  LOOP
    pos := position(dot in str);
    str := substring(str from pos+1);
    EXIT WHEN '' = str;
    res := res || str;
  END LOOP;
  res := res || dot;
  RETURN res;
END;
$$ LANGUAGE plpgsql IMMUTABLE STRICT;
COMMENT ON FUNCTION suffixes(address text) IS
 'Break an address like example.com into rooted pieces: ., com., example.com.';

CREATE FUNCTION suffixes(addresses text[])
RETURNS text[] AS $$
DECLARE
  acc     text[];
  address text;
BEGIN
  FOREACH address IN ARRAY addresses LOOP
    acc := acc || suffixes(address);
  END LOOP;
  RETURN uniq(acc);
END;
$$ LANGUAGE plpgsql IMMUTABLE STRICT;
COMMENT ON FUNCTION suffixes(addresses text[]) IS
 'Returns the unions of all suffixes of all the addresses.';

CREATE FUNCTION uniq(ANYARRAY)
RETURNS ANYARRAY AS $$
SELECT ARRAY( SELECT DISTINCT $1[s.i] FROM
              generate_series(array_lower($1,1), array_upper($1,1)) AS s(i) );
$$ LANGUAGE sql IMMUTABLE STRICT;
COMMENT ON FUNCTION uniq(ANYARRAY) IS
 'Ensures an array contains no duplicates.';

CREATE FUNCTION iso8601utc(t timestamp with time zone)
RETURNS text AS $$
BEGIN
  RETURN to_char(t AT TIME ZONE 'UTC', 'YYYY-MM-DD HH24:MI:SS.MS UTC');
END;
$$ LANGUAGE plpgsql IMMUTABLE STRICT;
COMMENT ON FUNCTION iso8601utc(t timestamp with time zone) IS
 'Returns a millisecond precision ISO 8601 UTC timestamp.';

CREATE FUNCTION format(uuid, timestamp with time zone, text, text, text)
RETURNS text AS $$
BEGIN
  RETURN $1::text||' '||iso8601utc($2)||' '||$3||' '||$4||' // '||$5;
END;
$$ LANGUAGE plpgsql IMMUTABLE STRICT;
COMMENT ON FUNCTION format(uuid, timestamp with time zone, text, text, text) IS
 'Render messages in an easily parseable text format.';

CREATE VIEW inbox AS
SELECT messages.* FROM messages, pg_listening_channels()
 WHERE chan = pg_listening_channels;
COMMENT ON VIEW inbox IS
 'Searches for posts which match the subscriptions of the present connection.';

CREATE VIEW threaded AS
SELECT threads.before, threads.disposition, messages.*
  FROM threads RIGHT OUTER JOIN messages ON threads.after = messages.uuid;
COMMENT ON VIEW threaded IS
 'Joined thread and message information for constructing message trees.';

CREATE TYPE branched AS ( path uuid[], disposition disposition,
                          timestamp timestamp with time zone,
                          poster text, chan text, message text );
CREATE FUNCTION thread(uuid)
RETURNS SETOF branched AS $$
SELECT string_to_array(branch,'/')::uuid[], disposition,
       timestamp, poster, chan, message
  FROM connectby('threaded', 'uuid', 'before', $1::text, 0, '/')
        AS t(uuid uuid, parent uuid, depth int, branch text)
       NATURAL JOIN threaded;
$$ LANGUAGE sql STRICT;
COMMENT ON FUNCTION thread(uuid) IS
 'Retrieve the thread rooted at a particular message.';

CREATE VIEW recent AS
SELECT nick, procpid, backend_start, timestamp, chans FROM
( SELECT registered.*, rank()
    OVER (PARTITION BY nick ORDER BY timestamp DESC) FROM registered
) AS intermediate WHERE rank = 1;
COMMENT ON VIEW recent IS
 'Most up to date record for each registered (or unregistered) client.';

CREATE VIEW connections AS
WITH r AS
( SELECT nick, procpid, backend_start, timestamp, chans FROM
  ( SELECT recent.*, rank()
      OVER (PARTITION BY procpid ORDER BY timestamp DESC) FROM recent
  ) AS intermediate WHERE rank = 1 )
SELECT * FROM r NATURAL JOIN pg_stat_activity;
COMMENT ON VIEW connections IS
 'Connection info for every active client.';

 ------------------------------------------------------------------------------
 ----------------------- Advisory Locks for Messages --------------------------
 ------------------------------------------------------------------------------

CREATE TABLE lock_log
( locked    uuid NOT NULL REFERENCES messages(uuid) ON DELETE CASCADE,
  locking   uuid NOT NULL REFERENCES messages(uuid) ON DELETE CASCADE,
  timestamp timestamp with time zone NOT NULL,
  sets_lock bool NOT NULL );
CREATE INDEX ON lock_log (timestamp);
CREATE INDEX ON lock_log USING hash(locked);
CREATE INDEX ON lock_log USING hash(locking);
COMMENT ON TABLE lock_log IS
 'Audit log of successful locks and unlocks of messages.';

CREATE VIEW locks AS SELECT locked, locking, timestamp FROM
( SELECT lock_log.*, rank()
    OVER (PARTITION BY locked ORDER BY timestamp DESC) FROM lock_log
) AS intermediate WHERE sets_lock AND rank = 1;
COMMENT ON VIEW locks IS 'Messages with active locks.';

CREATE FUNCTION locking
( poster text, chan text, message text, parent uuid, disposition disposition )
RETURNS uuid AS $$
BEGIN
  RETURN set_or_unset_lock(poster, chan, message, parent, disposition, TRUE);
END;
$$ LANGUAGE plpgsql STRICT SET search_path FROM CURRENT;
COMMENT ON FUNCTION locking
(poster text, chan text, message text, parent uuid, disposition disposition) IS
 'Try to lock a message and reply to it. If a lock is possible, the UUID of
  the stored reply is returned. If not, the null UUID is returned and nothing
  is stored.';

CREATE FUNCTION unlocking
( poster text, chan text, message text, parent uuid, disposition disposition )
RETURNS uuid AS $$
BEGIN
  RETURN set_or_unset_lock(poster, chan, message, parent, disposition, FALSE);
END;
$$ LANGUAGE plpgsql STRICT SET search_path FROM CURRENT;
COMMENT ON FUNCTION unlocking
(poster text, chan text, message text, parent uuid, disposition disposition) IS
 'Try to unlock a message and reply to it. If it is locked, then the lock is
  unset, a new reply is stored and its UUID is returned. If the message is
  already unlocked, then the null UUID is returned.';

CREATE FUNCTION set_or_unset_lock
( poster text, chan text, message text, parent uuid, disposition disposition,
  setting bool )
RETURNS uuid AS $$
DECLARE
  id uuid;
BEGIN
  CASE EXISTS ( SELECT * FROM locks WHERE locked = parent )
  WHEN setting THEN
    -- We are trying lock a locked lock or unlock and unlocked lock.
    RETURN '00000000-0000-0000-0000-000000000000';
  ELSE
    id := reply(poster, chan, message, parent, disposition);
    INSERT INTO lock_log VALUES (parent, id, now(), setting);
    RETURN id;
  END CASE;
END;
$$ LANGUAGE plpgsql STRICT SET search_path FROM CURRENT;
COMMENT ON FUNCTION set_or_unset_lock
( poster text, chan text, message text, parent uuid, disposition disposition,
  setting bool ) IS 'Implementation behind locking() and unlocking().';


text:
id: 52-Smarty-_SERVER-vars
author: matthew
title: 'Smarty $_SERVER vars'
draft: false
public: true
created: '2004-12-31T23:00:38-05:00'
updated: '2004-12-31T23:04:45-05:00'
tags:
    - personal
    - php
---
I don't know why I never bothered to look this up, but I didn't. One thing I
typically do in my parent Cgiapp classes is to pass `$_SERVER['SCRIPT_NAME']`
to the template. I just found out — through the pear-general newsgroup — that
this is unnecessary: use `$smarty.server.KEY_NAME` to access any `$_SERVER` vars
your template might need.


text:
<?xml version="1.0" encoding="utf-8" ?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">

    <camelContext id="timer-test" xmlns="http://camel.apache.org/schema/blueprint">
        <route>
            <from uri="timer:test" />
            <to uri="log:test" />
        </route>
    </camelContext>

    <reference id="interceptStragety" interface="org.apache.camel.spi.InterceptStrategy" />

</blueprint>


text:
ACCEPTED

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

#### Published in
Bull. Br. Mus. Nat. Hist. (Geol. ) 18: 306.

#### Original name
null

### Remarks
null


text:
<?php

namespace Map\Http\Controllers;

use Doctrine\Common\Cache\Cache;
use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Views\Twig;

class MapController
{
    /**
     * @var Twig
     */
    private $twig;

    /**
     * @var Cache
     */
    private $cache;

    /**
     * MapController constructor.
     * @param Twig $twig
     * @param Cache $cache
     */
    public function __construct(Twig $twig, Cache $cache)
    {
        $this->twig = $twig;
        $this->cache = $cache;
    }

    /**
     * @param Request $request
     * @param Response $response
     * @return mixed
     */
    public function index(Request $request, Response $response)
    {
        return $this->twig->render($response, 'map/index.twig');
    }

    /**
     * @param Request $request
     * @param Response $response
     * @return static
     */
    public function clearCache(Request $request, Response $response)
    {
        $this->cache->delete('nodes');

        return $response
            ->withStatus(302)
            ->withHeader('Location', (string) '/');
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:minHeight="?android:attr/listPreferredItemHeight"
	android:paddingLeft="@dimen/large_gutter"
	android:paddingRight="@dimen/large_gutter"
	android:paddingTop="@dimen/small_gutter"
	android:paddingBottom="@dimen/small_gutter"
	>
	<TextView
		android:id="@id/row_title"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:layout_alignParentTop="true"
		android:layout_alignParentLeft="true"
		style="@style/row_text"
		>
	</TextView>
	<TextView
		android:id="@id/row_description"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_below="@id/row_title"
		android:layout_alignParentLeft="true"
		android:layout_marginTop="@dimen/small_gutter"
		style="@style/row_text_small"
		>
	</TextView>
	<TextView
		android:id="@id/row_extra"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_alignParentRight="true"
		android:layout_alignParentBottom="true"
		style="@style/row_text_small"
		>
	</TextView>
</RelativeLayout>


text:
const c = require('./../schemas')

const ThangTypeSchema = (title, description) => c.object({
  title,
  description,
  required: ['type']
}, {
  type: {
    oneOf: [
      c.shortString({
        title: 'Hero',
        description: 'Hero ThangType Id computed at runtime',
        enum: ['hero', 'avatar']
      }),
      c.object({
        title: 'Character Slug',
        description: 'The slug of the Character Thangtype.',
        required: ['slug']
      }, {
        slug: c.shortString({
          title: 'Slug',
          description: 'The thangType slug of the asset. Only required if this isn\'t the player hero.'
        })
      })
    ]
  },
  scaleX: c.float({
    title: 'scaleX',
    description: 'The scaling factor along x axis to apply to the ThangType'
  }),
  scaleY: c.float({
    title: 'scaleY',
    description: 'The scaling factor along y axis to apply to the ThangType'
  }),
  pos: c.point2d({
    title: 'Position',
    description: 'The position in meters to place the thangType.'
  })
})

const CharacterSchema = (title) => c.object({
  title: title,
  description: 'ThangType that will appear on either the left or right side of the screen.',
  required: ['thangType']
}, {
  thangType: ThangTypeSchema('Character', 'The thangType to display for this character'),
  enterOnStart: {
    type: 'boolean',
    title: 'Animate in?',
    description: 'If true the character will animate in. Otherwise the character will start simply there.'
  }
})

const ShotSetup = c.object({
  title: 'ShotSetup'
}, {
  rightThangType: CharacterSchema('Right Character'),
  leftThangType: CharacterSchema('Left Character'),
  heroPetThangType: ThangTypeSchema('Hero Pet', 'The position property will be used to place the dog at an offset on the right lank.'),
  backgroundArt: ThangTypeSchema('Background Art', 'The rasterized image to place on the background'),
  camera: c.object({
    title: 'Camera placement',
    description: 'Where to place the camera at the beginning of the shot'
  }, {
    pos: c.point2d({
      title: 'Position',
      description: 'The position of the camera in meters.'
    }),
    zoom: {
      title: 'Zoom',
      description: 'The zoom level of the camera. A good default is \'2.01\'. There is a bug with the value 2. Recommended you change between 0 and 10.',
      type: 'number'
    }
  }),
  music: c.sound()
})

const DialogNode = c.object({
  title: 'Dialog Node',
  description: 'A node of a shot. Contains dialog instructions.'
}, {
  speaker: c.shortString({ enum: ['left', 'right'], title: 'Speaker', description: 'Which character is speaking. Used to select speech bubble.' }),
  text: { type: 'string', title: 'Text', description: 'html text', maxLength: 500 },
  textAnimationLength: c.int({ title: 'Text Animation Length(ms)', description: 'The number of milliseconds it takes for the text to animate in.' }),
  speakingAnimationAction: c.shortString({ title: 'Speaking Animation', description: 'The animation to play on the lank while the text is being animated.' }),
  i18n: { type: 'object', format: 'i18n', props: ['text'], description: 'Help translate this cinematic dialogNode.' },
  waitUserInput: { type: 'boolean', title: 'User Input?', description: 'Whether or not user input is required to continue to the next dialog node or shot setup. Defaults to true.' },
  textLocation: c.object({ title: 'Text Location', description: 'An {x, y} coordinate point.', format: 'point2d', required: ['x', 'y'] }, {
    x: { title: 'x', description: 'The x coordinate.', type: 'number', 'default': 0 },
    y: { title: 'y', description: 'The y coordinate.', type: 'number', 'default': 0 } }),
  programmingLanguageFilter: c.shortString({ enum: ['python', 'javascript'], title: 'Programming Language Filter', description: 'If set, this node is only shown if the user is using the programming language selected.' }),
  triggers: c.object({
    title: 'Triggers',
    description: 'Events that can occur during the dialogue.'
  }, {
    backgroundObject: c.object({
      title: 'Background Object',
      description: 'Add a background object after given duration',
      required: ['thangType', 'triggerStart']
    }, {
      thangType: ThangTypeSchema('Background Object', 'The image to place'),
      triggerStart: c.int({ title: 'Trigger Start(ms)', description: 'The number of milliseconds until background image art appears' })
    }),
    clearBackgroundObject: c.object({
      title: 'Clear Background Object',
      description: 'Clears the background objects from the screen after a given duration'
    }, {
      triggerStart: c.int({ title: 'Trigger Start(ms)', description: 'The number of milliseconds until background object is cleared' })
    }),
    soundFxTriggers: c.array({
      title: 'SoundFX triggers',
      description: 'A list of sound effects that we can play. Unlike music they will overlap and wont prevent other sounds playing.'
    },
    c.object({
      title: 'Sound Effect',
      description: 'A sound effect that plays after a delay.',
      required: ['sound']
    }, {
      sound: c.sound(),
      triggerStart: c.int({ title: 'Trigger Start(ms)', description: 'The number of milliseconds until the sound effect is played' })
    }))
  }),
  dialogClear: {
    type: 'boolean',
    title: 'Clear dialog on screen',
    description: 'Whether we clear any existing dialog nodes.'
  },
  exitCharacter: c.shortString({ title: 'Exit Character', description: 'whether character exits at dialog node completion', enum: ['left', 'right', 'both'] })
})

const Shot = c.object({
  title: 'Shot',
  description: 'A single shot, setting up camera and running dialog nodes'
}, {
  shotSetup: ShotSetup,
  dialogNodes: c.array({
    title: 'Dialog Nodes',
    description: 'List of all possible nodes in the shot.'
  }, DialogNode)
})

const CinematicSchema = c.object({
  description: 'A cinematic composed of shots.',
  title: 'Cinematic'
}, {
  shots: c.array({
    title: 'Shots',
    description: 'Ordered list of shots that make up a cinematic'
  }, Shot)
})

c.extendBasicProperties(CinematicSchema, 'cinematic')
c.extendNamedProperties(CinematicSchema)

module.exports = CinematicSchema


text:
using System;
using System.Collections.Generic;
using System.Numerics;

namespace RubberPlant
{
    public class Turtle
    {
        public IGenerator Generator { get; set; }

        // Angle is stored and consumed internally in radians, but exposed externally as degrees.
        private float m_angle;
        public float Angle
        {
            get { return MathHelpers.RadToDeg(m_angle); }
            set
            {
                m_angle = MathHelpers.DegToRad(value);
                m_turnLeft = Matrix4x4.CreateRotationZ(m_angle);
                m_turnRight = Matrix4x4.CreateRotationZ(-m_angle);
            }
        }

        private float m_stepLength;
        public float StepLength
        {
            get { return m_stepLength; }
            set
            {
                m_stepLength = value;
                m_translate = Matrix4x4.Identity;
                m_translate.Translation = new Vector3(m_stepLength, 0, 0);
            }
        }

        private Matrix4x4 m_currentState;

        private readonly Stack<Matrix4x4> m_states = new Stack<Matrix4x4>();

        // Operation matrices
        private Matrix4x4 m_translate;
        private Matrix4x4 m_turnLeft;
        private Matrix4x4 m_turnRight;

        public Turtle()
        {
            m_currentState = Matrix4x4.CreateRotationZ((float)Math.PI/2);
            StepLength = 1;
        }

        public void Generate(string outputDir, string lsysName, IEnumerable<TurtleCommand> commands)
        {
            if (Generator == null)
            {
                return;
            }

            Generator.StartGenerate(outputDir, lsysName);

            foreach (var command in commands)
            {
                switch (command)
                {
                    case TurtleCommand.Move:
                        m_currentState = m_translate * m_currentState;
                        break;

                    case TurtleCommand.Draw:
                        Generator.DrawSegment(m_currentState, StepLength);
                        m_currentState = m_translate * m_currentState;
                        break;

                    case TurtleCommand.TurnLeft:
                        m_currentState = m_turnLeft * m_currentState;
                        break;

                    case TurtleCommand.TurnRight:
                        m_currentState = m_turnRight * m_currentState;
                        break;

                    case TurtleCommand.StartBranch:
                        m_states.Push(m_currentState);
                        break;

                    case TurtleCommand.EndBranch:
                        if (m_states.Count > 0)
                        {
                            m_currentState = m_states.Pop();
                        }
                        break;

                    case TurtleCommand.Nop:
                        // nothing
                        break;

                    default:
                        throw new ArgumentException(string.Format("Command {0} isn't supported yet.", command));
                }
            }

            Generator.EndGenerate();
        }
    }
}


text:
var searchData=
[
  ['wizardcodegenerator',['WizardCodeGenerator',['../class_visual_entity_designer_tools_1_1_code_gen_1_1_wizard_code_generator.html#aa6dbb21f3ce89344119ed2f53a9b873c',1,'VisualEntityDesignerTools::CodeGen::WizardCodeGenerator']]]
];


text:
package org.vanilladb.core.remote.jdbc;

import java.sql.SQLException;

/**
 * An adapter class that wraps RemoteMetaData. Its methods do nothing except
 * transform RemoteExceptions into SQLExceptions.
 */
public class JdbcMetaData extends ResultSetMetaDataAdapter {
	private RemoteMetaData rmd;

	public JdbcMetaData(RemoteMetaData md) {
		rmd = md;
	}

	public int getColumnCount() throws SQLException {
		try {
			return rmd.getColumnCount();
		} catch (Exception e) {
			throw new SQLException(e);
		}
	}

	public String getColumnName(int column) throws SQLException {
		try {
			return rmd.getColumnName(column);
		} catch (Exception e) {
			throw new SQLException(e);
		}
	}

	public int getColumnType(int column) throws SQLException {
		try {
			return rmd.getColumnType(column);
		} catch (Exception e) {
			throw new SQLException(e);
		}
	}

	public int getColumnDisplaySize(int column) throws SQLException {
		try {
			return rmd.getColumnDisplaySize(column);
		} catch (Exception e) {
			throw new SQLException(e);
		}
	}
}


text:
// @ts-nocheck
// TODO(crbug.com/1011811): Enable TypeScript compiler checks

import * as Common from '../common/common.js';  // eslint-disable-line no-unused-vars
import * as TextUtils from '../text_utils/text_utils.js';

import {MultitargetNetworkManager} from './NetworkManager.js';

/**
 * @implements {TextUtils.ContentProvider.ContentProvider}
 * @unrestricted
 */
export class CompilerSourceMappingContentProvider {
  /**
   * @param {string} sourceURL
   * @param {!Common.ResourceType.ResourceType} contentType
   */
  constructor(sourceURL, contentType) {
    this._sourceURL = sourceURL;
    this._contentType = contentType;
  }

  /**
   * @override
   * @return {string}
   */
  contentURL() {
    return this._sourceURL;
  }

  /**
   * @override
   * @return {!Common.ResourceType.ResourceType}
   */
  contentType() {
    return this._contentType;
  }

  /**
   * @override
   * @return {!Promise<boolean>}
   */
  contentEncoded() {
    return Promise.resolve(false);
  }

  /**
   * @override
   * @return {!Promise<!TextUtils.ContentProvider.DeferredContent>}
   */
  requestContent() {
    return new Promise(resolve => {
      MultitargetNetworkManager.instance().loadResource(
          this._sourceURL, (success, _headers, content, errorDescription) => {
            if (!success) {
              const error = ls`Could not load content for ${this._sourceURL} (${errorDescription.message})`;
              console.error(error);
              resolve({error, isEncoded: false});
            } else {
              resolve({content, isEncoded: false});
            }
          });
    });
  }

  /**
   * @override
   * @param {string} query
   * @param {boolean} caseSensitive
   * @param {boolean} isRegex
   * @return {!Promise<!Array<!TextUtils.ContentProvider.SearchMatch>>}
   */
  async searchInContent(query, caseSensitive, isRegex) {
    const {content} = await this.requestContent();
    if (typeof content !== 'string') {
      return [];
    }
    return TextUtils.TextUtils.performSearchInContent(content, query, caseSensitive, isRegex);
  }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('micro_admin', '0012_groupmemberloanaccount_status'),
    ]

    operations = [
        migrations.AddField(
            model_name='groupmemberloanaccount',
            name='loan_issued_date',
            field=models.DateField(blank=True, null=True),
        ),
    ]


text:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UPS.SDK.TNT
{
    public partial class TNTShipmentWeightEntity
    {
        public TNTShipmentWeightEntity()
        {
            UnitOfMeasurement = new JObject();
            UnitOfMeasurement.Add("Code", "LBS");
            UnitOfMeasurement.Add("Description", "pounds");
        }

        public string Weight { get; set; }

        public JObject UnitOfMeasurement { get; set; }
    }
}


text:
#import <Foundation/Foundation.h>

@interface Crypto:NSObject {
}

+(NSData *)decrypt:(NSString *)data key:(NSString *)key;
+(NSData *)aes128Decrypt:(NSData *)data key:(NSData *)key withIV:(NSData *)iv;

+(NSData *)hexDecode:(NSString *)hexString;
+(NSString *)hexEncode:(NSString *)string;

+(NSString *)generateRandomString;

@end


text:
/**
* GuestUser.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs        :: http://sailsjs.org/#!documentation/models
*/

module.exports = {

  attributes: {
  	name: 'string',
  	age: 'string',
  	sex: 'string',

  	borough: {
  		model: 'borough'
  	},

    votes: {
      collection: 'vote',
      via: 'guestUser'
    },
  }
};


text:
package com.mhq0123.officialwebsite.microservice.customer.account.mapper;

import com.mhq0123.officialwebsite.microservice.customer.invoker.account.bean.CustomerAccount;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;

/**
 * project: mhq0123-officialwebsite
 * author:  mhq0123
 * date:    2016/12/30.
 * desc:
 */
@Mapper
public interface CustomerAccountMapper {

    /**
     * 单个写入
     * @param insertBean
     * @return
     */
    int insert(CustomerAccount insertBean);

    /**
     * 根据索引编号删除
     * @param accountId
     * @return
     */
    @CacheEvict(value = "CustomerAccount", key="'accountId_'+#accountId")
    int deleteById(int accountId);

    /**
     * 根据索引编号修改
     * @param updateBean
     * @return
     */
    @CacheEvict(value = "CustomerAccount", key="'accountId_'+#p0.getAccountId()")
    int updateById(CustomerAccount updateBean);

    /**
     * 根据编号查询单个
     * @param accountId
     * @return
     */
    @Cacheable(value = "CustomerAccount", key="'accountId_'+#accountId")
    CustomerAccount selectById(@Param("accountId") int accountId);

    /**
     * 根据用户名查询单个
     * @param accountName
     * @return
     */
    CustomerAccount selectByName(@Param("accountName") String accountName);

    /**
     * 根据邮箱查询单个
     * @param email
     * @return
     */
    CustomerAccount selectByEmail(@Param("email") String email);
}


text:
/// <reference path="../_references.ts"/>

module powerbi.visuals {
    /**
     * This is the baseline for some most common used object properties across visuals.
     * When adding new properties, please try to reuse the existing ones.
     */
    export const StandardObjectProperties = {
        axisEnd: {
            displayName: data.createDisplayNameGetter('Visual_Axis_End'),
            description: data.createDisplayNameGetter('Visual_Axis_EndDescription'),
            placeHolderText: data.createDisplayNameGetter('Visual_Precision_Auto'),
            type: { numeric: true },
            suppressFormatPainterCopy: true,
        },
        axisScale: {
            displayName: data.createDisplayNameGetter('Visual_Axis_Scale'),
            type: { enumeration: axisScale.type }
        },
        axisStart: {
            displayName: data.createDisplayNameGetter('Visual_Axis_Start'),
            description: data.createDisplayNameGetter('Visual_Axis_StartDescription'),
            placeHolderText: data.createDisplayNameGetter('Visual_Precision_Auto'),
            type: { numeric: true },
            suppressFormatPainterCopy: true,
        },
        axisStyle: {
            displayName: data.createDisplayNameGetter('Visual_Axis_Style'),
            type: { enumeration: axisStyle.type }
        },
        axisType: {
            displayName: data.createDisplayNameGetter('Visual_Axis_Type'),
            type: { enumeration: axisType.type },
        },
        backColor: {
            displayName: data.createDisplayNameGetter('Visual_Tablix_BackColor'),
            description: data.createDisplayNameGetter('Visual_Tablix_BackColor_Desc'),
            type: { fill: { solid: { color: true } } }
        },
        dataColor: {
            displayName: data.createDisplayNameGetter('Visual_LabelsFill'),
            description: data.createDisplayNameGetter('Visual_LabelsFillDescription'),
            type: { fill: { solid: { color: true } } }
        },
        dataLabelColor: {
            displayName: data.createDisplayNameGetter("Visual_Reference_Line_Data_Label_Color"),
            description: data.createDisplayNameGetter('Visual_Reference_Line_Data_Label_Color_Description'),
            type: { fill: { solid: { color: true } } }
        },
        dataLabelDecimalPoints: {
            displayName: data.createDisplayNameGetter("Visual_Reference_Line_Data_Decimal_Points"),
            placeHolderText: data.createDisplayNameGetter('Visual_Precision_Auto'),
            type: { numeric: true }
        },
        dataLabelDisplayUnits: {
            displayName: data.createDisplayNameGetter('Visual_DisplayUnits'),
            description: data.createDisplayNameGetter('Visual_DisplayUnitsDescription'),
            type: { formatting: { labelDisplayUnits: true } },
            suppressFormatPainterCopy: true,
        },
        dataLabelHorizontalPosition: {
            displayName: data.createDisplayNameGetter("Visual_Reference_Line_Data_Horizontal_Position"),
            description: data.createDisplayNameGetter('Visual_Reference_Line_Data_Label_Horizontal_Position_Description'),
            type: { enumeration: referenceLineDataLabelHorizontalPosition.type }
        },
        dataLabelShow: {
            displayName: data.createDisplayNameGetter("Visual_Reference_Line_Data_Label"),
            description: data.createDisplayNameGetter('Visual_Reference_Line_Data_Label_Show_Description'),
            type: { bool: true }
        },
        dataLabelVerticalPosition: {
            displayName: data.createDisplayNameGetter("Visual_Reference_Line_Data_Vertical_Position"),
            description: data.createDisplayNameGetter('Visual_Reference_Line_Data_Label_Vertical_Position_Description'),
            type: { enumeration: referenceLineDataLabelVerticalPosition.type }
        },
        defaultColor: {
            displayName: data.createDisplayNameGetter('Visual_DefaultColor'),
            type: { fill: { solid: { color: true } } }
        },
        fill: {
            displayName: data.createDisplayNameGetter('Visual_Fill'),
            type: { fill: { solid: { color: true } } }
        },
        fontColor: {
            displayName: data.createDisplayNameGetter('Visual_FontColor'),
            description: data.createDisplayNameGetter('Visual_Tablix_FontColor_Desc'),
            type: { fill: { solid: { color: true } } }
        },
        fontSize: {
            displayName: data.createDisplayNameGetter('Visual_TextSize'),
            type: { formatting: { fontSize: true } }
        },
        formatString: {
            type: { formatting: { formatString: true } },
        },
        image: {
            type: { image: {} },
        },
        labelColor: {
            displayName: data.createDisplayNameGetter('Visual_LegendTitleColor'),
            type: { fill: { solid: { color: true } } }
        },
        labelDisplayUnits: {
            displayName: data.createDisplayNameGetter('Visual_DisplayUnits'),
            description: data.createDisplayNameGetter('Visual_DisplayUnitsDescription'),
            type: { formatting: { labelDisplayUnits: true } }
        },
        labelPrecision: {
            displayName: data.createDisplayNameGetter('Visual_Precision'),
            description: data.createDisplayNameGetter('Visual_PrecisionDescription'),
            placeHolderText: data.createDisplayNameGetter('Visual_Precision_Auto'),
            type: { numeric: true }
        },
        legendPosition: {
            displayName: data.createDisplayNameGetter('Visual_LegendPosition'),
            description: data.createDisplayNameGetter('Visual_LegendPositionDescription'),
            type: { enumeration: legendPosition.type },
        },
        legendTitle: {
            displayName: data.createDisplayNameGetter('Visual_LegendName'),
            description: data.createDisplayNameGetter('Visual_LegendNameDescription'),
            type: { text: true },
        },
        lineColor: {
            displayName: data.createDisplayNameGetter('Visual_Reference_Line_Color'),
            description: data.createDisplayNameGetter('Visual_Reference_Line_Color_Description'),
            type: { fill: { solid: { color: true } } }
        },
        outline: {
            displayName: data.createDisplayNameGetter('Visual_Outline'),
            type: { enumeration: outline.type }
        },
        outlineColor: {
            displayName: data.createDisplayNameGetter('Visual_OutlineColor'),
            description: data.createDisplayNameGetter('Visual_OutlineColor_Desc'),
            type: { fill: { solid: { color: true } } }
        },
        outlineWeight: {
            displayName: data.createDisplayNameGetter('Visual_OutlineWeight'),
            description: data.createDisplayNameGetter('Visual_OutlineWeight_Desc'),
            type: { numeric: true }
        },
        show: {
            displayName: data.createDisplayNameGetter('Visual_Show'),
            type: { bool: true }
        },
        showAllDataPoints: {
            displayName: data.createDisplayNameGetter('Visual_DataPoint_Show_All'),
            type: { bool: true }
        },
        showLegendTitle: {
            displayName: data.createDisplayNameGetter('Visual_LegendShowTitle'),
            description: data.createDisplayNameGetter('Visual_LegendShowTitleDescription'),
            type: { bool: true }
        },
        referenceLinePosition: {
            displayName: data.createDisplayNameGetter('Visual_Reference_Line_Arrange'),
            description: data.createDisplayNameGetter('Visual_Reference_Line_Arrange_Description'),
            type: { enumeration: referenceLinePosition.type }
        },
        referenceLineStyle: {
            displayName: data.createDisplayNameGetter('Visual_Reference_Line_Style'),
            description: data.createDisplayNameGetter('Visual_Reference_Line_Style_Description'),
            type: { enumeration: lineStyle.type }
        },
        transparency: {
            displayName: data.createDisplayNameGetter('Visual_Background_Transparency'),
            description: data.createDisplayNameGetter('Visual_Background_TransparencyDescription'),
            type: { numeric: true }
        },
        yAxisPosition: {
            displayName: data.createDisplayNameGetter('Visual_YAxis_Position'),
            description: data.createDisplayNameGetter('Visual_YAxis_PositionDescription'),
            type: { enumeration: yAxisPosition.type },
        },
    };
}


text:
local assert, pcall, setmetatable, getmetatable, pairs, next, rawget, rawset,
type, select, error
   = assert, pcall, setmetatable, getmetatable, pairs, next, rawget, rawset,
type, select, error

local table = require 'table'
local string = require 'string'
local core = require 'lgi.core'

-- Generic component metatable.  Component is any entity in the repo,
-- e.g. record, object, enum, etc.
local component = { mt = {} }

-- Creates new component table by cloning all contents and setting
-- Gets table for category of compound (i.e. _field of struct or _property
-- for class etc).  Installs metatable which performs on-demand lookup of
-- symbols.
function component.get_category(children, xform_value,
				xform_name, xform_name_reverse)
   -- Either none or both transform methods must be provided.
   assert(not xform_name or xform_name_reverse)

   -- Early shortcircuit; no elements, no table needed at all.
   if #children == 0 then return nil end

   -- Index contains array of indices which were still not retrieved
   -- from 'children' table, and table part contains name->index
   -- mapping.
   local index, mt = {}, {}
   for i = 1, #children do index[i] = i end

   -- Fully resolves the category (i.e. loads everything remaining to
   -- be loaded in given category) and disconnects on-demand loading
   -- metatable.
   local function resolve(category)
      -- Load al values from unknown indices.
      local ei, en, val
      local function xvalue(arg)
	 if not xform_value then return arg end
	 if arg then
	    local ok, res = pcall(xform_value, arg)
	    return ok and res
	 end
      end
      while #index > 0 do
	 ei = children[table.remove(index)]
	 val = xvalue(ei)
	 if val then
	    en = ei.name
	    en = not xform_name_reverse and en or xform_name_reverse(en)
	    if en then category[en] = val end
	 end
      end

      -- Load all known indices.
      for en, idx in pairs(index) do
	 val = xvalue(children[idx])
	 en = not xform_name_reverse and en or xform_name_reverse(en)
	 if en then category[en] = val end
      end

      -- Metatable is no longer needed, disconnect it.
      return setmetatable(category, nil)
   end

   function mt:__index(requested_name)
      -- Check if closure for fully resolving the category is needed.
      if requested_name == '_resolve' then return resolve end

      -- Transform name by transform function.
      local name = not xform_name and requested_name
	 or xform_name(requested_name)
      if not name then return end

      -- Check, whether we already know its index.
      local idx, val = index[name]
      if idx then
	 -- We know at least the index, so get info directly.
	 val = children[idx]
	 index[name] = nil
      else
	 -- Not yet, go through unknown indices and try to find the
	 -- name.
	 while #index > 0 do
	    idx = table.remove(index)
	    val = children[idx]
	    local en = val.name
	    if en == name then break end
	    val = nil
	    index[en] = idx
	 end
      end

      -- If there is nothing in the index, we can disconnect
      -- metatable, because everything is already loaded.
      if not next(index) then
	 setmetatable(self, nil)
      end

      -- Transform found value and store it into the category (self)
      -- table.
      if not val then return nil end
      if xform_value then val = xform_value(val) end
      if not val then return nil end
      self[requested_name] = val
      return val
   end
   return setmetatable({}, mt)
end

-- Creates new component table by cloning all contents and setting
-- categories table.
function component.mt:clone(type, categories)
   local new_component = {}
   for key, value in pairs(self) do new_component[key] = value end
   new_component._type = type
   if categories then
      table.insert(categories, 1, '_attribute')
      new_component._categories = categories
   end
   return new_component
end

-- __call implementation, uses _new method to create new instance of
-- component type.
function component.mt:__call(...)
   return self:_new(...)
end

-- Fully resolves the whole typetable, i.e. load all symbols normally
-- loaded on-demand at once.  Returns self, so that resolve can be
-- easily chained for the caller.
function component.mt:_resolve()
   local categories = self._categories or {}
   for i = 1, #categories do
      -- Invoke '_resolve' function for all category tables, if they have it.
      local category = rawget(self, categories[i])
      local resolve = type(category) == 'table' and category._resolve
      if resolve then resolve(category) end
   end
   return self
end

-- Implementation of _access method, which is called by _core when
-- instance of repo-based type is accessed for reading or writing.
function component.mt:_access(instance, symbol, ...)
   -- Invoke _element, which converts symbol to element and category.
   local element, category = self:_element(instance, symbol)
   if not element then
      error(("%s: no `%s'"):format(self._name, tostring(symbol)), 3)
   end

   -- Get category handler to be used, and invoke it.
   if category then
      local handler = self['_access' .. category]
      if handler then return handler(self, instance, element, ...) end
   end

   -- If specific accessor does not exist, consider the element to be
   -- 'static const' attribute of the class.  This works well for
   -- methods, constants and assorted other elements added manually
   -- into the class by overrides.
   if select('#', ...) > 0 then
      error(("%s: `%s' is not writable"):format(self._name, symbol), 4)
   end
   return element
end

-- Keyword translation dictionary.  Used for translating Lua keywords
-- which might appear as symbols in typelibs into Lua-neutral identifiers.
local keyword_dictionary = {
   _end = 'end', _do = 'do', _then = 'then', _elseif = 'elseif', _in = 'in',
   _local = 'local', _function = 'function', _nil = 'nil', _false = 'false',
   _true = 'true', _and = 'and', _or = 'or', _not = 'not',
}

-- Retrieves (element, category) pair from given componenttable and
-- instance for given symbol.
function component.mt:_element(instance, symbol, origin)
   -- This generic version can work only with strings.  Refuse
   -- everything other, hoping that some more specialized _element
   -- implementation will handle it.
   if type(symbol) ~= 'string' then return end

   -- Check keyword translation dictionary.  If the symbol can be
   -- found there, try to lookup translated symbol.
   symbol = keyword_dictionary[symbol] or symbol

   -- Check whether symbol is directly accessible in the component.
   local element = rawget(self, symbol)
   if element then return element end

   -- Check whether symbol is accessible in cached directory of the
   -- component, packed as element value and category
   local cached = rawget(self, '_cached')
   if cached then
      element = cached[symbol]
      if element then return element[1], element[2] end
   end

   -- Decompose symbol name, in case that it contains category prefix
   -- (e.g. '_field_name' when requesting explicitely field called
   -- name).
   local category, name = string.match(symbol, '^(_.-)_(.*)$')
   if category and name and category ~= '_access' then
      -- Check requested category.
      local cat = rawget(self, category)
      element = cat and cat[name]
   elseif string.sub(symbol, 1, 1) ~= '_' then
      -- Check all available categories.
      local categories = self._categories or {}
      for i = 1, #categories do
	 category = categories[i]
	 local cat = rawget(self, category)
	 element = cat and cat[symbol]
	 if element then break end
      end
   end
   if element then
      -- Make sure that table-based attributes have symbol name, so
      -- that potential errors contain the name of referenced
      -- attribute.
      if type(element) == 'table' and category == '_attribute' then
	 element._name = element._name or symbol
      end

      -- If possible, cache the element in root table.
      if not category or not (origin or self)['_access' .. category] then
	 -- No category or no special category handler is present,
	 -- store it directly, which results in fastest access.  This
	 -- is most typical for methods.
	 self[symbol] = element
      else
	 -- Store into _cached table, because we have to preserve the
	 -- category.
	 if not cached then
	    cached = {}
	    self._cached = cached
	 end
	 cached[symbol] = { element, category }
      end

      return element, category
   end
end

-- __index implementation, uses _element method to perform lookup.
function component.mt:__index(key)
   -- First try to invoke our own _element method.
   local _element, mt = rawget(self, '_element')
   if not _element then
      mt = getmetatable(self)
      _element = rawget(mt, '_element')
   end
   local value, category = _element(self, nil, key)
   if value then
      if category then
	 -- Mangle the result by type-specific '_index_<category>'
	 -- method, if present.
	 local index_name = '_index' .. category
	 local index = rawget(self, index_name)
	 if not index then
	    if not mt then mt = getmetatable(self) end
	    if mt then index = rawget(mt, index_name) end
	 end
	 if index then value = index(self, value) end
      end
      return value
   end

   -- If not found as object element, examine the metatable itself.
   return rawget(mt or getmetatable(self), key)
end

-- Implementation of attribute accessor.  Attribute is either function
-- to be directly invoked, or table containing set and get functions.
function component.mt:_access_attribute(instance, element, ...)
   -- If element is a table, assume that this table contains 'get' and
   -- 'set' methods.  Dispatch to them, and error out if they are
   -- missing.
   if type(element) == 'table' then
      local mode = select('#', ...) == 0 and 'get' or 'set'
      if not element[mode] then
	 error(("%s: cannot %s `%s'"):format(
		  self._name, mode == 'get' and 'read' or 'write',
		  element._name or '<unknown>'), 5)
      end
      element = element[mode]
   end

   -- Invoke attribute access function.
   return element(instance, ...)
end

-- Pretty prints type name
function component.mt:__tostring()
   return self._name
end

-- Creates new component and sets up common parts according to given
-- info.
function component.create(info, mt, name)
   local gtype
   if core.gi.isinfo(info) then
      gtype = info.gtype
      name = info.fullname
   else
      gtype = info and core.gtype(info)
   end

   -- Fill in meta of the compound.
   local component = { _name = name }
   if gtype then
      -- Bind component in repo, make the relation using GType.
      component._gtype = gtype
      core.index[gtype] = component
   end
   return setmetatable(component, mt)
end

return component


text:
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 默认状态  -->
  <item android:state_window_focused="false"
        android:drawable="@drawable/upomp_bypay_keyboard_letter_bg" />
<!-- 按下状态  -->
  <item android:state_focused="true" android:state_pressed="true"
        android:drawable="@drawable/upomp_bypay_keyboard_letter_bg_on" />
  <item android:state_focused="false" android:state_pressed="true"
        android:drawable="@drawable/upomp_bypay_keyboard_letter_bg_on" />
<!-- 选中状态  -->
  <item android:state_selected="true"
        android:drawable="@drawable/upomp_bypay_keyboard_letter_bg_on" />
  <item android:state_focused="true"
        android:drawable="@drawable/upomp_bypay_keyboard_letter_bg_on" />
</selector>


text:
namespace mshtml
{
    using System.Runtime.InteropServices;

    [ComImport, Guid("3050F530-98B5-11CF-BB82-00AA00BDCE0B")]
    public interface HTMLScriptElement : DispHTMLScriptElement
    {
    }
}


text:
<?php

declare(strict_types=1);

namespace Shlinkio\Shlink\Core\Visit;

use Doctrine\ORM;
use Psr\EventDispatcher\EventDispatcherInterface;
use Shlinkio\Shlink\Core\EventDispatcher\Event\UrlVisited;
use Shlinkio\Shlink\Core\Options\TrackingOptions;
use Shlinkio\Shlink\Core\ShortUrl\Entity\ShortUrl;
use Shlinkio\Shlink\Core\Visit\Entity\Visit;
use Shlinkio\Shlink\Core\Visit\Model\Visitor;

class VisitsTracker implements VisitsTrackerInterface
{
    public function __construct(
        private ORM\EntityManagerInterface $em,
        private EventDispatcherInterface $eventDispatcher,
        private TrackingOptions $options,
    ) {
    }

    public function track(ShortUrl $shortUrl, Visitor $visitor): void
    {
        $this->trackVisit(
            fn (Visitor $v) => Visit::forValidShortUrl($shortUrl, $v, $this->options->anonymizeRemoteAddr),
            $visitor,
        );
    }

    public function trackInvalidShortUrlVisit(Visitor $visitor): void
    {
        $this->trackOrphanVisit(
            fn (Visitor $v) => Visit::forInvalidShortUrl($v, $this->options->anonymizeRemoteAddr),
            $visitor,
        );
    }

    public function trackBaseUrlVisit(Visitor $visitor): void
    {
        $this->trackOrphanVisit(
            fn (Visitor $v) => Visit::forBasePath($v, $this->options->anonymizeRemoteAddr),
            $visitor,
        );
    }

    public function trackRegularNotFoundVisit(Visitor $visitor): void
    {
        $this->trackOrphanVisit(
            fn (Visitor $v) => Visit::forRegularNotFound($v, $this->options->anonymizeRemoteAddr),
            $visitor,
        );
    }

    private function trackOrphanVisit(callable $createVisit, Visitor $visitor): void
    {
        if (! $this->options->trackOrphanVisits) {
            return;
        }

        $this->trackVisit($createVisit, $visitor);
    }

    private function trackVisit(callable $createVisit, Visitor $visitor): void
    {
        if ($this->options->disableTracking) {
            return;
        }

        $visit = $createVisit($visitor->normalizeForTrackingOptions($this->options));
        $this->em->persist($visit);
        $this->em->flush();

        $this->eventDispatcher->dispatch(UrlVisited::withOriginalIpAddress($visit->getId(), $visitor->remoteAddress));
    }
}


text:
package de.marcovogt.avrremote;

import java.awt.Font;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.UIManager;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class NoConnection extends JPanel {

	private static final long serialVersionUID = 1L;

	private JLabel heading;
	private JTextPane txtpnText;
	private JButton btnSettings;

	public NoConnection(MainWindow window) {
		setBounds(100, 100, 220, 385);
		setLayout(null);

		heading = new JLabel("AVR Remote");
		heading.setBounds(10, 11, 200, 37);
		heading.setHorizontalAlignment(SwingConstants.CENTER);
		heading.setFont(new Font("Tahoma", Font.PLAIN, 30));
		add(heading);

		txtpnText = new JTextPane();
		txtpnText.setText("No connection to AVR!");
		txtpnText.setFont(new Font("Tahoma", Font.PLAIN, 14));
		txtpnText.setEditable(false);
		txtpnText.setBackground(UIManager.getColor("ScrollBar.foreground"));
		txtpnText.setBounds(10, 59, 200, 267);
		add(txtpnText);

		btnSettings = new JButton("Settings");
		btnSettings.setFont(new Font("Tahoma", Font.PLAIN, 14));
		btnSettings.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				window.showSettings();
			}
		});
		btnSettings.setBounds(10, 337, 200, 37);
		add(btnSettings);

	}

	public void update() {

	}
}


text:
package edu.duke.cabig.c3pr.domain;

import edu.duke.cabig.c3pr.AbstractTestCase;

/**
 * The Class ScheduledNotificationTest.
 */
public class ScheduledNotificationTest extends AbstractTestCase{

	/** The Constant MESSAGE_BODY. */
	public static final String MESSAGE_BODY = "This is the message body!";

	/**
	 * Test get html based message used in report generation.
	 *
	 * @throws Exception the exception
	 */
	public void testGetHtmlMessage() throws Exception {
		ScheduledNotification scheduledNotification = new ScheduledNotification();

		StringBuffer message = new StringBuffer();
		message.append("");
		message.append(MESSAGE_BODY);
		message.append("");

		scheduledNotification.setMessage(message.toString());

		assertEquals(MESSAGE_BODY, scheduledNotification.getHtmlMessage());
	}

	/**
	 * Test get html based message used in report generation.
	 *
	 * @throws Exception the exception
	 */
	public void testGetHtmlMessageForNull() throws Exception {
		ScheduledNotification scheduledNotification = new ScheduledNotification();

		scheduledNotification.setMessage(null);
		assertEquals("", scheduledNotification.getHtmlMessage());
	}

	/**
	 * Test get html based message used in report generation.
	 *
	 * @throws Exception the exception
	 */
	public void testGetHtmlMessageForText() throws Exception {
ScheduledNotification scheduledNotification = new ScheduledNotification();

		StringBuffer message = new StringBuffer();
		message.append(MESSAGE_BODY);

		scheduledNotification.setMessage(message.toString());

		assertEquals(MESSAGE_BODY, scheduledNotification.getHtmlMessage());
	}
}


text:
using Base.LineEdit
using TestHelpers

a_foo = 0

const foo_keymap = {
    'a' => :( global a_foo; a_foo += 1)
}

b_foo = 0

const foo2_keymap = {
    'b' => :( global b_foo; b_foo += 1)
}

a_bar = 0
b_bar = 0

const bar_keymap = {
    'a' => :( global a_bar; a_bar += 1),
    'b' => :( global b_bar; b_bar += 1)
}

test1_func = @eval @LineEdit.keymap $foo_keymap

function run_test(f,buf)
    global a_foo, a_bar, b_bar
    a_foo = a_bar = b_bar = 0
    while !eof(buf)
        f(buf,nothing)
    end
end

run_test(test1_func,IOBuffer("aa"))
@test a_foo == 2

test2_func = @eval @LineEdit.keymap $([foo2_keymap, foo_keymap])

run_test(test2_func,IOBuffer("aaabb"))
@test a_foo == 3
@test b_foo == 2

test3_func = @eval @LineEdit.keymap $([bar_keymap, foo_keymap])

run_test(test3_func,IOBuffer("aab"))
@test a_bar == 2
@test b_bar == 1

## edit_move{left,right} ##
buf = IOBuffer("a\na\na\n")
seek(buf, 0)
for i = 1:6
    LineEdit.edit_move_right(buf)
    @test position(buf) == i
end
@test eof(buf)
for i = 5:0
    LineEdit.edit_move_left(buf)
    @test position(buf) == i
end

# skip unicode combining characters
buf = IOBuffer("ŷ")
seek(buf, 0)
LineEdit.edit_move_right(buf)
@test eof(buf)
LineEdit.edit_move_left(buf)
@test position(buf) == 0

## edit_move_{up,down} ##

buf = IOBuffer("type X\n    a::Int\nend")
for i = 0:6
    seek(buf,i)
    @test !LineEdit.edit_move_up(buf)
    @test position(buf) == i
    seek(buf,i)
    @test LineEdit.edit_move_down(buf)
    @test position(buf) == i+7
end
for i = 7:17
    seek(buf,i)
    @test LineEdit.edit_move_up(buf)
    @test position(buf) == min(i-7,6)
    seek(buf,i)
    @test LineEdit.edit_move_down(buf)
    @test position(buf) == min(i+11,21)
end
for i = 18:21
    seek(buf,i)
    @test LineEdit.edit_move_up(buf)
    @test position(buf) == i-11
    seek(buf,i)
    @test !LineEdit.edit_move_down(buf)
    @test position(buf) == i
end

buf = IOBuffer("type X\n\n")
seekend(buf)
@test LineEdit.edit_move_up(buf)
@test position(buf) == 7
@test LineEdit.edit_move_up(buf)
@test position(buf) == 0
@test !LineEdit.edit_move_up(buf)
@test position(buf) == 0
seek(buf,0)
@test LineEdit.edit_move_down(buf)
@test position(buf) == 7
@test LineEdit.edit_move_down(buf)
@test position(buf) == 8
@test !LineEdit.edit_move_down(buf)
@test position(buf) == 8

## edit_delete_prev_word ##

buf = IOBuffer("type X\n ")
seekend(buf)
@test LineEdit.edit_delete_prev_word(buf)
@test position(buf) == 5
@test buf.size == 5
@test bytestring(buf.data[1:buf.size]) == "type "

buf = IOBuffer("4 +aaa+ x")
seek(buf,8)
@test LineEdit.edit_delete_prev_word(buf)
@test position(buf) == 3
@test buf.size == 4
@test bytestring(buf.data[1:buf.size]) == "4 +x"

buf = IOBuffer("x = func(arg1,arg2 , arg3)")
seekend(buf)
LineEdit.char_move_word_left(buf)
@test position(buf) == 21
@test LineEdit.edit_delete_prev_word(buf)
@test bytestring(buf.data[1:buf.size]) == "x = func(arg1,arg3)"
@test LineEdit.edit_delete_prev_word(buf)
@test bytestring(buf.data[1:buf.size]) == "x = func(arg3)"
@test LineEdit.edit_delete_prev_word(buf)
@test bytestring(buf.data[1:buf.size]) == "x = arg3)"

# Unicode combining characters
let buf = IOBuffer()
    LineEdit.edit_insert(buf, "â")
    LineEdit.edit_move_left(buf)
    @test position(buf) == 0
    LineEdit.edit_move_right(buf)
    @test nb_available(buf) == 0
    LineEdit.edit_backspace(buf)
    @test bytestring(buf.data[1:buf.size]) == "a"
end

## edit_transpose ##
let buf = IOBuffer()
    LineEdit.edit_insert(buf, "abcde")
    seek(buf,0)
    LineEdit.edit_transpose(buf)
    @test bytestring(buf.data[1:buf.size]) == "abcde"
    LineEdit.char_move_right(buf)
    LineEdit.edit_transpose(buf)
    @test bytestring(buf.data[1:buf.size]) == "bacde"
    LineEdit.edit_transpose(buf)
    @test bytestring(buf.data[1:buf.size]) == "bcade"
    seekend(buf)
    LineEdit.edit_transpose(buf)
    @test bytestring(buf.data[1:buf.size]) == "bcaed"
    LineEdit.edit_transpose(buf)
    @test bytestring(buf.data[1:buf.size]) == "bcade"

    seek(buf, 0)
    LineEdit.edit_clear(buf)
    LineEdit.edit_insert(buf, "αβγδε")
    seek(buf,0)
    LineEdit.edit_transpose(buf)
    @test bytestring(buf.data[1:buf.size]) == "αβγδε"
    LineEdit.char_move_right(buf)
    LineEdit.edit_transpose(buf)
    @test bytestring(buf.data[1:buf.size]) == "βαγδε"
    LineEdit.edit_transpose(buf)
    @test bytestring(buf.data[1:buf.size]) == "βγαδε"
    seekend(buf)
    LineEdit.edit_transpose(buf)
    @test bytestring(buf.data[1:buf.size]) == "βγαεδ"
    LineEdit.edit_transpose(buf)
    @test bytestring(buf.data[1:buf.size]) == "βγαδε"
end

let
    term = TestHelpers.FakeTerminal(IOBuffer(), IOBuffer(), IOBuffer())
    s = LineEdit.init_state(term, Base.REPL.ModalInterface([Base.REPL.Prompt("test> ")]))
    buf = LineEdit.buffer(s)

    LineEdit.edit_insert(s,"first line\nsecond line\nthird line")
    @test bytestring(buf.data[1:buf.size]) == "first line\nsecond line\nthird line"

    ## edit_move_line_start/end ##
    seek(buf, 0)
    LineEdit.move_line_end(s)
    @test position(buf) == sizeof("first line")
    LineEdit.move_line_end(s) # Only move to input end on repeated keypresses
    @test position(buf) == sizeof("first line")
    s.key_repeats = 1 # Manually flag a repeated keypress
    LineEdit.move_line_end(s)
    s.key_repeats = 0
    @test eof(buf)

    seekend(buf)
    LineEdit.move_line_start(s)
    @test position(buf) == sizeof("first line\nsecond line\n")
    LineEdit.move_line_start(s)
    @test position(buf) == sizeof("first line\nsecond line\n")
    s.key_repeats = 1 # Manually flag a repeated keypress
    LineEdit.move_line_start(s)
    s.key_repeats = 0
    @test position(buf) == 0

    ## edit_kill_line, edit_yank ##
    seek(buf, 0)
    LineEdit.edit_kill_line(s)
    s.key_repeats = 1 # Manually flag a repeated keypress
    LineEdit.edit_kill_line(s)
    s.key_repeats = 0
    @test bytestring(buf.data[1:buf.size]) == "second line\nthird line"
    LineEdit.move_line_end(s)
    LineEdit.edit_move_right(s)
    LineEdit.edit_yank(s)
    @test bytestring(buf.data[1:buf.size]) == "second line\nfirst line\nthird line"
end

# Issue 7845
# First construct a problematic string:
# julia> is 6 characters + 1 character for space,
# so the rest of the terminal is 73 characters
#########################################################################
buf = IOBuffer(
"begin\nprint(\"A very very very very very very very very very very very very ve\")\nend")
seek(buf,4)
outbuf = IOBuffer()
termbuf = Base.Terminals.TerminalBuffer(outbuf)
term = TestHelpers.FakeTerminal(IOBuffer(), IOBuffer(), IOBuffer())
s = LineEdit.refresh_multi_line(termbuf, term, buf,
    Base.LineEdit.InputAreaState(0,0), "julia> ", indent = 7)
@test s == Base.LineEdit.InputAreaState(3,1)