text:
package caddytls

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"runtime/debug"
	"strings"
	"sync"
	"time"

	"github.com/caddyserver/caddy/v2"
	"github.com/caddyserver/certmagic"
	"go.uber.org/zap"
)

func init() {
	caddy.RegisterModule(TLS{})
	caddy.RegisterModule(AutomateLoader{})
}

// TLS provides TLS facilities including certificate
// loading and management, client auth, and more.
type TLS struct {
	// Caches certificates in memory for quick use during
	// TLS handshakes. Each key is the name of a certificate
	// loader module. All loaded certificates get pooled
	// into the same cache and may be used to complete TLS
	// handshakes for the relevant server names (SNI).
	// Certificates loaded manually (anything other than
	// "automate") are not automatically managed and will
	// have to be refreshed manually before they expire.
	CertificatesRaw caddy.ModuleMap `json:"certificates,omitempty" caddy:"namespace=tls.certificates"`

	// Configures the automation of certificate management.
	Automation *AutomationConfig `json:"automation,omitempty"`

	// Configures session ticket ephemeral keys (STEKs).
	SessionTickets *SessionTicketService `json:"session_tickets,omitempty"`

	// Configures the in-memory certificate cache.
	Cache *CertCacheOptions `json:"cache,omitempty"`

	certificateLoaders []CertificateLoader
	automateNames      []string
	certCache          *certmagic.Cache
	ctx                caddy.Context
	storageCleanTicker *time.Ticker
	storageCleanStop   chan struct{}
	logger             *zap.Logger
}

// CaddyModule returns the Caddy module information.
func (TLS) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "tls",
		New: func() caddy.Module { return new(TLS) },
	}
}

// Provision sets up the configuration for the TLS app.
func (t *TLS) Provision(ctx caddy.Context) error {
	t.ctx = ctx
	t.logger = ctx.Logger(t)

	// set up a new certificate cache; this (re)loads all certificates
	cacheOpts := certmagic.CacheOptions{
		GetConfigForCert: func(cert certmagic.Certificate) (*certmagic.Config, error) {
			return t.getConfigForName(cert.Names[0]), nil
		},
		Logger: t.logger.Named("cache"),
	}
	if t.Automation != nil {
		cacheOpts.OCSPCheckInterval = time.Duration(t.Automation.OCSPCheckInterval)
		cacheOpts.RenewCheckInterval = time.Duration(t.Automation.RenewCheckInterval)
	}
	if t.Cache != nil {
		cacheOpts.Capacity = t.Cache.Capacity
	}
	if cacheOpts.Capacity <= 0 {
		cacheOpts.Capacity = 10000
	}
	t.certCache = certmagic.NewCache(cacheOpts)

	// certificate loaders
	val, err := ctx.LoadModule(t, "CertificatesRaw")
	if err != nil {
		return fmt.Errorf("loading certificate loader modules: %s", err)
	}
	for modName, modIface := range val.(map[string]interface{}) {
		if modName == "automate" {
			// special case; these will be loaded in later using our automation facilities,
			// which we want to avoid doing during provisioning
			if automateNames, ok := modIface.(*AutomateLoader); ok && automateNames != nil {
				t.automateNames = []string(*automateNames)
			} else {
				return fmt.Errorf("loading certificates with 'automate' requires array of strings, got: %T", modIface)
			}
			continue
		}
		t.certificateLoaders = append(t.certificateLoaders, modIface.(CertificateLoader))
	}

	// automation/management policies
	if t.Automation == nil {
		t.Automation = new(AutomationConfig)
	}
	t.Automation.defaultPublicAutomationPolicy = new(AutomationPolicy)
	err = t.Automation.defaultPublicAutomationPolicy.Provision(t)
	if err != nil {
		return fmt.Errorf("provisioning default public automation policy: %v", err)
	}
	for _, n := range t.automateNames {
		// if any names specified by the "automate" loader do not qualify for a public
		// certificate, we should initialize a default internal automation policy
		// (but we don't want to do this unnecessarily, since it may prompt for password!)
		if certmagic.SubjectQualifiesForPublicCert(n) {
			continue
		}
		t.Automation.defaultInternalAutomationPolicy = &AutomationPolicy{
			IssuersRaw: []json.RawMessage{json.RawMessage(`{"module":"internal"}`)},
		}
		err = t.Automation.defaultInternalAutomationPolicy.Provision(t)
		if err != nil {
			return fmt.Errorf("provisioning default internal automation policy: %v", err)
		}
		break
	}
	for i, ap := range t.Automation.Policies {
		err := ap.Provision(t)
		if err != nil {
			return fmt.Errorf("provisioning automation policy %d: %v", i, err)
		}
	}

	// session ticket ephemeral keys (STEK) service and provider
	if t.SessionTickets != nil {
		err := t.SessionTickets.provision(ctx)
		if err != nil {
			return fmt.Errorf("provisioning session tickets configuration: %v", err)
		}
	}

	// on-demand rate limiting
	if t.Automation != nil && t.Automation.OnDemand != nil && t.Automation.OnDemand.RateLimit != nil {
		onDemandRateLimiter.SetMaxEvents(t.Automation.OnDemand.RateLimit.Burst)
		onDemandRateLimiter.SetWindow(time.Duration(t.Automation.OnDemand.RateLimit.Interval))
	} else {
		// remove any existing rate limiter
		onDemandRateLimiter.SetMaxEvents(0)
		onDemandRateLimiter.SetWindow(0)
	}

	// load manual/static (unmanaged) certificates - we do this in
	// provision so that other apps (such as http) can know which
	// certificates have been manually loaded, and also so that
	// commands like validate can be a better test
	magic := certmagic.New(t.certCache, certmagic.Config{
		Storage: ctx.Storage(),
		Logger:  t.logger,
	})
	for _, loader := range t.certificateLoaders {
		certs, err := loader.LoadCertificates()
		if err != nil {
			return fmt.Errorf("loading certificates: %v", err)
		}
		for _, cert := range certs {
			err := magic.CacheUnmanagedTLSCertificate(cert.Certificate, cert.Tags)
			if err != nil {
				return fmt.Errorf("caching unmanaged certificate: %v", err)
			}
		}
	}

	// TODO: TEMPORARY UNTIL RELEASE CANDIDATES:
	// MIGRATE MANAGED CERTIFICATE ASSETS TO NEW PATH
	err = t.moveCertificates()
	if err != nil {
		t.logger.Error("migrating certificates", zap.Error(err))
	}
	// END TODO: TEMPORARY.

	return nil
}

// Validate validates t's configuration.
func (t *TLS) Validate() error {
	if t.Automation != nil {
		// ensure that host aren't repeated; since only the first
		// automation policy is used, repeating a host in the lists
		// isn't useful and is probably a mistake; same for two
		// catch-all/default policies
		var hasDefault bool
		hostSet := make(map[string]int)
		for i, ap := range t.Automation.Policies {
			if len(ap.Subjects) == 0 {
				if hasDefault {
					return fmt.Errorf("automation policy %d is the second policy that acts as default/catch-all, but will never be used", i)
				}
				hasDefault = true
			}
			for _, h := range ap.Subjects {
				if first, ok := hostSet[h]; ok {
					return fmt.Errorf("automation policy %d: cannot apply more than one automation policy to host: %s (first match in policy %d)", i, h, first)
				}
				hostSet[h] = i
			}
		}
	}
	if t.Cache != nil {
		if t.Cache.Capacity < 0 {
			return fmt.Errorf("cache capacity must be >= 0")
		}
	}
	return nil
}

// Start activates the TLS module.
func (t *TLS) Start() error {
	// now that we are running, and all manual certificates have
	// been loaded, time to load the automated/managed certificates
	err := t.Manage(t.automateNames)
	if err != nil {
		return fmt.Errorf("automate: managing %v: %v", t.automateNames, err)
	}

	t.keepStorageClean()

	return nil
}

// Stop stops the TLS module and cleans up any allocations.
func (t *TLS) Stop() error {
	// stop the storage cleaner goroutine and ticker
	if t.storageCleanStop != nil {
		close(t.storageCleanStop)
	}
	if t.storageCleanTicker != nil {
		t.storageCleanTicker.Stop()
	}
	return nil
}

// Cleanup frees up resources allocated during Provision.
func (t *TLS) Cleanup() error {
	// stop the certificate cache
	if t.certCache != nil {
		t.certCache.Stop()
	}

	// stop the session ticket rotation goroutine
	if t.SessionTickets != nil {
		t.SessionTickets.stop()
	}

	return nil
}

// Manage immediately begins managing names according to the
// matching automation policy.
func (t *TLS) Manage(names []string) error {
	// for a large number of names, we can be more memory-efficient
	// by making only one certmagic.Config for all the names that
	// use that config, rather than calling ManageAsync once for
	// every name; so first, bin names by AutomationPolicy
	policyToNames := make(map[*AutomationPolicy][]string)
	for _, name := range names {
		ap := t.getAutomationPolicyForName(name)
		policyToNames[ap] = append(policyToNames[ap], name)
	}

	// now that names are grouped by policy, we can simply make one
	// certmagic.Config for each (potentially large) group of names
	// and call ManageAsync just once for the whole batch
	for ap, names := range policyToNames {
		err := ap.magic.ManageAsync(t.ctx.Context, names)
		if err != nil {
			return fmt.Errorf("automate: manage %v: %v", names, err)
		}
	}

	return nil
}

// HandleHTTPChallenge ensures that the HTTP challenge is handled for the
// certificate named by r.Host, if it is an HTTP challenge request. It
// requires that the automation policy for r.Host has an issuer of type
// *certmagic.ACMEManager, or one that is ACME-enabled (GetACMEIssuer()).
func (t *TLS) HandleHTTPChallenge(w http.ResponseWriter, r *http.Request) bool {
	if !certmagic.LooksLikeHTTPChallenge(r) {
		return false
	}
	// try all the issuers until we find the one that initiated the challenge
	ap := t.getAutomationPolicyForName(r.Host)
	type acmeCapable interface{ GetACMEIssuer() *ACMEIssuer }
	for _, iss := range ap.magic.Issuers {
		if am, ok := iss.(acmeCapable); ok {
			iss := am.GetACMEIssuer()
			if certmagic.NewACMEManager(iss.magic, iss.template).HandleHTTPChallenge(w, r) {
				return true
			}
		}
	}
	return false
}

// AddAutomationPolicy provisions and adds ap to the list of the app's
// automation policies. If an existing automation policy exists that has
// fewer hosts in its list than ap does, ap will be inserted before that
// other policy (this helps ensure that ap will be prioritized/chosen
// over, say, a catch-all policy).
func (t *TLS) AddAutomationPolicy(ap *AutomationPolicy) error {
	if t.Automation == nil {
		t.Automation = new(AutomationConfig)
	}
	err := ap.Provision(t)
	if err != nil {
		return err
	}
	// sort new automation policies just before any other which is a superset
	// of this one; if we find an existing policy that covers every subject in
	// ap but less specifically (e.g. a catch-all policy, or one with wildcards
	// or with fewer subjects), insert ap just before it, otherwise ap would
	// never be used because the first matching policy is more general
	for i, existing := range t.Automation.Policies {
		// first see if existing is superset of ap for all names
		var otherIsSuperset bool
	outer:
		for _, thisSubj := range ap.Subjects {
			for _, otherSubj := range existing.Subjects {
				if certmagic.MatchWildcard(thisSubj, otherSubj) {
					otherIsSuperset = true
					break outer
				}
			}
		}
		// if existing AP is a superset or if it contains fewer names (i.e. is
		// more general), then new AP is more specific, so insert before it
		if otherIsSuperset || len(existing.Subjects) < len(ap.Subjects) {
			t.Automation.Policies = append(t.Automation.Policies[:i],
				append([]*AutomationPolicy{ap}, t.Automation.Policies[i:]...)...)
			return nil
		}
	}
	// otherwise just append the new one
	t.Automation.Policies = append(t.Automation.Policies, ap)
	return nil
}

func (t *TLS) getConfigForName(name string) *certmagic.Config {
	ap := t.getAutomationPolicyForName(name)
	return ap.magic
}

// getAutomationPolicyForName returns the first matching automation policy
// for the given subject name. If no matching policy can be found, the
// default policy is used, depending on whether the name qualifies for a
// public certificate or not.
func (t *TLS) getAutomationPolicyForName(name string) *AutomationPolicy {
	for _, ap := range t.Automation.Policies {
		if len(ap.Subjects) == 0 {
			return ap // no host filter is an automatic match
		}
		for _, h := range ap.Subjects {
			if certmagic.MatchWildcard(name, h) {
				return ap
			}
		}
	}
	if certmagic.SubjectQualifiesForPublicCert(name) || t.Automation.defaultInternalAutomationPolicy == nil {
		return t.Automation.defaultPublicAutomationPolicy
	}
	return t.Automation.defaultInternalAutomationPolicy
}

// AllMatchingCertificates returns the list of all certificates in
// the cache which could be used to satisfy the given SAN.
func (t *TLS) AllMatchingCertificates(san string) []certmagic.Certificate {
	return t.certCache.AllMatchingCertificates(san)
}

// keepStorageClean starts a goroutine that immediately cleans up all
// known storage units if it was not recently done, and then runs the
// operation at every tick from t.storageCleanTicker.
func (t *TLS) keepStorageClean() {
	t.storageCleanTicker = time.NewTicker(storageCleanInterval)
	t.storageCleanStop = make(chan struct{})
	go func() {
		defer func() {
			if err := recover(); err != nil {
				log.Printf("[PANIC] storage cleaner: %v\n%s", err, debug.Stack())
			}
		}()
		t.cleanStorageUnits()
		for {
			select {
			case <-t.storageCleanStop:
				return
			case <-t.storageCleanTicker.C:
				t.cleanStorageUnits()
			}
		}
	}()
}

func (t *TLS) cleanStorageUnits() {
	storageCleanMu.Lock()
	defer storageCleanMu.Unlock()

	if !storageClean.IsZero() && time.Since(storageClean) < storageCleanInterval {
		return
	}

	options := certmagic.CleanStorageOptions{
		OCSPStaples:            true,
		ExpiredCerts:           true,
		ExpiredCertGracePeriod: 24 * time.Hour * 14,
	}

	// start with the default storage
	certmagic.CleanStorage(t.ctx, t.ctx.Storage(), options)

	// then clean each storage defined in ACME automation policies
	if t.Automation != nil {
		for _, ap := range t.Automation.Policies {
			if ap.storage != nil {
				certmagic.CleanStorage(t.ctx, ap.storage, options)
			}
		}
	}

	storageClean = time.Now()

	t.logger.Info("cleaned up storage units")
}

// CertificateLoader is a type that can load certificates.
// Certificates can optionally be associated with tags.
type CertificateLoader interface {
	LoadCertificates() ([]Certificate, error)
}

// Certificate is a TLS certificate, optionally
// associated with arbitrary tags.
type Certificate struct {
	tls.Certificate
	Tags []string
}

// AutomateLoader is a no-op certificate loader module
// that is treated as a special case: it uses this app's
// automation features to load certificates for the
// list of hostnames, rather than loading certificates
// manually.
type AutomateLoader []string

// CaddyModule returns the Caddy module information.
func (AutomateLoader) CaddyModule() caddy.ModuleInfo {
	return caddy.ModuleInfo{
		ID:  "tls.certificates.automate",
		New: func() caddy.Module { return new(AutomateLoader) },
	}
}

// CertCacheOptions configures the certificate cache.
type CertCacheOptions struct {
	// Maximum number of certificates to allow in the
	// cache. If reached, certificates will be randomly
	// evicted to make room for new ones. Default: 0
	// (no limit).
	Capacity int `json:"capacity,omitempty"`
}

// Variables related to storage cleaning.
var (
	storageCleanInterval = 12 * time.Hour

	storageClean   time.Time
	storageCleanMu sync.Mutex
)

// Interface guards
var (
	_ caddy.App          = (*TLS)(nil)
	_ caddy.Provisioner  = (*TLS)(nil)
	_ caddy.Validator    = (*TLS)(nil)
	_ caddy.CleanerUpper = (*TLS)(nil)
)

// TODO: This is temporary until the release candidates
// (beta 16 changed the storage path for certificates),
// after which this function can be deleted
func (t *TLS) moveCertificates() error {
	logger := t.logger.Named("automigrate")

	baseDir := caddy.AppDataDir()

	// if custom storage path was defined, use that instead
	if fs, ok := t.ctx.Storage().(*certmagic.FileStorage); ok && fs.Path != "" {
		baseDir = fs.Path
	}

	oldAcmeDir := filepath.Join(baseDir, "acme")
	oldAcmeCas, err := ioutil.ReadDir(oldAcmeDir)
	if err != nil {
		if os.IsNotExist(err) {
			return nil
		}
		return fmt.Errorf("listing used ACME CAs: %v", err)
	}

	// get list of used CAs
	oldCANames := make([]string, 0, len(oldAcmeCas))
	for _, fi := range oldAcmeCas {
		if !fi.IsDir() {
			continue
		}
		oldCANames = append(oldCANames, fi.Name())
	}

	for _, oldCA := range oldCANames {
		// make new destination path
		newCAName := oldCA
		if strings.Contains(oldCA, "api.letsencrypt.org") &&
			!strings.HasSuffix(oldCA, "-directory") {
			newCAName += "-directory"
		}
		newBaseDir := filepath.Join(baseDir, "certificates", newCAName)
		err := os.MkdirAll(newBaseDir, 0700)
		if err != nil {
			return fmt.Errorf("making new certs directory: %v", err)
		}

		// list sites in old path
		oldAcmeSitesDir := filepath.Join(oldAcmeDir, oldCA, "sites")
		oldAcmeSites, err := ioutil.ReadDir(oldAcmeSitesDir)
		if err != nil {
			if os.IsNotExist(err) {
				continue
			}
			return fmt.Errorf("listing sites: %v", err)
		}

		if len(oldAcmeSites) > 0 {
			logger.Warn("certificate storage path has changed; attempting one-time auto-migration",
				zap.String("old_folder", oldAcmeSitesDir),
				zap.String("new_folder", newBaseDir),
				zap.String("details", "https://github.com/caddyserver/caddy/issues/2955"))
		}

		// for each site, move its folder and re-encode its metadata
		for _, siteInfo := range oldAcmeSites {
			if !siteInfo.IsDir() {
				continue
			}

			// move the folder
			oldPath := filepath.Join(oldAcmeSitesDir, siteInfo.Name())
			newPath := filepath.Join(newBaseDir, siteInfo.Name())
			logger.Info("moving certificate assets",
				zap.String("ca", oldCA),
				zap.String("site", siteInfo.Name()),
				zap.String("destination", newPath))
			err = os.Rename(oldPath, newPath)
			if err != nil {
				logger.Error("failed moving site to new path; skipping",
					zap.String("old_path", oldPath),
					zap.String("new_path", newPath),
					zap.Error(err))
				continue
			}

			// re-encode metadata file
			metaFilePath := filepath.Join(newPath, siteInfo.Name()+".json")
			metaContents, err := ioutil.ReadFile(metaFilePath)
			if err != nil {
				logger.Error("could not read metadata file",
					zap.String("filename", metaFilePath),
					zap.Error(err))
				continue
			}
			if len(metaContents) == 0 {
				continue
			}
			cr := certmagic.CertificateResource{
				SANs:       []string{siteInfo.Name()},
				IssuerData: json.RawMessage(metaContents),
			}
			newMeta, err := json.MarshalIndent(cr, "", "\t")
			if err != nil {
				logger.Error("encoding new metadata file", zap.Error(err))
				continue
			}
			err = ioutil.WriteFile(metaFilePath, newMeta, 0600)
			if err != nil {
				logger.Error("writing new metadata file", zap.Error(err))
				continue
			}
		}

		// delete now-empty old sites dir (OK if fails)
		os.Remove(oldAcmeSitesDir)
	}

	return nil
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using Ivvy.API.Json;
using Newtonsoft.Json;

namespace Ivvy.API.Venue.Bookings
{
    /// <summary>
    /// A room option that has been added to a group accommodation block on an iVvy venue booking.
    /// </summary>
    public class AccommodationRoomOption : ISerializable
    {
        [JsonProperty("bookingDate")]
        public string BookingDate
        {
            get; set;
        }

        [JsonProperty("roomOptionId")]
        public int RoomOptionId
        {
            get; set;
        }

        [JsonProperty("numRooms")]
        public int NumRooms
        {
            get; set;
        }

        [JsonProperty("numOptionsPerRoom")]
        public int NumOptionsPerRoom
        {
            get; set;
        }

        [JsonProperty("price")]
        public float Price
        {
            get; set;
        }

        [JsonProperty("discount")]
        public float? Discount
        {
            get; set;
        }
        [JsonProperty("excludedTaxIds")]
        public int[] ExcludedTaxIds
        {
            get; set;
        }

        [JsonProperty("totalAmount")]
        public float? TotalAmount
        {
            get; set;
        }

        [JsonProperty("totalDiscount")]
        public float? TotalDiscount
        {
            get; set;
        }
        [JsonProperty("totalTaxAmount")]
        public float? TotalTaxAmount
        {
            get; set;
        }

        [JsonProperty("costcenterId")]
        public int? CostCenterId
        {
            get; set;
        }

        [JsonProperty("numPayableByGuest")]
        public int NumPayableByGuest
        {
            get; set;
        }
    }
}


text:
using MarkdownPreview.Core;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Diagnostics;

namespace MarkdownPreview.Tests
{
	/// <summary>
	/// Contains all tests for <see cref="Engine"/>
	/// </summary>
	[TestClass]
	public class EngineTests
	{
		/// <summary>
		/// Tests <see cref="Engine.GetCss"/>
		/// </summary>
		[TestMethod]
		public void GetCssTest()
		{
			//Arrange
			//Act
			var actual = Engine.GetCss();

			//Assert
			Assert.IsFalse(string.IsNullOrEmpty(actual), "result of getting CSS was null or empty");

			Trace.Write(actual);
		}

		/// <summary>
		/// Tests <see cref="Engine.MarkDownToHtml(string)"/>
		/// </summary>
		[TestMethod()]
		public void MarkDownToHtmlTest() {
			//arrange
			var markdown = @"# Hello
this is a paragraph with a [link](https://github.com/Atrejoe/MarkdownPreview)";
			//act

			var html = Engine.MarkDownToHtml(markdown);

			//assert
			Assert.IsFalse(string.IsNullOrWhiteSpace(html));

			Trace.Write(html);
		}

		/// <summary>
		/// Tests <see cref="Engine.IsDarkMode"/>
		/// </summary>
		[TestMethod()]
		public void IsDarkModeTest() {
			//arrange

			//act

			var actual = Engine.IsDarkMode();

			//assert

			Trace.Write($@"Is dark mode : {actual}");
		}
	}
}


text:
import {
  ThemeService,
  ThemeType,
} from '../modules/shared/services/theme/theme.service';
import { BehaviorSubject } from 'rxjs';

export const themeServiceStub: Partial<ThemeService> = {
  loadCSS: () => void 0,
  loadTheme: () => void 0,
  isLightThemeEnabled: () => true,
  switchTheme: () => void 0,
  themeType: new BehaviorSubject<ThemeType>('light'),
};


text:
package crafttweaker.api.vanilla;

import crafttweaker.annotations.ZenRegister;
import stanhebben.zenscript.annotations.*;

/**
 * @author Stan
 */
@ZenClass("vanilla.IVanilla")
@ZenRegister
public interface IVanilla {

    @ZenGetter("seeds")
    ISeedRegistry getSeeds();
}


text:
package org.saiku.olap.dto;

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

public class SaikuTuple {

	private List<SaikuMember> saikuMembers;

	public SaikuTuple() {}

	public SaikuTuple(List<SaikuMember> members) {
		this.saikuMembers = members;
	}

	public List<SaikuMember> getSaikuMembers() {
		return saikuMembers;
	}

	public void setSaikuMembers(List<SaikuMember> members) {
		this.saikuMembers = members;
	}

	public SaikuMember getSaikuMember(String dimensionUniqueName) {
		for (SaikuMember m : saikuMembers) {
			if (m.getDimensionUniqueName().equals(dimensionUniqueName)) {
				return m;
			}
		}
		return null;
	}

	public List<SaikuMember> getOtherSaikuMembers(String dimensionUniqueName) {
		List<SaikuMember> others = new ArrayList<SaikuMember>();
		for (SaikuMember m : saikuMembers) {
			if (!m.getDimensionUniqueName().equals(dimensionUniqueName)) {
				others.add(m);
			}
		}
		return others;
	}

}


text:
/**
 * This file was automatically generated by the TRLD transpiler.
 * Source: trld/jsonld/compaction.py
 */
package trld.jsonld;

//import javax.annotation.Nullable;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.io.*;

import trld.Builtins;
import trld.KeyValue;

import static trld.Common.warning;
import static trld.jsonld.Base.*;
import trld.jsonld.Context;
import trld.jsonld.Term;
import trld.jsonld.InvalidNestValueError;
import static trld.jsonld.Invcontext.getInverseContext;

public class Compaction {
  public static final String PRESERVE = "@preserve"; // LINE: 8

  public static Object compact(Object context, Object docData) {
    return compact(context, docData, null);
  }
  public static Object compact(Object context, Object docData, /*@Nullable*/ String baseIri) {
    return compact(context, docData, baseIri, true);
  }
  public static Object compact(Object context, Object docData, /*@Nullable*/ String baseIri, Boolean compactArrays) {
    return compact(context, docData, baseIri, compactArrays, false);
  }
  public static Object compact(Object context, Object docData, /*@Nullable*/ String baseIri, Boolean compactArrays, Boolean ordered) { // LINE: 15
    Context activeContext; // LINE: 19
    if (context instanceof Context) { // LINE: 20
      activeContext = (Context) context; // LINE: 21
    } else {
      /*@Nullable*/ String contextUrl = (context instanceof String ? (String) context : null); // LINE: 23
      if (context instanceof Map) { // LINE: 24
        context = ((Map) context).get(CONTEXT); // LINE: 25
      }
      activeContext = (Context) new Context(baseIri).getContext(((Object) context), contextUrl); // LINE: 26
    }
    Object result = compaction(activeContext, null, docData, compactArrays, ordered); // LINE: 28
    if (result instanceof List) { // LINE: 29
      if (((List) result).size() == 0) { // LINE: 30
        result = new HashMap<>(); // LINE: 31
      } else {
        result = Builtins.mapOf(iriCompaction(activeContext, GRAPH), result); // LINE: 33
      }
    }
    return result; // LINE: 34
  }

  public static Object compaction(Context activeContext, /*@Nullable*/ String activeProperty, Object element) {
    return compaction(activeContext, activeProperty, element, false);
  }
  public static Object compaction(Context activeContext, /*@Nullable*/ String activeProperty, Object element, Boolean compactArrays) {
    return compaction(activeContext, activeProperty, element, compactArrays, false);
  }
  public static Object compaction(Context activeContext, /*@Nullable*/ String activeProperty, Object element, Boolean compactArrays, Boolean ordered) { // LINE: 37
    Context typeScopedContext = activeContext; // LINE: 45
    Object result; // LINE: 46
    Map<String, Object> resultMap; // LINE: 47
    List<Object> resultList; // LINE: 48
    /*@Nullable*/ Term activeTerm = (/*@Nullable*/ Term) activeContext.terms.get(activeProperty); // LINE: 50
    List activeContainerMapping = (activeTerm != null ? activeTerm.container : new ArrayList<>()); // LINE: 51
    Object compactedItem; // LINE: 52
    if ((element == null || isScalar(element))) { // LINE: 55
      return element; // LINE: 56
    }
    if (element instanceof List) { // LINE: 59
      result = resultList = new ArrayList<>(); // LINE: 61
      for (Object item : (List) element) { // LINE: 63
        compactedItem = compaction(activeContext, activeProperty, item, compactArrays, ordered); // LINE: 65
        if (compactedItem != null) { // LINE: 68
          ((List) result).add(compactedItem); // LINE: 69
        }
      }
      if ((resultList.size() == 0 || resultList.size() > 1 || !(compactArrays) || new HashSet(new ArrayList<>(Arrays.asList(new String[] {(String) GRAPH, SET}))).contains(activeProperty) || activeContainerMapping.contains(LIST) || activeContainerMapping.contains(SET))) { // LINE: 71
        return resultList; // LINE: 74
      } else {
        return resultList.get(0); // LINE: 77
      }
    }
    assert element instanceof Map;
    if ((!(activeContext.propagate) && activeContext.previousContext != null)) { // LINE: 83
      if (!((Map) element).containsKey(VALUE)) { // LINE: 84
        if ((!((Map) element).containsKey(ID) || ((Map) element).size() != 1)) { // LINE: 85
          activeContext = (Context) activeContext.previousContext; // LINE: 86
        }
      }
    }
    if ((activeTerm != null && activeTerm.hasLocalContext)) { // LINE: 89
      activeContext = (Context) activeTerm.getLocalContext(activeContext); // LINE: 90
    }
    if ((((Map) element).containsKey(VALUE) || ((Map) element).containsKey(ID))) { // LINE: 93
      Object valueResult = valueCompaction(activeContext, activeTerm, (Map) element); // LINE: 94
      if ((isScalar(valueResult) || (activeTerm != null && (activeTerm.typeMapping == null && ((Object) JSON) == null || activeTerm.typeMapping != null && (activeTerm.typeMapping).equals(JSON))))) { // LINE: 95
        return valueResult; // LINE: 96
      }
    }
    if ((element instanceof Map && ((Map) element).containsKey(LIST) && activeContainerMapping.contains(LIST))) { // LINE: 99
      return compaction(activeContext, activeProperty, ((Map) element).get(LIST), compactArrays, ordered); // LINE: 100
    }
    Boolean insideReverse = (Boolean) (activeProperty == null && ((Object) REVERSE) == null || activeProperty != null && (activeProperty).equals(REVERSE)); // LINE: 103
    result = resultMap = new HashMap<>(); // LINE: 106
    List<String> compactedTypes = new ArrayList<>(); // LINE: 110
    Context currentActiveContext = activeContext; // LINE: 111
    if (((Map) element).containsKey(TYPE)) { // LINE: 112
      for (Object expandedType : asList(((Map) element).get(TYPE))) { // LINE: 113
        compactedTypes.add(iriCompaction(typeScopedContext, ((String) expandedType))); // LINE: 114
      }
      for (Object ctype : Builtins.sorted(compactedTypes)) { // LINE: 116
        /*@Nullable*/ Term typeterm = (/*@Nullable*/ Term) typeScopedContext.terms.get(ctype); // LINE: 118
        if ((typeterm != null && typeterm.hasLocalContext)) { // LINE: 119
          activeContext = typeterm.getLocalContext(currentActiveContext, false); // LINE: 120
        }
      }
    }
    for (Map.Entry<String, Object> expandedProperty_expandedValue : ((Map<String, Object>) element).entrySet()) { // LINE: 123
      String expandedProperty = expandedProperty_expandedValue.getKey();
      Object expandedValue = expandedProperty_expandedValue.getValue();
      /*@Nullable*/ String compactedValue = null; // LINE: 124
      String alias = iriCompaction(activeContext, expandedProperty, expandedValue); // LINE: 126
      /*@Nullable*/ Term aliasTerm = (/*@Nullable*/ Term) activeContext.terms.get(alias); // LINE: 127
      List aliasContainerMapping = (aliasTerm != null ? aliasTerm.container : new ArrayList<>()); // LINE: 128
      Boolean asArray; // LINE: 129
      if ((expandedProperty == null && ((Object) ID) == null || expandedProperty != null && (expandedProperty).equals(ID))) { // LINE: 132
        if (expandedValue instanceof String) { // LINE: 134
          compactedValue = shortenIri(activeContext, (String) expandedValue); // LINE: 135
        }
        resultMap.put(alias, ((Object) compactedValue)); // LINE: 139
        continue; // LINE: 140
      } else if ((expandedProperty == null && ((Object) TYPE) == null || expandedProperty != null && (expandedProperty).equals(TYPE))) { // LINE: 143
        asArray = (((activeContext.processingMode == null && ((Object) JSONLD11) == null || activeContext.processingMode != null && (activeContext.processingMode).equals(JSONLD11)) && aliasContainerMapping.contains(SET)) || !(compactArrays)); // LINE: 154
        addValue(resultMap, alias, (compactedTypes.size() == 1 ? compactedTypes.get(0) : compactedTypes), asArray); // LINE: 159
        continue; // LINE: 163
      } else if ((expandedProperty == null && ((Object) REVERSE) == null || expandedProperty != null && (expandedProperty).equals(REVERSE))) { // LINE: 166
        Map<String, Object> compactedMap = ((Map<String, Object>) compaction(activeContext, REVERSE, expandedValue, compactArrays, ordered)); // LINE: 168
        for (String prop : ((List<String>) new ArrayList(compactedMap.keySet()))) { // LINE: 171
          Object value = (Object) compactedMap.get(prop); // LINE: 172
          /*@Nullable*/ Term propTerm = (/*@Nullable*/ Term) activeContext.terms.get(prop); // LINE: 173
          if ((propTerm != null && propTerm.isReverseProperty)) { // LINE: 175
            asArray = (((activeContext.processingMode == null && ((Object) JSONLD11) == null || activeContext.processingMode != null && (activeContext.processingMode).equals(JSONLD11)) && propTerm.container.contains(SET)) || !(compactArrays)); // LINE: 177
            addValue(resultMap, prop, value, asArray); // LINE: 180
            compactedMap.remove(prop); // LINE: 182
          }
        }
        if (compactedMap.size() > 0) { // LINE: 184
          String revAlias = iriCompaction(activeContext, REVERSE); // LINE: 186
          resultMap.put(revAlias, compactedMap); // LINE: 188
        }
        continue; // LINE: 190
      } else if ((expandedProperty == null && ((Object) PRESERVE) == null || expandedProperty != null && (expandedProperty).equals(PRESERVE))) { // LINE: 193
        if (!expandedValue.equals(new ArrayList<>())) { // LINE: 196
          resultMap.put(PRESERVE, compaction(activeContext, activeProperty, expandedValue, compactArrays, ordered)); // LINE: 197
        }
      } else if (((expandedProperty == null && ((Object) INDEX) == null || expandedProperty != null && (expandedProperty).equals(INDEX)) && activeContainerMapping.contains(INDEX))) { // LINE: 201
        continue; // LINE: 202
      } else if (new HashSet(new ArrayList<>(Arrays.asList(new String[] {(String) DIRECTION, INDEX, LANGUAGE, VALUE}))).contains(expandedProperty)) { // LINE: 205
        resultMap.put(alias, expandedValue); // LINE: 208
        continue; // LINE: 209
      }
      String itemActiveProperty; // LINE: 211
      /*@Nullable*/ Term itemActiveTerm; // LINE: 212
      Map<String, Object> nestResult; // LINE: 213
      if ((expandedValue == null && ((Object) new ArrayList<>()) == null || expandedValue != null && (expandedValue).equals(new ArrayList<>()))) { // LINE: 215
        itemActiveProperty = iriCompaction(activeContext, expandedProperty, expandedValue, true, insideReverse); // LINE: 217
        itemActiveTerm = (Term) activeContext.terms.get(itemActiveProperty); // LINE: 218
        nestResult = getNestResult(activeContext, itemActiveTerm, resultMap); // LINE: 220
        addValueAsList(nestResult, itemActiveProperty, new ArrayList<>()); // LINE: 222
      }
      expandedValue = (Object) asList(expandedValue); // LINE: 225
      assert expandedValue instanceof List;
      for (Object expandedItem : (List) expandedValue) { // LINE: 228
        itemActiveProperty = iriCompaction(activeContext, expandedProperty, expandedItem, true, insideReverse); // LINE: 230
        itemActiveTerm = (Term) activeContext.terms.get(itemActiveProperty); // LINE: 231
        nestResult = getNestResult(activeContext, itemActiveTerm, resultMap); // LINE: 233
        List<String> container; // LINE: 235
        if ((itemActiveTerm != null && itemActiveTerm.container != null)) { // LINE: 236
          container = (List<String>) itemActiveTerm.container; // LINE: 237
        } else {
          container = new ArrayList<>(); // LINE: 239
        }
        asArray = ((container.contains(SET) || new HashSet(new ArrayList<>(Arrays.asList(new String[] {(String) GRAPH, LIST}))).contains(itemActiveProperty)) || !(compactArrays)); // LINE: 241
        Object itemToCompact = expandedItem; // LINE: 245
        Boolean itemIsListObject = false; // LINE: 246
        Boolean itemIsGraphObject = false; // LINE: 247
        if (expandedItem instanceof Map) { // LINE: 248
          if (((Map) expandedItem).containsKey(LIST)) { // LINE: 249
            itemToCompact = ((Map) expandedItem).get(LIST); // LINE: 250
            itemIsListObject = true; // LINE: 251
          }
          if (isGraphObject((Map) expandedItem)) { // LINE: 252
            itemToCompact = ((Map) expandedItem).get(GRAPH); // LINE: 253
            itemIsGraphObject = true; // LINE: 254
          }
        }
        compactedItem = compaction(activeContext, itemActiveProperty, itemToCompact, compactArrays, ordered); // LINE: 256
        if (itemIsListObject) { // LINE: 260
          assert expandedItem instanceof Map;
          if (!(compactedItem instanceof List)) { // LINE: 264
            compactedItem = new ArrayList<>(Arrays.asList(new Object[] {(Object) compactedItem})); // LINE: 265
          }
          if (!container.contains(LIST)) { // LINE: 267
            compactedItem = Builtins.mapOf(iriCompaction(activeContext, LIST), compactedItem); // LINE: 269
            assert compactedItem instanceof Map;
            if (((Map) expandedItem).containsKey(INDEX)) { // LINE: 272
              ((Map) compactedItem).put(iriCompaction(activeContext, INDEX), ((Map) expandedItem).get(INDEX)); // LINE: 273
            }
            addValue(nestResult, itemActiveProperty, (Map) compactedItem, asArray); // LINE: 275
            continue; // LINE: 277
          } else if (activeProperty != null) { // LINE: 279
            nestResult.put(activeProperty, (List) compactedItem); // LINE: 280
          }
        }
        Map<String, Object> mapObject; // LINE: 283
        /*@Nullable*/ String mapKey = null; // LINE: 284
        if (itemIsGraphObject) { // LINE: 285
          assert expandedItem instanceof Map;
          if ((container.contains(GRAPH) && container.contains(ID))) { // LINE: 288
            if (!nestResult.containsKey(itemActiveProperty)) nestResult.put(itemActiveProperty, new HashMap<>());
            mapObject = ((Map<String, Object>) nestResult.get(itemActiveProperty)); // LINE: 290
            String idOrNone = (String) (((Map) expandedItem).containsKey(ID) ? ((String) ((Map) expandedItem).get(ID)) : NONE); // LINE: 292
            mapKey = (String) iriCompaction(activeContext, idOrNone, null, !((Map) expandedItem).containsKey(ID)); // LINE: 293
            addValue(mapObject, mapKey, compactedItem, asArray); // LINE: 295
          } else if ((container.contains(GRAPH) && container.contains(INDEX) && isSimpleGraphObject((Map) expandedItem))) { // LINE: 297
            if (!nestResult.containsKey(itemActiveProperty)) nestResult.put(itemActiveProperty, new HashMap<>());
            mapObject = ((Map<String, Object>) nestResult.get(itemActiveProperty)); // LINE: 299
            String indexOrNone = (String) (((Map) expandedItem).containsKey(INDEX) ? ((String) ((Map) expandedItem).get(INDEX)) : NONE); // LINE: 301
            mapKey = iriCompaction(activeContext, indexOrNone); // LINE: 302
            addValue(mapObject, mapKey, compactedItem, asArray); // LINE: 304
          } else if ((container.contains(GRAPH) && isSimpleGraphObject((Map) expandedItem))) { // LINE: 306
            if ((compactedItem instanceof List && ((List) compactedItem).size() > 1)) { // LINE: 308
              compactedItem = Builtins.mapOf(iriCompaction(activeContext, INCLUDED), compactedItem); // LINE: 309
            }
            addValue(nestResult, itemActiveProperty, compactedItem, asArray); // LINE: 311
          } else {
            compactedItem = Builtins.mapOf(iriCompaction(activeContext, GRAPH), compactedItem); // LINE: 315
            assert compactedItem instanceof Map;
            if (((Map) expandedItem).containsKey(ID)) { // LINE: 318
              ((Map) compactedItem).put(iriCompaction(activeContext, ID), shortenIri(activeContext, ((String) ((Map) expandedItem).get(ID)))); // LINE: 319
            }
            if (((Map) expandedItem).containsKey(INDEX)) { // LINE: 321
              ((Map) compactedItem).put(iriCompaction(activeContext, INDEX), iriCompaction(activeContext, ((String) ((Map) expandedItem).get(INDEX)))); // LINE: 322
            }
            addValue(nestResult, itemActiveProperty, (Map) compactedItem, asArray); // LINE: 324
          }
        } else if (((container.contains(LANGUAGE) || container.contains(INDEX) || container.contains(ID) || container.contains(TYPE)) && !container.contains(GRAPH))) { // LINE: 327
          assert expandedItem instanceof Map;
          if (!nestResult.containsKey(itemActiveProperty)) nestResult.put(itemActiveProperty, new HashMap<>());
          mapObject = ((Map<String, Object>) nestResult.get(itemActiveProperty)); // LINE: 333
          String containerKw = (String) ((String) (container.contains(LANGUAGE) ? LANGUAGE : (container.contains(INDEX) ? INDEX : (container.contains(ID) ? ID : (container.contains(TYPE) ? TYPE : null))))); // LINE: 335
          String containerKey = iriCompaction(activeContext, containerKw); // LINE: 339
          String indexKey = ((itemActiveTerm != null && itemActiveTerm.index != null) ? itemActiveTerm.index : INDEX); // LINE: 341
          if ((container.contains(LANGUAGE) && ((Map) expandedItem).containsKey(VALUE))) { // LINE: 343
            if (compactedItem instanceof Map) { // LINE: 345
              compactedItem = ((Map) compactedItem).get(VALUE); // LINE: 346
            }
            mapKey = ((String) ((Map) expandedItem).get(LANGUAGE)); // LINE: 347
          } else if ((container.contains(INDEX) && (indexKey == null && ((Object) INDEX) == null || indexKey != null && (indexKey).equals(INDEX)))) { // LINE: 349
            if ((compactedItem instanceof Map && ((Map) compactedItem).containsKey(VALUE) && ((Map) compactedItem).size() == 1)) { // LINE: 351
              compactedItem = ((Map) compactedItem).get(VALUE); // LINE: 352
            }
            mapKey = ((String) ((Map) expandedItem).get(INDEX)); // LINE: 353
          } else if ((container.contains(INDEX) && !indexKey.equals(INDEX))) { // LINE: 355
            containerKey = iriCompaction(activeContext, indexKey); // LINE: 357
            if ((compactedItem instanceof Map && ((Map) compactedItem).containsKey(containerKey))) { // LINE: 360
              mapKey = (String) getMapKeyAndDepleteContainerKey((Map) compactedItem, containerKey, asArray); // LINE: 361
            }
          } else if (container.contains(ID)) { // LINE: 363
            assert compactedItem instanceof Map;
            mapKey = ((/*@Nullable*/ String) ((Map) compactedItem).remove(containerKey)); // LINE: 365
          } else if (container.contains(TYPE)) { // LINE: 367
            assert compactedItem instanceof Map;
            if (((Map) compactedItem).containsKey(containerKey)) { // LINE: 372
              mapKey = (String) getMapKeyAndDepleteContainerKey((Map) compactedItem, containerKey, asArray); // LINE: 373
            }
            if (((Map) compactedItem).size() == 1) { // LINE: 375
              for (Map.Entry<String, Object> key_idval : ((Map<String, Object>) compactedItem).entrySet()) { // LINE: 376
                String key = key_idval.getKey();
                Object idval = key_idval.getValue();
                if ((activeContext.expandVocabIri(key) == null && ((Object) ID) == null || activeContext.expandVocabIri(key) != null && (activeContext.expandVocabIri(key)).equals(ID))) { // LINE: 377
                  compactedItem = compaction(activeContext, itemActiveProperty, Builtins.mapOf(ID, idval)); // LINE: 378
                }
              }
            }
          }
          if (mapKey == null) { // LINE: 381
            mapKey = iriCompaction(activeContext, NONE); // LINE: 382
          }
          addValue(mapObject, mapKey, compactedItem, asArray); // LINE: 384
        } else {
          addValue(nestResult, itemActiveProperty, compactedItem, asArray); // LINE: 388
        }
      }
    }
    return result; // LINE: 391
  }

  protected static /*@Nullable*/ String getMapKeyAndDepleteContainerKey(Map<String, Object> compactedItem, String containerKey, Boolean asArray) { // LINE: 394
    List<String> containerKeyValues = (List<String>) asList(compactedItem.get(containerKey)); // LINE: 398
    Object keyValue = (Object) containerKeyValues.remove(0); // LINE: 400
    if (!(keyValue instanceof String)) { // LINE: 401
      return null; // LINE: 402
    }
    String mapKey = (String) keyValue; // LINE: 403
    if (compactedItem.get(containerKey) != containerKeyValues) { // LINE: 405
      for (Object remaining : new ArrayList(containerKeyValues)) { // LINE: 406
        addValue(compactedItem, containerKey, remaining); // LINE: 407
      }
    }
    if ((containerKeyValues.size() == 1 && !(asArray))) { // LINE: 409
      compactedItem.put(containerKey, containerKeyValues.get(0)); // LINE: 410
    } else if (containerKeyValues.size() == 0) { // LINE: 411
      compactedItem.remove(containerKey); // LINE: 412
    }
    return mapKey; // LINE: 414
  }

  protected static Map<String, Object> getNestResult(Context activeContext, /*@Nullable*/ Term itemActiveTerm, Map<String, Object> resultMap) { // LINE: 417
    Map<String, Object> nestResult; // LINE: 422
    if ((itemActiveTerm != null && itemActiveTerm.nestValue != null)) { // LINE: 423
      if ((!itemActiveTerm.nestValue.equals(NEST) && !activeContext.expandVocabIri(itemActiveTerm.nestValue).equals(NEST))) { // LINE: 425
        throw new InvalidNestValueError(itemActiveTerm.nestValue); // LINE: 427
      }
      if (!resultMap.containsKey(itemActiveTerm.nestValue)) { // LINE: 429
        resultMap.put(itemActiveTerm.nestValue, new HashMap<>()); // LINE: 430
      }
      return ((Map<String, Object>) resultMap.get(itemActiveTerm.nestValue)); // LINE: 432
    } else {
      return resultMap; // LINE: 435
    }
  }

  public static /*@Nullable*/ String maybeIriCompaction(Context activeContext, /*@Nullable*/ String iri) {
    return maybeIriCompaction(activeContext, iri, null);
  }
  public static /*@Nullable*/ String maybeIriCompaction(Context activeContext, /*@Nullable*/ String iri, /*@Nullable*/ Object value) {
    return maybeIriCompaction(activeContext, iri, value, true);
  }
  public static /*@Nullable*/ String maybeIriCompaction(Context activeContext, /*@Nullable*/ String iri, /*@Nullable*/ Object value, Boolean vocab) {
    return maybeIriCompaction(activeContext, iri, value, vocab, false);
  }
  public static /*@Nullable*/ String maybeIriCompaction(Context activeContext, /*@Nullable*/ String iri, /*@Nullable*/ Object value, Boolean vocab, Boolean reverse) { // LINE: 438
    if (iri == null) { // LINE: 445
      return null; // LINE: 446
    }
    return iriCompaction(activeContext, iri, value, vocab, reverse); // LINE: 447
  }

  public static String shortenIri(Context activeContext, String iri) { // LINE: 452
    return iriCompaction(activeContext, iri, null, false); // LINE: 453
  }

  public static String iriCompaction(Context activeContext, String iri) {
    return iriCompaction(activeContext, iri, null);
  }
  public static String iriCompaction(Context activeContext, String iri, /*@Nullable*/ Object value) {
    return iriCompaction(activeContext, iri, value, true);
  }
  public static String iriCompaction(Context activeContext, String iri, /*@Nullable*/ Object value, Boolean vocab) {
    return iriCompaction(activeContext, iri, value, vocab, false);
  }
  public static String iriCompaction(Context activeContext, String iri, /*@Nullable*/ Object value, Boolean vocab, Boolean reverse) { // LINE: 456
    Map inverseContext = (Map) getInverseContext(activeContext); // LINE: 462
    if ((vocab && inverseContext.containsKey(iri))) { // LINE: 465
      String defaultLanguage = (activeContext.defaultLanguage != null ? activeContext.defaultLanguage : NONE); // LINE: 467
      if (activeContext.defaultBaseDirection != null) { // LINE: 468
        defaultLanguage = defaultLanguage + "_" + activeContext.defaultBaseDirection; // LINE: 470
      }
      if ((value instanceof Map && ((Map) value).containsKey(PRESERVE))) { // LINE: 473
        List values = (List) asList(((Map) value).get(PRESERVE)); // LINE: 474
        value = (Map) values.get(0); // LINE: 475
      }
      List<String> containers = new ArrayList<>(); // LINE: 478
      String typeOrLanguage = LANGUAGE; // LINE: 481
      String typeOrLanguageValue = NULL; // LINE: 482
      if ((value instanceof Map && ((Map) value).containsKey(INDEX) && !((Map) value).containsKey(GRAPH))) { // LINE: 485
        containers.add(INDEX); // LINE: 486
        containers.add(INDEX + SET); // LINE: 487
      }
      if (reverse) { // LINE: 490
        typeOrLanguage = TYPE; // LINE: 491
        typeOrLanguageValue = REVERSE; // LINE: 492
        containers.add(SET); // LINE: 493
      } else if ((value instanceof Map && ((Map) value).containsKey(LIST))) { // LINE: 495
        if (!((Map) value).containsKey(INDEX)) { // LINE: 497
          containers.add(LIST); // LINE: 498
        }
        List<Map<String, Object>> valuelist = (List<Map<String, Object>>) ((List<Map<String, Object>>) ((Map) value).get(LIST)); // LINE: 500
        /*@Nullable*/ String commonType = null; // LINE: 502
        /*@Nullable*/ String commonLanguage = null; // LINE: 503
        if (valuelist.size() == 0) { // LINE: 504
          commonLanguage = defaultLanguage; // LINE: 505
        }
        for (Map<String, Object> item : valuelist) { // LINE: 507
          String itemLanguage = NONE; // LINE: 510
          String itemType = NONE; // LINE: 511
          if ((item instanceof Map && ((Map) item).containsKey(VALUE))) { // LINE: 513
            if (((Map) item).containsKey(DIRECTION)) { // LINE: 515
              itemLanguage = ((String) ((Map) item).getOrDefault(LANGUAGE, "")) + "_" + ((Map) item).get(DIRECTION); // LINE: 516
            } else if (((Map) item).containsKey(LANGUAGE)) { // LINE: 518
              itemLanguage = ((String) ((Map) item).get(LANGUAGE)); // LINE: 519
            } else if (((Map) item).containsKey(TYPE)) { // LINE: 521
              itemType = ((String) ((Map) item).get(TYPE)); // LINE: 522
            } else {
              itemLanguage = NULL; // LINE: 525
            }
          } else {
            itemType = ID; // LINE: 528
          }
          if (commonLanguage == null) { // LINE: 530
            commonLanguage = itemLanguage; // LINE: 531
          } else if ((!itemLanguage.equals(commonLanguage) && item instanceof Map && ((Map) item).containsKey(VALUE))) { // LINE: 533
            commonLanguage = NONE; // LINE: 534
          }
          if (commonType == null) { // LINE: 536
            commonType = itemType; // LINE: 537
          } else if (!itemType.equals(commonType)) { // LINE: 539
            commonType = NONE; // LINE: 540
          }
          if (((commonLanguage == null && ((Object) NONE) == null || commonLanguage != null && (commonLanguage).equals(NONE)) && (commonType == null && ((Object) NONE) == null || commonType != null && (commonType).equals(NONE)))) { // LINE: 542
            break; // LINE: 543
          }
        }
        if (commonLanguage == null) { // LINE: 545
          commonLanguage = NONE; // LINE: 546
        }
        if (commonType == null) { // LINE: 548
          commonType = NONE; // LINE: 549
        }
        if (!commonType.equals(NONE)) { // LINE: 551
          typeOrLanguage = TYPE; // LINE: 552
          typeOrLanguageValue = commonType; // LINE: 553
        } else {
          typeOrLanguageValue = commonLanguage; // LINE: 556
        }
      } else if ((value instanceof Map && ((Map) value).containsKey(GRAPH))) { // LINE: 558
        if (((Map) value).containsKey(INDEX)) { // LINE: 560
          containers.add(GRAPH + INDEX); // LINE: 561
          containers.add(GRAPH + INDEX + SET); // LINE: 562
        }
        if (((Map) value).containsKey(ID)) { // LINE: 564
          containers.add(GRAPH + ID); // LINE: 565
          containers.add(GRAPH + ID + SET); // LINE: 566
        }
        containers.add(GRAPH); // LINE: 568
        containers.add(GRAPH + SET); // LINE: 569
        containers.add(SET); // LINE: 570
        if (!((Map) value).containsKey(INDEX)) { // LINE: 572
          containers.add(GRAPH + INDEX); // LINE: 573
          containers.add(GRAPH + INDEX + SET); // LINE: 574
        }
        if (!((Map) value).containsKey(ID)) { // LINE: 576
          containers.add(GRAPH + ID); // LINE: 577
          containers.add(GRAPH + ID + SET); // LINE: 578
        }
        containers.add(INDEX); // LINE: 580
        containers.add(INDEX + SET); // LINE: 581
        typeOrLanguage = TYPE; // LINE: 583
        typeOrLanguageValue = ID; // LINE: 584
      } else {
        if ((value instanceof Map && ((Map) value).containsKey(VALUE))) { // LINE: 588
          if ((((Map) value).containsKey(DIRECTION) && !((Map) value).containsKey(INDEX))) { // LINE: 590
            typeOrLanguageValue = ((String) ((Map) value).getOrDefault(LANGUAGE, "")) + "_" + ((Map) value).get(DIRECTION); // LINE: 591
            containers.add(LANGUAGE); // LINE: 592
            containers.add(LANGUAGE + SET); // LINE: 593
          } else if ((((Map) value).containsKey(LANGUAGE) && !((Map) value).containsKey(INDEX))) { // LINE: 595
            typeOrLanguageValue = ((String) ((Map) value).get(LANGUAGE)); // LINE: 596
            containers.add(LANGUAGE); // LINE: 597
            containers.add(LANGUAGE + SET); // LINE: 598
          } else if (((Map) value).containsKey(TYPE)) { // LINE: 600
            typeOrLanguageValue = ((String) ((Map) value).get(TYPE)); // LINE: 601
            typeOrLanguage = TYPE; // LINE: 602
          }
        } else {
          typeOrLanguage = TYPE; // LINE: 605
          typeOrLanguageValue = ID; // LINE: 606
          containers.add(ID); // LINE: 607
          containers.add(ID + SET); // LINE: 608
          containers.add(TYPE); // LINE: 609
          containers.add(SET + TYPE); // LINE: 610
        }
        containers.add(SET); // LINE: 612
      }
      containers.add(NONE); // LINE: 615
      if (!activeContext.processingMode.equals(JSONLD10)) { // LINE: 617
        if ((!(value instanceof Map) || !((Map) value).containsKey(INDEX))) { // LINE: 618
          containers.add(INDEX); // LINE: 619
          containers.add(INDEX + SET); // LINE: 620
        }
      }
      if (!activeContext.processingMode.equals(JSONLD10)) { // LINE: 622
        if ((value instanceof Map && ((Map) value).size() == 1 && ((Map) value).containsKey(VALUE))) { // LINE: 623
          containers.add(LANGUAGE); // LINE: 624
          containers.add(LANGUAGE + SET); // LINE: 625
        }
      }
      if (typeOrLanguageValue == null) { // LINE: 627
        typeOrLanguageValue = NULL; // LINE: 628
      }
      List<String> preferredValues = new ArrayList<>(); // LINE: 630
      if ((typeOrLanguageValue == null && ((Object) REVERSE) == null || typeOrLanguageValue != null && (typeOrLanguageValue).equals(REVERSE))) { // LINE: 632
        preferredValues.add(REVERSE); // LINE: 633
      }
      if ((new HashSet(new ArrayList<>(Arrays.asList(new String[] {(String) ID, REVERSE}))).contains(typeOrLanguageValue) && value instanceof Map && ((Map) value).containsKey(ID))) { // LINE: 635
        String compactId = (String) iriCompaction(activeContext, ((String) ((Map) value).get(ID))); // LINE: 637
        /*@Nullable*/ Term idTerm = (/*@Nullable*/ Term) activeContext.terms.get(compactId); // LINE: 638
        if ((idTerm != null && (idTerm.iri == null && ((Object) ((Map) value).get(ID)) == null || idTerm.iri != null && (idTerm.iri).equals(((Map) value).get(ID))))) { // LINE: 639
          preferredValues.add(VOCAB); // LINE: 640
          preferredValues.add(ID); // LINE: 641
          preferredValues.add(NONE); // LINE: 642
        } else {
          preferredValues.add(ID); // LINE: 645
          preferredValues.add(VOCAB); // LINE: 646
          preferredValues.add(NONE); // LINE: 647
        }
      } else {
        preferredValues.add(typeOrLanguageValue); // LINE: 650
        preferredValues.add(NONE); // LINE: 651
        if ((value instanceof Map && ((Map) value).containsKey(LIST))) { // LINE: 652
          List listvalue = (List) ((List) ((Map) value).get(LIST)); // LINE: 653
          if (listvalue.size() == 0) { // LINE: 654
            typeOrLanguage = ANY; // LINE: 655
          }
        }
      }
      preferredValues.add(ANY); // LINE: 657
      for (String pv : ((List<String>) new ArrayList(preferredValues))) { // LINE: 659
        Integer idx = (Integer) pv.indexOf("_"); // LINE: 660
        if (idx > -1) { // LINE: 661
          preferredValues.add(pv.substring(idx)); // LINE: 662
        }
      }
      /*@Nullable*/ String termKey = termSelection(activeContext, iri, containers, typeOrLanguage, preferredValues); // LINE: 664
      if (termKey != null) { // LINE: 666
        return termKey; // LINE: 667
      }
    }
    if ((vocab && activeContext.vocabularyMapping != null)) { // LINE: 670
      if (iri.startsWith(activeContext.vocabularyMapping)) { // LINE: 672
        String suffix = (String) iri.substring(activeContext.vocabularyMapping.length()); // LINE: 673
        if ((suffix.length() > 0 && !activeContext.terms.containsKey(suffix))) { // LINE: 674
          return suffix; // LINE: 675
        }
      }
    }
    /*@Nullable*/ String compactIri = null; // LINE: 678
    for (Map.Entry<String, Term> key_termDfn : activeContext.terms.entrySet()) { // LINE: 681
      String key = key_termDfn.getKey();
      Term termDfn = key_termDfn.getValue();
      if ((termDfn.iri == null || (termDfn.iri == null && ((Object) iri) == null || termDfn.iri != null && (termDfn.iri).equals(iri)) || !(iri.startsWith(termDfn.iri)) || !(termDfn.isPrefix))) { // LINE: 683
        continue; // LINE: 684
      }
      String candidate = key + ":" + iri.substring(termDfn.iri.length()); // LINE: 686
      if ((compactIri == null || (candidate.length() <= compactIri.length() && candidate.compareTo(compactIri) < 0))) { // LINE: 688
        if ((!activeContext.terms.containsKey(candidate) || ((activeContext.terms.get(candidate).iri == null && ((Object) iri) == null || activeContext.terms.get(candidate).iri != null && (activeContext.terms.get(candidate).iri).equals(iri)) && value == null))) { // LINE: 689
          compactIri = candidate; // LINE: 690
        }
      }
    }
    if (compactIri != null) { // LINE: 693
      return compactIri; // LINE: 694
    }
    Integer colonx = (Integer) iri.indexOf(":"); // LINE: 697
    if ((colonx > -1 && !iri.contains("//"))) { // LINE: 698
      /*@Nullable*/ Term term = activeContext.terms.get(iri.substring(0, colonx)); // LINE: 699
      if ((term != null && term.isPrefix)) { // LINE: 700
        throw new IRIConfusedWithPrefixError(iri.toString()); // LINE: 701
      }
    }
    if (!(vocab)) { // LINE: 704
      iri = relativiseIri(activeContext.baseIri, iri); // LINE: 705
    }
    return iri; // LINE: 708
  }

  public static /*@Nullable*/ String termSelection(Context activeContext, String keywordOrIri, List<String> containers, String typeOrLanguage, List<String> preferredValues) { // LINE: 711
    Map inverseContext = (Map) getInverseContext(activeContext); // LINE: 718
    Map<String, Object> containerMap = ((Map<String, Object>) inverseContext.get(keywordOrIri)); // LINE: 720
    for (String container : containers) { // LINE: 722
      if (!containerMap.containsKey(container)) { // LINE: 724
        continue; // LINE: 725
      }
      Map<String, Object> typelanguageMap = ((Map<String, Object>) containerMap.get(container)); // LINE: 727
      Map<String, String> valueMap = ((Map<String, String>) typelanguageMap.get(typeOrLanguage)); // LINE: 729
      for (String item : preferredValues) { // LINE: 731
        if (!valueMap.containsKey(item)) { // LINE: 733
          continue; // LINE: 734
        }
        return valueMap.get(item); // LINE: 736
      }
    }
    return null; // LINE: 738
  }

  public static Object valueCompaction(Context activeContext, /*@Nullable*/ Term activeTerm, Map<String, Object> value) { // LINE: 741
    Object result = new HashMap(value); // LINE: 747
    Map inverseContext = (Map) getInverseContext(activeContext); // LINE: 750
    /*@Nullable*/ String language = (/*@Nullable*/ String) activeContext.defaultLanguage; // LINE: 752
    if ((activeTerm != null && activeTerm.language != null)) { // LINE: 753
      language = (String) activeTerm.language; // LINE: 754
    }
    /*@Nullable*/ String direction = (/*@Nullable*/ String) activeContext.defaultBaseDirection; // LINE: 756
    if ((activeTerm != null && activeTerm.direction != null)) { // LINE: 757
      direction = (String) activeTerm.direction; // LINE: 758
    }
    if (((value.containsKey(ID) && value.size() == 1) || (value.size() == 2 && value.containsKey(INDEX)))) { // LINE: 760
      if ((activeTerm != null && (activeTerm.typeMapping == null && ((Object) ID) == null || activeTerm.typeMapping != null && (activeTerm.typeMapping).equals(ID)))) { // LINE: 762
        result = (Object) shortenIri(activeContext, ((String) value.get(ID))); // LINE: 763
      } else if ((activeTerm != null && (activeTerm.typeMapping == null && ((Object) VOCAB) == null || activeTerm.typeMapping != null && (activeTerm.typeMapping).equals(VOCAB)))) { // LINE: 765
        result = (Object) iriCompaction(activeContext, ((String) value.get(ID))); // LINE: 766
      }
    } else if ((activeTerm != null && value.containsKey(TYPE) && (value.get(TYPE) == null && ((Object) activeTerm.typeMapping) == null || value.get(TYPE) != null && (value.get(TYPE)).equals(activeTerm.typeMapping)))) { // LINE: 768
      result = (Object) value.get(VALUE); // LINE: 769
    } else if (((activeTerm != null && (activeTerm.typeMapping == null && ((Object) NONE) == null || activeTerm.typeMapping != null && (activeTerm.typeMapping).equals(NONE))) || (value.containsKey(TYPE) && (activeTerm == null || !value.get(TYPE).equals(activeTerm.typeMapping))))) { // LINE: 771
      if ((result instanceof Map && ((Map) result).containsKey(TYPE))) { // LINE: 773
        Object rtype = (Object) ((Map) result).get(TYPE); // LINE: 775
        if (rtype instanceof List) { // LINE: 776
          List<String> ctypes = new ArrayList<>(); // LINE: 777
          for (Object t : (List) rtype) { // LINE: 778
            ctypes.add(iriCompaction(activeContext, ((String) t))); // LINE: 779
          }
          ((Map) result).put(TYPE, ctypes); // LINE: 780
        } else {
          ((Map) result).put(TYPE, iriCompaction(activeContext, ((String) rtype))); // LINE: 782
        }
      }
    } else if ((value.containsKey(VALUE) && !(value.get(VALUE) instanceof String))) { // LINE: 784
      if (((value.containsKey(INDEX) && activeTerm != null && activeTerm.container.contains(INDEX)) || !value.containsKey(INDEX))) { // LINE: 786
        result = (Object) value.get(VALUE); // LINE: 787
      }
    } else if ((value.containsKey(VALUE) && ((value.containsKey(LANGUAGE) && (value.get(LANGUAGE) == null && ((Object) language) == null || value.get(LANGUAGE) != null && (value.get(LANGUAGE)).equals(language))) || (NULLS.contains(language) && !value.containsKey(LANGUAGE))))) { // LINE: 789
      if ((!value.containsKey(DIRECTION) || (direction != null && (value.get(DIRECTION) == null && ((Object) direction) == null || value.get(DIRECTION) != null && (value.get(DIRECTION)).equals(direction))))) { // LINE: 790
        if ((!value.containsKey(INDEX) || (activeTerm != null && activeTerm.container.contains(INDEX)))) { // LINE: 792
          result = (Object) value.get(VALUE); // LINE: 793
        }
      }
    }
    if (result instanceof Map) { // LINE: 795
      Map compacted = new HashMap<>(); // LINE: 796
      for (Map.Entry<String, Object> k_v : ((Map<String, Object>) result).entrySet()) { // LINE: 797
        String k = k_v.getKey();
        Object v = k_v.getValue();
        compacted.put(iriCompaction(activeContext, k, v), v); // LINE: 798
      }
      result = compacted; // LINE: 799
    }
    return result; // LINE: 801
  }
}


text: Test running....


text:
package org.clearsilver.jni;

import java.io.File;
import java.util.regex.Pattern;

/**
 * Loads the ClearSilver JNI library.
 *
 *
By default, it attempts to load the library 'clearsilver-jni' from the
 * path specified in the 'java.library.path' system property. However, this
 * can be overriden by calling {@link #setLibraryName(String)} and
 * {@link #setLibrarySearchPaths(String[])}.

 *
 *
If this fails, the JVM exits with a code of 1. However, this strategy
 * can be changed using {@link #setFailureCallback(Runnable)}.

 */
public final class JNI {

  /**
   * Failure callback strategy that writes a message to sysout, then calls
   * System.exit(1).
   */
  public static Runnable EXIT_JVM = new Runnable() {
    public void run() {
      System.err.println("Could not load '" + libraryName + "'. Searched:");
      String platformLibraryName = System.mapLibraryName(libraryName);
      for (String path : librarySearchPaths) {
        System.err.println("  " +
            new File(path, platformLibraryName).getAbsolutePath());
      }
      System.err.println(
          "Try specifying -Djava.library.path=[directory] or calling "
              + JNI.class.getName() + ".setLibrarySearchPaths(String...)");
      System.exit(1);
    }
  };

  /**
   * Failure callback strategy that throws an UnsatisfiedLinkError, which
   * should be caught be client code.
   */
  public static Runnable THROW_ERROR = new Runnable() {
    public void run() {
      throw new UnsatisfiedLinkError("Could not load '" + libraryName + "'");
    }
  };

  private static Runnable failureCallback = EXIT_JVM;

  private static Object callbackLock = new Object();

  private static String libraryName = "clearsilver-jni";

  private static String[] librarySearchPaths
      = System.getProperty("java.library.path", ".").split(
          Pattern.quote(File.pathSeparator));

  private static volatile boolean successfullyLoadedLibrary;

  /**
   * Attempts to load the ClearSilver JNI library.
   *
   * @see #setFailureCallback(Runnable)
   */
  public static void loadLibrary() {

    // Library already loaded? Great - nothing to do.
    if (successfullyLoadedLibrary) {
      return;
    }

    synchronized (callbackLock) {

      // Search librarySearchPaths...
      String platformLibraryName = System.mapLibraryName(libraryName);
      for (String path : librarySearchPaths) {
        try {
          // Attempt to load the library in that path.
          System.load(new File(path, platformLibraryName).getAbsolutePath());
          // If we got here, it worked. We're done.
          successfullyLoadedLibrary = true;
          return;
        } catch (UnsatisfiedLinkError e) {
          // Library not found. Continue loop.
        }
      }

      // Still here? Couldn't load library. Fail.
      if (failureCallback != null) {
        failureCallback.run();
      }
    }

  }

  /**
   * Sets a callback for what should happen if the JNI library cannot
   * be loaded. The default is {@link #EXIT_JVM}.
   *
   * @see #EXIT_JVM
   * @see #THROW_ERROR
   */
  public static void setFailureCallback(Runnable failureCallback) {
    synchronized(callbackLock) {
      JNI.failureCallback = failureCallback;
    }
  }

  /**
   * Set name of JNI library to load. Default is 'clearsilver-jni'.
   */
  public static void setLibraryName(String libraryName) {
    JNI.libraryName = libraryName;
  }

  /**
   * Sets locations where JNI library is searched.
   */
  public static void setLibrarySearchPaths(String... paths) {
    JNI.librarySearchPaths = paths;
  }

}


text:
<?php
return array (
  'Request space membership' => 'Złóż podanie o członkostwo w strefie',
  'Close' => 'Zamknij',
  'Your request was successfully submitted to the space administrators.' => 'Twoje podanie z powodzeniem zostało dodane i przesłane administratorom strefy.',
);


text:
package br.com.tdc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@Controller
public class TodosController {

    @Autowired
    private TodoRepository repository;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index() {
        return "todos";
    }

    @ResponseBody
    @RequestMapping(value = "/api/all", method = RequestMethod.GET)
    public Iterable<Todo> all() {
        return repository.findAll();
    }

    @ResponseBody
    @RequestMapping(value = "/api/save", method = RequestMethod.POST)
    public Iterable<Todo> save(@RequestBody Todo todo) {
        repository.save(todo);
        return repository.findAll();
    }

    @ResponseBody
    @RequestMapping(value = "/api/delete/{id}", method = RequestMethod.DELETE)
    public Iterable<Todo> delete(@PathVariable Integer id) {
        repository.delete(id);
        return repository.findAll();
    }

}


text:
package selfupdate

import (
	"context"
	"fmt"
	"net/http"
	"os"
	"regexp"

	"github.com/google/go-github/v30/github"
	gitconfig "github.com/tcnksm/go-gitconfig"
	"golang.org/x/oauth2"
)

// Updater is responsible for managing the context of self-update.
// It contains GitHub client and its context.
type Updater struct {
	api       *github.Client
	apiCtx    context.Context
	validator Validator
	filters   []*regexp.Regexp
}

// Config represents the configuration of self-update.
type Config struct {
	// APIToken represents GitHub API token. If it's not empty, it will be used for authentication of GitHub API
	APIToken string
	// EnterpriseBaseURL is a base URL of GitHub API. If you want to use this library with GitHub Enterprise,
	// please set "https://{your-organization-address}/api/v3/" to this field.
	EnterpriseBaseURL string
	// EnterpriseUploadURL is a URL to upload stuffs to GitHub Enterprise instance. This is often the same as an API base URL.
	// So if this field is not set and EnterpriseBaseURL is set, EnterpriseBaseURL is also set to this field.
	EnterpriseUploadURL string
	// Validator represents types which enable additional validation of downloaded release.
	Validator Validator
	// Filters are regexp used to filter on specific assets for releases with multiple assets.
	// An asset is selected if it matches any of those, in addition to the regular tag, os, arch, extensions.
	// Please make sure that your filter(s) uniquely match an asset.
	Filters []string
}

func newHTTPClient(ctx context.Context, token string) *http.Client {
	if token == "" {
		return http.DefaultClient
	}
	src := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
	return oauth2.NewClient(ctx, src)
}

// NewUpdater creates a new updater instance. It initializes GitHub API client.
// If you set your API token to $GITHUB_TOKEN, the client will use it.
func NewUpdater(config Config) (*Updater, error) {
	token := config.APIToken
	if token == "" {
		token = os.Getenv("GITHUB_TOKEN")
	}
	if token == "" {
		token, _ = gitconfig.GithubToken()
	}
	ctx := context.Background()
	hc := newHTTPClient(ctx, token)

	filtersRe := make([]*regexp.Regexp, 0, len(config.Filters))
	for _, filter := range config.Filters {
		re, err := regexp.Compile(filter)
		if err != nil {
			return nil, fmt.Errorf("Could not compile regular expression %q for filtering releases: %v", filter, err)
		}
		filtersRe = append(filtersRe, re)
	}

	if config.EnterpriseBaseURL == "" {
		client := github.NewClient(hc)
		return &Updater{api: client, apiCtx: ctx, validator: config.Validator, filters: filtersRe}, nil
	}

	u := config.EnterpriseUploadURL
	if u == "" {
		u = config.EnterpriseBaseURL
	}
	client, err := github.NewEnterpriseClient(config.EnterpriseBaseURL, u, hc)
	if err != nil {
		return nil, err
	}
	return &Updater{api: client, apiCtx: ctx, validator: config.Validator, filters: filtersRe}, nil
}

// DefaultUpdater creates a new updater instance with default configuration.
// It initializes GitHub API client with default API base URL.
// If you set your API token to $GITHUB_TOKEN, the client will use it.
func DefaultUpdater() *Updater {
	token := os.Getenv("GITHUB_TOKEN")
	if token == "" {
		token, _ = gitconfig.GithubToken()
	}
	ctx := context.Background()
	client := newHTTPClient(ctx, token)
	return &Updater{api: github.NewClient(client), apiCtx: ctx}
}


text:
DELIMITER /
INSERT INTO SEQ_QUESTIONNAIRE_REF_ID VALUES(NULL)
/
INSERT INTO QUESTIONNAIRE_USAGE(QUESTIONNAIRE_USAGE_ID,QUESTIONNAIRE_REF_ID_FK,MODULE_ITEM_CODE,MODULE_SUB_ITEM_CODE,RULE_ID,QUESTIONNAIRE_LABEL,QUESTIONNAIRE_SEQUENCE_NUMBER,UPDATE_USER,UPDATE_TIMESTAMP,OBJ_ID,VER_NBR)
VALUES ((SELECT (MAX(ID)) FROM SEQ_QUESTIONNAIRE_REF_ID),(SELECT QUESTIONNAIRE_REF_ID FROM QUESTIONNAIRE WHERE NAME = 'IRB Long' AND SEQUENCE_NUMBER = 1),(SELECT MODULE_CODE FROM COEUS_MODULE WHERE DESCRIPTION = 'IRB'),0,NULL,'IRB Questionnaire 1',1,'admin',NOW(),UUID(),1)
/
INSERT INTO SEQ_QUESTIONNAIRE_REF_ID VALUES(NULL)
/
INSERT INTO QUESTIONNAIRE_USAGE(QUESTIONNAIRE_USAGE_ID,QUESTIONNAIRE_REF_ID_FK,MODULE_ITEM_CODE,MODULE_SUB_ITEM_CODE,RULE_ID,QUESTIONNAIRE_LABEL,QUESTIONNAIRE_SEQUENCE_NUMBER,UPDATE_USER,UPDATE_TIMESTAMP,OBJ_ID,VER_NBR)
VALUES ((SELECT (MAX(ID)) FROM SEQ_QUESTIONNAIRE_REF_ID),(SELECT QUESTIONNAIRE_REF_ID FROM QUESTIONNAIRE WHERE NAME = 'IRB Long' AND SEQUENCE_NUMBER = 2),(SELECT MODULE_CODE FROM COEUS_MODULE WHERE DESCRIPTION = 'IRB'),0,NULL,'IRB Questionnaire 1 V2',1,'admin',NOW(),UUID(),1)
/
DELIMITER ;


text:
package com.marv;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.github.paolorotolo.appintro.AppIntro;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class Introduction extends AppIntro implements Introduction_Slide2.OnFragmentInteractionListener,Introduction_Slide3.OnFragmentInteractionListener, Introduction_Slide4.OnFragmentInteractionListener {

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private boolean signUp = false;
    private boolean authenticate = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAuth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d("TAG", "onAuthStateChanged:signed_in:" + user.getUid());
                } else {
                    // User is signed out
                    Log.d("TAG", "onAuthStateChanged:signed_out");
                }
                // ...
            }
        };
        showStatusBar(false);
        showSkipButton(false);
        setColorDoneText(getResources().getColor(R.color.Black));
        setColorTransitionsEnabled(true);
        setImmersive(true);
        Fragment fragment1 = new Introduction_Slide1();
        Fragment fragment2 = new Introduction_Slide2();
        Fragment fragment3 = new Introduction_Slide3();
        Fragment fragment4 = new Introduction_Slide4();
        Fragment fragment5 = new Introduction_Slide5();
        Fragment fragment6 = new Introduction_Slide6();
        addSlide(fragment1);
        addSlide(fragment2);
        addSlide(fragment3);
        addSlide(fragment4);
        if(UniversalClass.isRooted)addSlide(fragment6);
        addSlide(fragment5);
    }

    @Override
    public void onSkipPressed(Fragment currentFragment) {
        super.onSkipPressed(currentFragment);
        // Do something when users tap on Skip button.
    }

    @Override
    public void onDonePressed(Fragment currentFragment) {
        super.onDonePressed(currentFragment);
        // Do something when users tap on Done button
        LayoutInflater inflater= LayoutInflater.from(Introduction.this);
                final View setupcomplete=inflater.inflate(R.layout.setup_complete_dialog, null);
                AlertDialog.Builder ab=new AlertDialog.Builder(Introduction.this);
                ab.setView(setupcomplete);
                ab.setCancelable(true);
                ab.create();
                final AlertDialog show=ab.show();
                TextView introcomplete=(TextView) setupcomplete.findViewById(R.id.introcomplete);
                introcomplete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SharedPreferences sp = getSharedPreferences("com.marv_preferences",MODE_PRIVATE);
                        SharedPreferences.Editor edit = sp.edit();
                        edit.putBoolean("First Launch", false);
                        edit.commit();
                        startActivity(new Intent(Introduction.this, SplashActivity.class));
                        finish();
                    }
                });
    }

    @Override
    public void onSlideChanged(@Nullable Fragment oldFragment, @Nullable Fragment newFragment) {
        super.onSlideChanged(oldFragment, newFragment);
        // Do something when the slide changes.
    }

    @Override
    public void onFragmentInteraction(String id) {
        switch (id){
            case "grantpermissions": Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivity(intent);
                break;
            case "submit": onResume();
                if(UniversalClass.username.isEmpty()||UniversalClass.password.isEmpty()){
                    AlertDialog.Builder ab=new AlertDialog.Builder(Introduction.this);
                    ab.setMessage("It is not necessary to complete this step. But if you wish to do so, please use a valid email ID and password.");
                    ab.setPositiveButton("OKAY", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //Dismiss the dialog box
                        }
                    });
                    ab.setCancelable(true);
                    ab.create();
                    ab.show();
                    authenticate = false;
                }
                if(authenticate) {
                    SharedPreferences sp = getSharedPreferences("com.marv_preferences", MODE_PRIVATE);
                    SharedPreferences.Editor edit = sp.edit();
                    if (UniversalClass.username.isEmpty()) {
                        UniversalClass.username = "friend";
                    }
                    edit.putString("Name", UniversalClass.username);
                    edit.commit();
                    mAuth.createUserWithEmailAndPassword(UniversalClass.email, UniversalClass.password)
                            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                                @Override
                                public void onComplete(@NonNull Task<AuthResult> task) {
                                    Log.d("TAG", "createUserWithEmail:onComplete:" + task.isSuccessful());
                                    if (task.isSuccessful()) {
                                        Toast.makeText(getApplicationContext(), "Account created successfully!", Toast.LENGTH_SHORT).show();
                                        signUp = true;
                                    }
                                    // If sign in fails, display a message to the user. If sign in succeeds
                                    // the auth state listener will be notified and logic to handle the
                                    // signed in user can be handled in the listener.
                                    if (!task.isSuccessful()) {
                                        signUp = false;
                                    }

                                    // ...
                                }
                            });
                    if (!signUp) {
                        mAuth.signInWithEmailAndPassword(UniversalClass.email, UniversalClass.password)
                                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                                    @Override
                                    public void onComplete(@NonNull Task<AuthResult> task) {
                                        Log.d("TAG", "signInWithEmail:onComplete:" + task.isSuccessful());
                                        if (task.isSuccessful()) {
                                            Toast.makeText(getApplicationContext(), "Welcome back!", Toast.LENGTH_SHORT).show();
                                            signUp = false;
                                        }
                                        // If sign in fails, display a message to the user. If sign in succeeds
                                        // the auth state listener will be notified and logic to handle the
                                        // signed in user can be handled in the listener.
                                        if (!task.isSuccessful()) {
                                            signUp = true;
                                            Log.w("TAG", "signInWithEmail:failed", task.getException());
                                            Toast.makeText(getApplicationContext(), "Sign in Failed!", Toast.LENGTH_SHORT).show();
                                        }

                                        // ...
                                    }
                                });
                    }
                    authenticate = true;
                }
                break;
            case "introcando": startActivity(new Intent(Introduction.this,Help.class)); UniversalClass.introBackStack=true;
                break;
        }
    }

    @Override
    protected void onResume() {
        if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        super.onResume();
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
    }

    @Override
    protected void onPause() {
        super.onPause();
        FirebaseAuth.getInstance().signOut();
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

}


text:
package me.drton.jmavsim;

import javax.vecmath.Vector3d;

/**
 * User: ton Date: 28.11.13 Time: 20:35
 */
public abstract class Environment extends WorldObject {
    public Environment(World world) {
        super(world);
    }

    /**
     * Get gravity vector.
     * Should be pointed to ground.
     *
     * @return gravity vector
     */
    public abstract Vector3d getG();

    /**
     * Get magnetic field vector in specified point.
     *
     * @param point point in NED frame
     * @return magnetic field vector
     */
    public abstract Vector3d getMagField(Vector3d point);

    /**
     * Get wind (air velocity) vector in specified point.
     *
     * @param point point in NED frame
     * @return wind vector
     */
    public abstract Vector3d getWind(Vector3d point);

    /**
     * Get ground level for specified point.
     * Multilevel environment may be simulated, in this case method should return level under specified point.
     *
     * @param point point in NED frame
     * @return ground level in NED frame
     */
    public abstract double getGroundLevel(Vector3d point);
}


text:
<?php

namespace GraphicObjectTemplating\Controller;

use GraphicObjectTemplating\Objects\ODContent;
use GraphicObjectTemplating\Objects\OSContainer;
use Zend\Config\Config;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class GOTController extends AbstractActionController
{

    public function indexAction()
    {
        return new ViewModel();
    }

    public function render($object)
    {
        $id   = $object->getId();
        $conf = $object->getProperties();
        $conf = new Config($conf);

        $typObj = $conf->object;
        if ($object instanceof ODContent)
        {
            $prefix = "odcontent/";
        } elseif ($object instanceof OSContainer) {
            $prefix = "oscontainer/";
        } else {
            $prefix = "";
        }
        $template = "graphic-objet-templating/" .$prefix .$typObj ."/" .$typObj .".phtml";

        $view = new ViewModel();
        $view->setTerminal(true);
        $view->setTemplate($template);

        return $view;
    }

}


text:
<!doctype html>
<!--
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE
The complete set of authors may be found at http://polymer.github.io/AUTHORS
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS
-->
<html>
<head>
  <meta charset="UTF-8">
  <title>app-scroll-effects tests</title>
  <script src="../../../web-component-tester/browser.js"></script>
</head>
<body>
  <script>
    WCT.loadSuites([
      'app-scroll-effects-behavior.html?dom=shadow',
      'waterfall.html?dom=shadow',
      'resize-title.html?dom=shadow',
      'resize-snapped-title.html?dom=shadow',
      'parallax-background.html?dom=shadow',
      'blend-background.html?dom=shadow',
      'fade-background.html?dom=shadow',
      'app-scroll-effects-behavior.html?wc-shadydom=true&wc-ce=true',
      'waterfall.html?wc-shadydom=true&wc-ce=true',
      'resize-title.html?wc-shadydom=true&wc-ce=true',
      'resize-snapped-title.html?wc-shadydom=true&wc-ce=true',
      'parallax-background.html?wc-shadydom=true&wc-ce=true',
      'blend-background.html?wc-shadydom=true&wc-ce=true',
      'fade-background.html?wc-shadydom=true&wc-ce=true'
    ]);
  </script>
</body>
</html>


text:
import { ILuTranslation } from '@lucca-front/ng/core';

export interface ILuUserSelectInputLabel {
	users: string;
	me: string;
}
export abstract class ALuUserSelectInputLabel {
	users: string;
	me: string;
}

export const luUserSelectInputTranslations: ILuTranslation<ILuUserSelectInputLabel> = {
	en: {
		users: 'users',
		me: 'Me:',
	},
	fr: {
		users: 'utilisateurs',
		me: 'Moi :',
	},
	es: {
		users: 'empleados',
		me: 'Yo :',
	},
};


text:
package io.cdap.plugin.pubsub.runners.sinkrunner;

import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;

/**
 * Test Runner to execute PubSub sink cases.
 */
@RunWith(Cucumber.class)
@CucumberOptions(
  features = {"src/e2e-test/features"},
  glue = {"io.cdap.plugin.pubsub.stepsdesign", "io.cdap.plugin.gcs.stepsdesign",
    "io.cdap.plugin.common.stepsdesign", "io.cdap.plugin.bigquery.stepsdesign", "stepsdesign"},
  tags = {"@PubSub_Sink"},
  monochrome = true,
  plugin = {"pretty", "html:target/cucumber-html-report/pubsub-sink",
    "json:target/cucumber-reports/cucumber-pubsub-sink.json",
    "junit:target/cucumber-reports/cucumber-pubsub-sink.xml"}
)

public class TestRunner {
}


text:
package com.ericsson.jigsaw.redis.embedded;

import redis.clients.util.SafeEncoder;
import ch.lambdaj.function.convert.Converter;

public class DoubleToStringByteArrayConverter implements Converter<Double, byte[]> {

	public static DoubleToStringByteArrayConverter createDoubleToStringByteArrayConverter() {
		return new DoubleToStringByteArrayConverter();
	}

	@Override
	public byte[] convert(Double from) {
		String doubleValue = Double.toString(from);
		return SafeEncoder.encode(doubleValue);
	}

}


text:
package cromwell

import akka.testkit._
import cromwell.CromwellSpec.DockerTest
import wdl4s.types.{WdlArrayType, WdlStringType, WdlFileType}
import wdl4s.{WorkflowInput, NamespaceWithWorkflow}
import wdl4s.values.{WdlArray, WdlInteger, WdlString}
import cromwell.engine.backend.BackendType
import cromwell.util.SampleWdl

import scala.language.postfixOps

class WriteLinesSpec extends CromwellTestkitSpec {
  val outputs = Map(
    "write_lines.a2f.out" -> WdlArray(WdlArrayType(WdlStringType), Seq("a", "b", "c", "d").map(WdlString))
  )

  "A task that calls write_lines() in the command section" should {
    "run properly" in {
      runWdlAndAssertOutputs(
        sampleWdl = SampleWdl.WriteLinesWorkflow,
        eventFilter = EventFilter.info(pattern = s"starting calls: write_lines.a2f", occurrences = 1),
        expectedOutputs = outputs
      )
    }
    "run properly in a Docker environment" taggedAs DockerTest in {
      runWdlAndAssertOutputs(
        sampleWdl = SampleWdl.WriteLinesWorkflow,
        eventFilter = EventFilter.info(pattern = s"starting calls: write_lines.a2f", occurrences = 1),
        runtime =
          """runtime {
            |  docker: "ubuntu:latest"
            |}
          """.stripMargin,
        expectedOutputs = outputs
      )
    }
  }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <title>{{ isset($page_title) && !!$page_title ? $page_title . ' - ' : '' }}TWHL: Half-Life and Source Mapping Tutorials and Resources</title>

        <meta content="The Whole Half-Life" property="og:site_name">
        @if (isset($meta_description) && strlen($meta_description) > 0)
            <?php $meta_description = str_replace("\n", ' ', substr($meta_description, 0, 300)) . (strlen($meta_description) > 300 ? '...' : ''); ?>
            <meta property="og:description" content="{{$meta_description}}">
        @else
            <meta property="og:description" content="View this page on TWHL">
        @endif
        <meta property="og:type" content="website">
        @if (isset($meta_title) && strlen($meta_title) > 0)
            <meta property="og:title" content="{{$meta_title}}">
        @else
            <meta property="og:title" content="{{$page_title}}">
        @endif
        @if (isset($meta_images) && count($meta_images) > 0)
            @foreach ($meta_images as $img)
                <meta property="og:image" content="{{asset($img)}}">
            @endforeach
            <meta name="twitter:card" content="summary_large_image">
        @else
            <meta property="og:image" content="{{asset('images/twhl-logo.png')}}">
        @endif
        <meta property="og:url" content="{{Request::url()}}">
        <meta name="theme-color" content="#e68a27">

        <link href="{{ mix('/css/app.css') }}?sl" rel="stylesheet">
        <link rel="shortcut icon" href="{{ asset('favicon.ico') }}" />

        @yield('styles', '')

        <link href='//fonts.googleapis.com/css?family=Roboto:400,300' rel='stylesheet' type='text/css'>

    @include('nav')

    @if (!app()->environment('production'))

                This is the public beta version of TWHL and any content posted here will be deleted once the database is refreshed.
                Please go to twhl.info if you are looking for resources or information.

    @endif

        @include('nav-desktop')
	    @yield('content')

        Site and non-dynamic content copyright © {{\Carbon\Carbon::now()->year}}, Logic & Trick. Original site by atom. All rights reserved.

        All member-submitted resources copyright their respective authors unless otherwise specified.

        TWHL is a fan site and is not affiliated with Valve Corporation. Views expressed by users are the individuals's own and do not represent the opinions of any other entity.

        {{ render_time() }}

    @if (app('config')->get('app.debug'))

                        Query
                        Parameters
                        Time

                {? $debug_query_total = 0; $debug_query_count = 0; ?}
                @foreach (DB::getQueryLog() as $query)
                    {? $debug_query_total += $query['time']; $debug_query_count++; ?}

                        {{ $query['query'] }}
                        {{ print_r($query['bindings'], true) }}
                        {{ $query['time'] }}ms

                @endforeach

                    Total
                    {{ $debug_query_count }} queries
                    {{ $debug_query_total }}ms

    @endif

    @yield('scripts', '')


text:
package test;

import generators.JPAClassGenerator;
import generators.JPAResourceClassGenerator;
import generators.SQLGenerator;

import java.util.Arrays;

import model.JPAClassModel;
import model.JPAResourceClassModel;
import model.SQLData;

public class Test {

	private static SQLData createSQLData() {
		SQLData data = new SQLData();
		data.setTableName("COMMUNITY_USER");
		data.getFieldData().put("GATEWAY_NAME", Arrays.asList(new String[]{"VARCHAR", "256", "NOT", "NULL"}));
		data.getFieldData().put("COMMUNITY_USER_NAME", Arrays.asList(new String[]{"VARCHAR", "256", "NOT", "NULL"}));
		data.getFieldData().put("TOKEN_ID", Arrays.asList(new String[]{"VARCHAR", "256", "NOT", "NULL"}));
		data.getFieldData().put("COMMUNITY_USER_EMAIL", Arrays.asList(new String[]{"VARCHAR", "256", "NOT", "NULL"}));
		data.getFieldData().put("CREATION_TIME", Arrays.asList(new String[]{"TIMESTAMP", "DEFAULT", "NOW()"}));
		data.getFieldData().put("CPU_COUNT", Arrays.asList(new String[]{"INTEGER"}));
		data.getPrimaryKeys().add("GATEWAY_NAME");
		data.getPrimaryKeys().add("COMMUNITY_USER_NAME");
		data.getPrimaryKeys().add("TOKEN_ID");
		data.getForiegnKeys().put("EXPERIMENT_ID", new SQLData.ForiegnKeyData("EXPERIMENT(EXPERIMENT_ID)","Experiment","ExperimentResource"));
		return data;
	}
	public static void testSqlGen() {
		SQLData data = createSQLData();
		SQLGenerator sqlGenerator = new SQLGenerator();
		System.out.println(sqlGenerator.generateSQLCreateQuery(data));
	}

	public static void testJPAClassGen() {
		SQLData data = createSQLData();
		JPAClassGenerator jpaClassGenerator = new JPAClassGenerator();
		JPAClassModel model = jpaClassGenerator.createJPAClassModel(data);
		System.out.println(jpaClassGenerator.generateJPAClass(model));
		System.out.println(jpaClassGenerator.generateJPAPKClass(model.pkClassModel));
	}

	public static void testJPAResourceClassGen() {
		SQLData data = createSQLData();
		JPAClassGenerator jpaClassGenerator = new JPAClassGenerator();
		JPAClassModel model = jpaClassGenerator.createJPAClassModel(data);
		JPAResourceClassGenerator jpaResourceClassGenerator = new JPAResourceClassGenerator();
		JPAResourceClassModel model2 = jpaResourceClassGenerator.createJPAResourceClassModel(model);
		System.out.println(jpaResourceClassGenerator.generateJPAResourceClass(model2));
		System.out.println(jpaResourceClassGenerator.generateAbstractResourceClassUpdates(model2));
		System.out.println(jpaResourceClassGenerator.generateAppCatalogResourceTypeUpdates(model2));
		System.out.println(jpaResourceClassGenerator.generateAppCatalogJPAUtilUpdates(model2));

	}
	public static void main(String[] args) {
		testJPAResourceClassGen();
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/list_item_forecast_textview"
        android:paddingTop="20dp"
        android:paddingBottom="20dp" />
</LinearLayout>


text:
package com.alanbuttars.commons.compress.stub.decompress;

import static com.alanbuttars.commons.compress.files.util.CompressedFiles.PACK200;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.compress.compressors.pack200.Pack200Strategy;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;

/**
 * Test class for {@link DecompressCompressedFileWithStubPack200Impl}.
 *
 * @author Alan Buttars
 *
 */
@RunWith(PowerMockRunner.class)
public class DecompressCompressedFileWithStubPack200ImplTest {

	private File source;
	private File destination;
	private DecompressCompressedFileWithStubPack200Impl stub;

	@Before
	public void setup() throws IOException {
		source = File.createTempFile(getClass().getName(), ".tmp");
		destination = File.createTempFile(getClass().getName(), ".tmp");
		stub = spy(new DecompressCompressedFileWithStubPack200Impl(source));
	}

	@After
	public void teardown() {
		source.deleteOnExit();
		destination.deleteOnExit();
	}

	@Test
	public void testConstructor() {
		assertEquals(source, stub.source);
		assertEquals(PACK200, stub.fileType);
	}

	@Test(expected = IOException.class)
	public void testCompressionFunction() throws IOException {
		stub.to(destination);
		verify(stub, times(1)).createCompressedFileInputStream(any(InputStream.class), eq(Pack200Strategy.IN_MEMORY), isNull(Map.class));
	}

	@Test(expected = IOException.class)
	public void testCustomCompressionFunction() throws IOException {
		Map<String, String> properties = new HashMap<String, String>();
		stub.andMode(Pack200Strategy.TEMP_FILE).andProperties(properties).to(destination);
		verify(stub, times(1)).createCompressedFileInputStream(any(InputStream.class), eq(Pack200Strategy.TEMP_FILE), eq(properties));
	}
}


text:
<!DOCTYPE html>
<title>TextEdit demo in CanvasKit</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

TextEdit in CanvasKit

  <canvas id=para2 width=600 height=600 tabindex='-1'></canvas>