text:
package net

import (
	"context"
	"errors"
	"io"
	"math/rand"
	"os"
	"sync"
	"time"
)

// A dnsConn represents a DNS transport endpoint.
type dnsConn interface {
	io.Closer

	SetDeadline(time.Time) error

	// dnsRoundTrip executes a single DNS transaction, returning a
	// DNS response message for the provided DNS query message.
	dnsRoundTrip(query *dnsMsg) (*dnsMsg, error)
}

// dnsPacketConn implements the dnsConn interface for RFC 1035's
// "UDP usage" transport mechanism. Conn is a packet-oriented connection,
// such as a *UDPConn.
type dnsPacketConn struct {
	Conn
}

func (c *dnsPacketConn) dnsRoundTrip(query *dnsMsg) (*dnsMsg, error) {
	b, ok := query.Pack()
	if !ok {
		return nil, errors.New("cannot marshal DNS message")
	}
	if _, err := c.Write(b); err != nil {
		return nil, err
	}

	b = make([]byte, 512) // see RFC 1035
	for {
		n, err := c.Read(b)
		if err != nil {
			return nil, err
		}
		resp := &dnsMsg{}
		if !resp.Unpack(b[:n]) || !resp.IsResponseTo(query) {
			// Ignore invalid responses as they may be malicious
			// forgery attempts. Instead continue waiting until
			// timeout. See golang.org/issue/13281.
			continue
		}
		return resp, nil
	}
}

// dnsStreamConn implements the dnsConn interface for RFC 1035's
// "TCP usage" transport mechanism. Conn is a stream-oriented connection,
// such as a *TCPConn.
type dnsStreamConn struct {
	Conn
}

func (c *dnsStreamConn) dnsRoundTrip(query *dnsMsg) (*dnsMsg, error) {
	b, ok := query.Pack()
	if !ok {
		return nil, errors.New("cannot marshal DNS message")
	}
	l := len(b)
	b = append([]byte{byte(l >> 8), byte(l)}, b...)
	if _, err := c.Write(b); err != nil {
		return nil, err
	}

	b = make([]byte, 1280) // 1280 is a reasonable initial size for IP over Ethernet, see RFC 4035
	if _, err := io.ReadFull(c, b[:2]); err != nil {
		return nil, err
	}
	l = int(b[0])<<8 | int(b[1])
	if l > len(b) {
		b = make([]byte, l)
	}
	n, err := io.ReadFull(c, b[:l])
	if err != nil {
		return nil, err
	}
	resp := &dnsMsg{}
	if !resp.Unpack(b[:n]) {
		return nil, errors.New("cannot unmarshal DNS message")
	}
	if !resp.IsResponseTo(query) {
		return nil, errors.New("invalid DNS response")
	}
	return resp, nil
}

// exchange sends a query on the connection and hopes for a response.
func (r *Resolver) exchange(ctx context.Context, server, name string, qtype uint16, timeout time.Duration) (*dnsMsg, error) {
	out := dnsMsg{
		dnsMsgHdr: dnsMsgHdr{
			recursion_desired: true,
		},
		question: []dnsQuestion{
			{name, qtype, dnsClassINET},
		},
	}
	for _, network := range []string{"udp", "tcp"} {
		// TODO(mdempsky): Refactor so defers from UDP-based
		// exchanges happen before TCP-based exchange.

		ctx, cancel := context.WithDeadline(ctx, time.Now().Add(timeout))
		defer cancel()

		c, err := r.dial(ctx, network, server)
		if err != nil {
			return nil, err
		}
		defer c.Close()
		if d, ok := ctx.Deadline(); ok && !d.IsZero() {
			c.SetDeadline(d)
		}
		out.id = uint16(rand.Int()) ^ uint16(time.Now().UnixNano())
		in, err := c.dnsRoundTrip(&out)
		if err != nil {
			return nil, mapErr(err)
		}
		if in.truncated { // see RFC 5966
			continue
		}
		return in, nil
	}
	return nil, errors.New("no answer from DNS server")
}

// Do a lookup for a single name, which must be rooted
// (otherwise answer will not find the answers).
func (r *Resolver) tryOneName(ctx context.Context, cfg *dnsConfig, name string, qtype uint16) (string, []dnsRR, error) {
	var lastErr error
	serverOffset := cfg.serverOffset()
	sLen := uint32(len(cfg.servers))

	for i := 0; i < cfg.attempts; i++ {
		for j := uint32(0); j < sLen; j++ {
			server := cfg.servers[(serverOffset+j)%sLen]

			msg, err := r.exchange(ctx, server, name, qtype, cfg.timeout)
			if err != nil {
				lastErr = &DNSError{
					Err:    err.Error(),
					Name:   name,
					Server: server,
				}
				if nerr, ok := err.(Error); ok && nerr.Timeout() {
					lastErr.(*DNSError).IsTimeout = true
				}
				// Set IsTemporary for socket-level errors. Note that this flag
				// may also be used to indicate a SERVFAIL response.
				if _, ok := err.(*OpError); ok {
					lastErr.(*DNSError).IsTemporary = true
				}
				continue
			}
			// libresolv continues to the next server when it receives
			// an invalid referral response. See golang.org/issue/15434.
			if msg.rcode == dnsRcodeSuccess && !msg.authoritative && !msg.recursion_available && len(msg.answer) == 0 && len(msg.extra) == 0 {
				lastErr = &DNSError{Err: "lame referral", Name: name, Server: server}
				continue
			}
			cname, rrs, err := answer(name, server, msg, qtype)
			// If answer errored for rcodes dnsRcodeSuccess or dnsRcodeNameError,
			// it means the response in msg was not useful and trying another
			// server probably won't help. Return now in those cases.
			// TODO: indicate this in a more obvious way, such as a field on DNSError?
			if err == nil || msg.rcode == dnsRcodeSuccess || msg.rcode == dnsRcodeNameError {
				return cname, rrs, err
			}
			lastErr = err
		}
	}
	return "", nil, lastErr
}

// addrRecordList converts and returns a list of IP addresses from DNS
// address records (both A and AAAA). Other record types are ignored.
func addrRecordList(rrs []dnsRR) []IPAddr {
	addrs := make([]IPAddr, 0, 4)
	for _, rr := range rrs {
		switch rr := rr.(type) {
		case *dnsRR_A:
			addrs = append(addrs, IPAddr{IP: IPv4(byte(rr.A>>24), byte(rr.A>>16), byte(rr.A>>8), byte(rr.A))})
		case *dnsRR_AAAA:
			ip := make(IP, IPv6len)
			copy(ip, rr.AAAA[:])
			addrs = append(addrs, IPAddr{IP: ip})
		}
	}
	return addrs
}

// A resolverConfig represents a DNS stub resolver configuration.
type resolverConfig struct {
	initOnce sync.Once // guards init of resolverConfig

	// ch is used as a semaphore that only allows one lookup at a
	// time to recheck resolv.conf.
	ch          chan struct{} // guards lastChecked and modTime
	lastChecked time.Time     // last time resolv.conf was checked

	mu        sync.RWMutex // protects dnsConfig
	dnsConfig *dnsConfig   // parsed resolv.conf structure used in lookups
}

var resolvConf resolverConfig

// init initializes conf and is only called via conf.initOnce.
func (conf *resolverConfig) init() {
	// Set dnsConfig and lastChecked so we don't parse
	// resolv.conf twice the first time.
	conf.dnsConfig = systemConf().resolv
	if conf.dnsConfig == nil {
		conf.dnsConfig = dnsReadConfig("/etc/resolv.conf")
	}
	conf.lastChecked = time.Now()

	// Prepare ch so that only one update of resolverConfig may
	// run at once.
	conf.ch = make(chan struct{}, 1)
}

// tryUpdate tries to update conf with the named resolv.conf file.
// The name variable only exists for testing. It is otherwise always
// "/etc/resolv.conf".
func (conf *resolverConfig) tryUpdate(name string) {
	conf.initOnce.Do(conf.init)

	// Ensure only one update at a time checks resolv.conf.
	if !conf.tryAcquireSema() {
		return
	}
	defer conf.releaseSema()

	now := time.Now()
	if conf.lastChecked.After(now.Add(-5 * time.Second)) {
		return
	}
	conf.lastChecked = now

	var mtime time.Time
	if fi, err := os.Stat(name); err == nil {
		mtime = fi.ModTime()
	}
	if mtime.Equal(conf.dnsConfig.mtime) {
		return
	}

	dnsConf := dnsReadConfig(name)
	conf.mu.Lock()
	conf.dnsConfig = dnsConf
	conf.mu.Unlock()
}

func (conf *resolverConfig) tryAcquireSema() bool {
	select {
	case conf.ch <- struct{}{}:
		return true
	default:
		return false
	}
}

func (conf *resolverConfig) releaseSema() {
	<-conf.ch
}

func (r *Resolver) lookup(ctx context.Context, name string, qtype uint16) (cname string, rrs []dnsRR, err error) {
	if !isDomainName(name) {
		// We used to use "invalid domain name" as the error,
		// but that is a detail of the specific lookup mechanism.
		// Other lookups might allow broader name syntax
		// (for example Multicast DNS allows UTF-8; see RFC 6762).
		// For consistency with libc resolvers, report no such host.
		return "", nil, &DNSError{Err: errNoSuchHost.Error(), Name: name}
	}
	resolvConf.tryUpdate("/etc/resolv.conf")
	resolvConf.mu.RLock()
	conf := resolvConf.dnsConfig
	resolvConf.mu.RUnlock()
	for _, fqdn := range conf.nameList(name) {
		cname, rrs, err = r.tryOneName(ctx, conf, fqdn, qtype)
		if err == nil {
			break
		}
		if nerr, ok := err.(Error); ok && nerr.Temporary() && r.StrictErrors {
			// If we hit a temporary error with StrictErrors enabled,
			// stop immediately instead of trying more names.
			break
		}
	}
	if err, ok := err.(*DNSError); ok {
		// Show original name passed to lookup, not suffixed one.
		// In general we might have tried many suffixes; showing
		// just one is misleading. See also golang.org/issue/6324.
		err.Name = name
	}
	return
}

// avoidDNS reports whether this is a hostname for which we should not
// use DNS. Currently this includes only .onion, per RFC 7686. See
// golang.org/issue/13705. Does not cover .local names (RFC 6762),
// see golang.org/issue/16739.
func avoidDNS(name string) bool {
	if name == "" {
		return true
	}
	if name[len(name)-1] == '.' {
		name = name[:len(name)-1]
	}
	return stringsHasSuffixFold(name, ".onion")
}

// nameList returns a list of names for sequential DNS queries.
func (conf *dnsConfig) nameList(name string) []string {
	if avoidDNS(name) {
		return nil
	}

	// Check name length (see isDomainName).
	l := len(name)
	rooted := l > 0 && name[l-1] == '.'
	if l > 254 || l == 254 && rooted {
		return nil
	}

	// If name is rooted (trailing dot), try only that name.
	if rooted {
		return []string{name}
	}

	hasNdots := count(name, '.') >= conf.ndots
	name += "."
	l++

	// Build list of search choices.
	names := make([]string, 0, 1+len(conf.search))
	// If name has enough dots, try unsuffixed first.
	if hasNdots {
		names = append(names, name)
	}
	// Try suffixes that are not too long (see isDomainName).
	for _, suffix := range conf.search {
		if l+len(suffix) <= 254 {
			names = append(names, name+suffix)
		}
	}
	// Try unsuffixed, if not tried first above.
	if !hasNdots {
		names = append(names, name)
	}
	return names
}

// hostLookupOrder specifies the order of LookupHost lookup strategies.
// It is basically a simplified representation of nsswitch.conf.
// "files" means /etc/hosts.
type hostLookupOrder int

const (
	// hostLookupCgo means defer to cgo.
	hostLookupCgo      hostLookupOrder = iota
	hostLookupFilesDNS                 // files first
	hostLookupDNSFiles                 // dns first
	hostLookupFiles                    // only files
	hostLookupDNS                      // only DNS
)

var lookupOrderName = map[hostLookupOrder]string{
	hostLookupCgo:      "cgo",
	hostLookupFilesDNS: "files,dns",
	hostLookupDNSFiles: "dns,files",
	hostLookupFiles:    "files",
	hostLookupDNS:      "dns",
}

func (o hostLookupOrder) String() string {
	if s, ok := lookupOrderName[o]; ok {
		return s
	}
	return "hostLookupOrder=" + itoa(int(o)) + "??"
}

// goLookupHost is the native Go implementation of LookupHost.
// Used only if cgoLookupHost refuses to handle the request
// (that is, only if cgoLookupHost is the stub in cgo_stub.go).
// Normally we let cgo use the C library resolver instead of
// depending on our lookup code, so that Go and C get the same
// answers.
func (r *Resolver) goLookupHost(ctx context.Context, name string) (addrs []string, err error) {
	return r.goLookupHostOrder(ctx, name, hostLookupFilesDNS)
}

func (r *Resolver) goLookupHostOrder(ctx context.Context, name string, order hostLookupOrder) (addrs []string, err error) {
	if order == hostLookupFilesDNS || order == hostLookupFiles {
		// Use entries from /etc/hosts if they match.
		addrs = lookupStaticHost(name)
		if len(addrs) > 0 || order == hostLookupFiles {
			return
		}
	}
	ips, _, err := r.goLookupIPCNAMEOrder(ctx, name, order)
	if err != nil {
		return
	}
	addrs = make([]string, 0, len(ips))
	for _, ip := range ips {
		addrs = append(addrs, ip.String())
	}
	return
}

// lookup entries from /etc/hosts
func goLookupIPFiles(name string) (addrs []IPAddr) {
	for _, haddr := range lookupStaticHost(name) {
		haddr, zone := splitHostZone(haddr)
		if ip := ParseIP(haddr); ip != nil {
			addr := IPAddr{IP: ip, Zone: zone}
			addrs = append(addrs, addr)
		}
	}
	sortByRFC6724(addrs)
	return
}

// goLookupIP is the native Go implementation of LookupIP.
// The libc versions are in cgo_*.go.
func (r *Resolver) goLookupIP(ctx context.Context, host string) (addrs []IPAddr, err error) {
	order := systemConf().hostLookupOrder(host)
	addrs, _, err = r.goLookupIPCNAMEOrder(ctx, host, order)
	return
}

func (r *Resolver) goLookupIPCNAMEOrder(ctx context.Context, name string, order hostLookupOrder) (addrs []IPAddr, cname string, err error) {
	if order == hostLookupFilesDNS || order == hostLookupFiles {
		addrs = goLookupIPFiles(name)
		if len(addrs) > 0 || order == hostLookupFiles {
			return addrs, name, nil
		}
	}
	if !isDomainName(name) {
		// See comment in func lookup above about use of errNoSuchHost.
		return nil, "", &DNSError{Err: errNoSuchHost.Error(), Name: name}
	}
	resolvConf.tryUpdate("/etc/resolv.conf")
	resolvConf.mu.RLock()
	conf := resolvConf.dnsConfig
	resolvConf.mu.RUnlock()
	type racer struct {
		cname string
		rrs   []dnsRR
		error
	}
	lane := make(chan racer, 1)
	qtypes := [...]uint16{dnsTypeA, dnsTypeAAAA}
	var lastErr error
	for _, fqdn := range conf.nameList(name) {
		for _, qtype := range qtypes {
			go func(qtype uint16) {
				cname, rrs, err := r.tryOneName(ctx, conf, fqdn, qtype)
				lane <- racer{cname, rrs, err}
			}(qtype)
		}
		hitStrictError := false
		for range qtypes {
			racer := <-lane
			if racer.error != nil {
				if nerr, ok := racer.error.(Error); ok && nerr.Temporary() && r.StrictErrors {
					// This error will abort the nameList loop.
					hitStrictError = true
					lastErr = racer.error
				} else if lastErr == nil || fqdn == name+"." {
					// Prefer error for original name.
					lastErr = racer.error
				}
				continue
			}
			addrs = append(addrs, addrRecordList(racer.rrs)...)
			if cname == "" {
				cname = racer.cname
			}
		}
		if hitStrictError {
			// If either family hit an error with StrictErrors enabled,
			// discard all addresses. This ensures that network flakiness
			// cannot turn a dualstack hostname IPv4/IPv6-only.
			addrs = nil
			break
		}
		if len(addrs) > 0 {
			break
		}
	}
	if lastErr, ok := lastErr.(*DNSError); ok {
		// Show original name passed to lookup, not suffixed one.
		// In general we might have tried many suffixes; showing
		// just one is misleading. See also golang.org/issue/6324.
		lastErr.Name = name
	}
	sortByRFC6724(addrs)
	if len(addrs) == 0 {
		if order == hostLookupDNSFiles {
			addrs = goLookupIPFiles(name)
		}
		if len(addrs) == 0 && lastErr != nil {
			return nil, "", lastErr
		}
	}
	return addrs, cname, nil
}

// goLookupCNAME is the native Go (non-cgo) implementation of LookupCNAME.
func (r *Resolver) goLookupCNAME(ctx context.Context, host string) (cname string, err error) {
	order := systemConf().hostLookupOrder(host)
	_, cname, err = r.goLookupIPCNAMEOrder(ctx, host, order)
	return
}

// goLookupPTR is the native Go implementation of LookupAddr.
// Used only if cgoLookupPTR refuses to handle the request (that is,
// only if cgoLookupPTR is the stub in cgo_stub.go).
// Normally we let cgo use the C library resolver instead of depending
// on our lookup code, so that Go and C get the same answers.
func (r *Resolver) goLookupPTR(ctx context.Context, addr string) ([]string, error) {
	names := lookupStaticAddr(addr)
	if len(names) > 0 {
		return names, nil
	}
	arpa, err := reverseaddr(addr)
	if err != nil {
		return nil, err
	}
	_, rrs, err := r.lookup(ctx, arpa, dnsTypePTR)
	if err != nil {
		return nil, err
	}
	ptrs := make([]string, len(rrs))
	for i, rr := range rrs {
		ptrs[i] = rr.(*dnsRR_PTR).Ptr
	}
	return ptrs, nil
}


text:
import fs = require("fs");
import glob = require("glob");
import minimatch = require("minimatch");
import path = require("path");

export interface WriteStream extends fs.WriteStream {

}

export let createWriteStream = fs.createWriteStream;

export async function readdir(path_: string | Buffer): Promise<string[]> {
	return new Promise<string[]>((resolve, reject) => {
		fs.readdir(path_, (err, files) => {
			if (err) {
				reject(err);
			} else {
				resolve(files);
			}
		});
	});
}

export async function stat(path_: string | Buffer): Promise<fs.Stats> {
	return new Promise<any>((resolve, reject) => {
		fs.stat(path_, (err, stats) => {
			if (err) {
				reject(err);
			} else {
				resolve(stats);
			}
		});
	});
}

export async function mkdir(file: string | Buffer): Promise<any> {
	return new Promise<any>((resolve, reject) => {
		fs.mkdir(file, (err) => {
			if (err) {
				reject(err);
				return;
			}
			resolve();
		});
	});
}

export async function rmdir(file: string | Buffer): Promise<any> {
	return new Promise<any>((resolve, reject) => {
		fs.rmdir(file, (err) => {
			if (err) {
				reject(err);
			} else {
				resolve();
			}
		});
	});
}

export async function exists(file: string | Buffer): Promise<boolean> {
	return new Promise<boolean>((resolve, reject) => {
		fs.exists(file, (exists_) => {
			resolve(exists_);
		});
	});
}

export async function readFile(filename: string, encoding: string | null): Promise<string | Buffer> {
	return new Promise<any>((resolve, reject) => {
		fs.readFile(filename, encoding, (err, data) => {
			if (err) {
				reject(err);
			} else {
				resolve(data);
			}
		});
	});
}

export async function writeFile(filename: string, encoding: string, data: any): Promise<void> {
	return new Promise<void>((resolve, reject) => {
		fs.writeFile(filename, data, { encoding }, (err) => {
			if (err) {
				reject(err);
			} else {
				resolve();
			}
		});
	});
}

export async function mkdtemp(prefix: string): Promise<string> {
	return new Promise<string>((resolve, reject) => {
		fs.mkdtemp(prefix, (err, folder) => {
			if (err) {
				reject(err);
			} else {
				resolve(folder);
			}
		});
	});
}

export async function unlink(path_: string | Buffer): Promise<void> {
	return new Promise<void>((resolve, reject) => {
		fs.unlink(path_, (err) => {
			if (err) {
				reject(err);
			} else {
				resolve();
			}
		});
	});
}

export function normalize_path(filepath: string): string {
	if (process.platform === "win32") {
		return filepath.split(/\/|\\/).join("\\");
	} else {
		return filepath.split(/\/|\\/).join("/");
	}
}

function path_join(base: string, file_path: string): string {
	const nbase = normalize_path(base);
	const nfp = normalize_path(file_path);
	if (nbase.endsWith("/") || nbase.endsWith("\\")) {
		return nbase + nfp;
	} else {
		return nbase + normalize_path("/") + nfp;
	}
}

export async function find_all_files(base_path: string, level?: number): Promise<string[]> {
	let all_files: string[] = [];
	const items = await readdir(base_path);

	for (const item of items) {
		const full_path = path_join(base_path, item);
		const stat_ = await stat(full_path);
		if (stat_.isDirectory()) {
			if (level < 10 || !level) {
				const files = await find_all_files(full_path, (level || 0) + 1);
				all_files = all_files.concat(files);
			}
		} else {
			all_files.push(full_path);
		}

	}
	return all_files;
}

export async function filter_glob(pattern: string, files: string[]): Promise<string[]> {
	const retfiles = files.filter((v, i, a) => {
		return !minimatch.filter(path.normalize(normalize_path(pattern)), { dot: true })(path.normalize(normalize_path(v)), i, a);
	});
	return retfiles;
}

// http://stackoverflow.com/questions/10420352/converting-file-size-in-bytes-to-human-readable
export function human_file_size(bytes: number, si?: boolean): string {
	const thresh = si ? 1000 : 1024;
	if (Math.abs(bytes) < thresh) {
		return bytes + " B";
	}
	const units = si
		? ["kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
		: ["KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"];
	let u = -1;
	do {
		bytes /= thresh;
		++u;
	} while (Math.abs(bytes) >= thresh && u < units.length - 1);
	return bytes.toFixed(1) + " " + units[u];
}

export async function list_folder_by_pattern(pattern: string): Promise<string[]> {
	return new Promise<string[]>((resolve, reject) => {
		glob(pattern, {}, (er, files) => {
			if (er) {
				reject(er);
				return;
			}
			resolve(files);
		});
	});
}

export async function list_folder(patterns: string[]): Promise<string[]> {
	let files: string[] = [];
	for (const pattern of patterns) {
		files = files.concat(await list_folder_by_pattern(pattern));
	}
	return files;
}

redpajama_set_name: RedPajamaGithub


text:
package com.google.gwt.resources.converter;

import com.google.gwt.core.ext.UnableToCompleteException;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

/**
 * Integration tests for Css2Gss
 */
public class Css2GssTest {

  @Test
  public void testInlineBlockCssEscaping() throws Exception {
    assertFileContentEqualsAfterConversion("inline-block.css", "inline-block.gss");
  }

  @Test
  public void testMultipleDeclarationOfSameProperty() throws Exception {
    assertFileContentEqualsAfterConversion("multiple_declarations.css",
        "multiple_declarations.gss");
  }

  @Test
  public void testCssConditional() throws Exception {
    assertFileContentEqualsAfterConversion("conditional.css", "conditional.gss");
  }

  @Test
  public void testLenientFlag() throws Exception {
    assertFileContentEqualsAfterConversion("badRule.css", "badRule.gss", true);
  }

  @Test
  public void testSprite() throws Exception {
    assertFileContentEqualsAfterConversion("sprite.css", "sprite.gss");
  }

  @Test
  public void testFontFamily() throws Exception {
    assertFileContentEqualsAfterConversion("font-bug.css", "font-bug.gss");
  }

  @Test
  public void testExternalBug() throws Exception {
    assertFileContentEqualsAfterConversion("external-bug.css", "external-bug.gss", true);
  }

  @Test
  public void testUndefinedConstant() throws Exception {
    assertFileContentEqualsAfterConversion(
        "undefined-constants.css", "undefined-constants.gss", true);
  }

  @Test
  public void testRemoveExternalEscaping() throws Exception {
    assertFileContentEqualsAfterConversion(
        "external-escaping.css", "external-escaping.gss");
  }

  @Test
  public void testNestedConditional() throws Exception {
    assertFileContentEqualsAfterConversion(
        "nestedElseIf.css", "nestedElseIf.gss");
  }

  @Test
  public void testConstants() throws Exception {
    assertFileContentEqualsAfterConversion(
        "constants.css", "constants.gss", true);
  }

  @Test
  public void testInvalidConstantName() throws IOException, UnableToCompleteException {
    assertFileContentEqualsAfterConversion(
        "invalidConstantName.css", "invalidConstantName.gss", true);
  }

  private void assertFileContentEqualsAfterConversion(String inputCssFile, String expectedGssFile)
      throws IOException, UnableToCompleteException {
    assertFileContentEqualsAfterConversion(inputCssFile, expectedGssFile, false);
  }

  private void assertFileContentEqualsAfterConversion(String inputCssFile,
      String expectedGssFile, boolean lenient) throws IOException, UnableToCompleteException {
    URL resource = Css2GssTest.class.getResource(inputCssFile);
    InputStream stream = Css2GssTest.class.getResourceAsStream(expectedGssFile);
    String convertedGss = new Css2Gss(resource, lenient).toGss();
    String gss = IOUtils.toString(stream, "UTF-8");
    Assert.assertEquals(gss, convertedGss);
  }
}


text:
package io.getlime.security.powerauth.app.nextstep.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * Default Spring Security configuration.
 *
 * @author Petr Dvorak, petr@wultra.com
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    /**
     * Configures HTTP security.
     * @param http HTTP security.
     * @throws Exception Thrown when configuration fails.
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().disable();
        http.csrf().disable();
    }

}


text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.skyframe;

import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.pkgcache.TransitivePackageLoader;
import com.google.devtools.build.lib.skyframe.SkyframeExecutor.SkyframeTransitivePackageLoader;
import com.google.devtools.build.skyframe.CyclesReporter;
import com.google.devtools.build.skyframe.ErrorInfo;
import com.google.devtools.build.skyframe.EvaluationResult;
import com.google.devtools.build.skyframe.SkyKey;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
import javax.annotation.Nullable;

/**
 * Skyframe-based transitive package loader.
 */
final class SkyframeLabelVisitor implements TransitivePackageLoader {

  private final SkyframeTransitivePackageLoader transitivePackageLoader;
  private final AtomicReference<CyclesReporter> skyframeCyclesReporter;

  SkyframeLabelVisitor(SkyframeTransitivePackageLoader transitivePackageLoader,
      AtomicReference<CyclesReporter> skyframeCyclesReporter) {
    this.transitivePackageLoader = transitivePackageLoader;
    this.skyframeCyclesReporter = skyframeCyclesReporter;
  }

  // The only remaining non-test caller of this code is BlazeQueryEnvironment.
  @Override
  public boolean sync(
      ExtendedEventHandler eventHandler,
      Set<Label> labelsToVisit,
      boolean keepGoing,
      int parallelThreads)
      throws InterruptedException {
    EvaluationResult<TransitiveTargetValue> result = transitivePackageLoader.loadTransitiveTargets(
        eventHandler, labelsToVisit, keepGoing, parallelThreads);

    if (!hasErrors(result)) {
      return true;
    }

    Set<Entry<SkyKey, ErrorInfo>> errors = result.errorMap().entrySet();
    if (!keepGoing) {
      // We may have multiple errors, but in non keep_going builds, we're obligated to print only
      // one of them.
      Preconditions.checkState(!errors.isEmpty(), result);
      Entry<SkyKey, ErrorInfo> error = errors.iterator().next();
      ErrorInfo errorInfo = error.getValue();
      SkyKey topLevel = error.getKey();
      Label topLevelLabel = ((TransitiveTargetKey) topLevel).getLabel();
      if (!Iterables.isEmpty(errorInfo.getCycleInfo())) {
        skyframeCyclesReporter.get().reportCycles(errorInfo.getCycleInfo(), topLevel, eventHandler);
        errorAboutLoadingFailure(topLevelLabel, null, eventHandler);
      } else if (isDirectErrorFromTopLevelLabel(topLevelLabel, labelsToVisit, errorInfo)) {
        // An error caused by a non-top-level label has already been reported during error
        // bubbling but an error caused by the top-level non-target label itself hasn't been
        // reported yet. Note that errors from top-level targets have already been reported
        // during target parsing.
        errorAboutLoadingFailure(topLevelLabel, errorInfo.getException(), eventHandler);
      }
      return false;
    }

    for (Entry<SkyKey, ErrorInfo> errorEntry : errors) {
      SkyKey key = errorEntry.getKey();
      ErrorInfo errorInfo = errorEntry.getValue();
      Preconditions.checkState(key.functionName().equals(SkyFunctions.TRANSITIVE_TARGET), errorEntry);
      Label topLevelLabel = ((TransitiveTargetKey) key).getLabel();
      if (!Iterables.isEmpty(errorInfo.getCycleInfo())) {
        skyframeCyclesReporter.get().reportCycles(errorInfo.getCycleInfo(), key, eventHandler);
      }
      if (isDirectErrorFromTopLevelLabel(topLevelLabel, labelsToVisit, errorInfo)) {
        // Unlike top-level targets, which have already gone through target parsing,
        // errors directly coming from top-level labels have not been reported yet.
        //
        // See the note in the --nokeep_going case above.
        eventHandler.handle(Event.error(errorInfo.getException().getMessage()));
      }
      warnAboutLoadingFailure(topLevelLabel, eventHandler);
    }
    for (TransitiveTargetKey topLevelTransitiveTargetKey : result.<TransitiveTargetKey>keyNames()) {
      TransitiveTargetValue topLevelTransitiveTargetValue = result.get(topLevelTransitiveTargetKey);
      if (topLevelTransitiveTargetValue.getTransitiveRootCauses() != null) {
        warnAboutLoadingFailure(topLevelTransitiveTargetKey.getLabel(), eventHandler);
      }
    }
    return false;
  }

  private static boolean hasErrors(EvaluationResult<TransitiveTargetValue> result) {
    if (result.hasError()) {
      return true;
    }
    for (TransitiveTargetValue transitiveTargetValue : result.values()) {
      if (transitiveTargetValue.getTransitiveRootCauses() != null) {
        return true;
      }
    }
    return false;
  }

  private static boolean isDirectErrorFromTopLevelLabel(Label label, Set<Label> topLevelLabels,
      ErrorInfo errorInfo) {
    return errorInfo.getException() != null && topLevelLabels.contains(label)
        && Iterables.contains(errorInfo.getRootCauses(), TransitiveTargetKey.of(label));
  }

  private static void errorAboutLoadingFailure(
      Label topLevelLabel, @Nullable Throwable throwable, ExtendedEventHandler eventHandler) {
    eventHandler.handle(Event.error(
        "Loading of target '" + topLevelLabel + "' failed; build aborted" +
            (throwable == null ? "" : ": " + throwable.getMessage())));
  }

  private static void warnAboutLoadingFailure(Label label, ExtendedEventHandler eventHandler) {
    eventHandler.handle(Event.warn("errors encountered while loading target '" + label + "'"));
  }
}


text:
package schain

import java.io.BufferedOutputStream
import java.util.Collections
import java.util.concurrent.{Executors, Future, LinkedBlockingQueue}

import com.tencent.angel.PartitionKey
import com.tencent.angel.conf.AngelConf
import com.tencent.angel.exception.AngelException
import com.tencent.angel.ml.MLLearner
import com.tencent.angel.ml.feature.LabeledData
import com.tencent.angel.ml.matrix.psf.get.base.{PartitionGetParam, PartitionGetResult}
import com.tencent.angel.ml.model.MLModel
import com.tencent.angel.psagent.PSAgentContext
import com.tencent.angel.utils.HdfsUtil
import com.tencent.angel.worker.storage.DataBlock
import com.tencent.angel.worker.task.TaskContext
import psf.{FloatPartCSRResult, GetFloatPartFunc}
import org.apache.commons.logging.{Log, LogFactory}
import org.apache.hadoop.fs.Path

import scala.collection.mutable

/**
  * Created by chris on 9/21/17.
  */
class SCLearner(ctx:TaskContext, data:SMatrix, model:SCModel) extends MLLearner(ctx) {

  val LOG:Log = LogFactory.getLog(classOf[SCLearner])

  val pkeyR = PSAgentContext.get().getMatrixPartitionRouter.
    getPartitionKeyList(model.wtMat.getMatrixId())

  Collections.shuffle(pkeyR)

  val pkeyM1 = PSAgentContext.get().getMatrixPartitionRouter.
    getPartitionKeyList(model.mat1.getMatrixId())

  Collections.shuffle(pkeyM1)

  val pkeyM2 = PSAgentContext.get().getMatrixPartitionRouter.
    getPartitionKeyList(model.mat2.getMatrixId())

  Collections.shuffle(pkeyM2)

  override
  def train(train: DataBlock[LabeledData], vali: DataBlock[LabeledData]): MLModel = ???

  val queue = new LinkedBlockingQueue[SCOperator]()
  val executor = Executors.newFixedThreadPool(model.threadNum)

  val batchSize = model.batchSize
  var bkeys = (0 until data.numOfRows by batchSize) map {i =>
  (i, Math.min(data.numOfRows, i + batchSize))
  }

  def scheduleInit(): Unit = {
    class Task(operator: SCOperator, pkey: PartitionKey) extends Thread {
      override def run(): Unit = {
        operator.initialize(pkey)
        queue.add(operator)
      }
    }

    for (i <- 0 until model.threadNum) queue.add(new SCOperator(data, model))

    val iter = pkeyR.iterator()
    while (iter.hasNext) {
      val operator = queue.take()
      executor.execute(new Task(operator, iter.next()))
    }

    for (i <- 0 until model.threadNum) queue.take()

    // update for wt
   model.wtMat.clock().get()
  }

  def scheduleMultiply():Unit = {
    class MultiTask(operator: SCOperator, pkey: PartitionKey, csr: FloatPartCSRResult, dkey: (Int, Int), partResult: Array[Array[Float]], label:Int) extends Thread {
      override def run(): Unit = {
        operator.multiply(dkey, csr, pkey, partResult, label)
        queue.add(operator)
      }
    }

    class ProjTask(operator: SCOperator, batch : Array[Array[Float]], csr:FloatPartCSRResult, pkey:PartitionKey, result:Array[Array[Float]]) extends Thread {
      override def run(): Unit = {
        operator.proj(batch,csr,pkey, result)
        queue.add(operator)
      }
    }

  val client = PSAgentContext.get().getMatrixTransportClient
  val func = new GetFloatPartFunc(null)

  bkeys.indices foreach { i =>
    val bkey = bkeys(i)
    val (bs, be) = bkey
    val len = be - bs
    val futures = new mutable.HashMap[PartitionKey, Future[PartitionGetResult]]()
    var batch = Array.ofDim[Float](len, model.N)
    for (i <- 0 until model.threadNum) queue.add(new SCOperator(data, model))
    val iter1 = pkeyM1.iterator()
    while (iter1.hasNext) {
      val pkey = iter1.next()
      val param = new PartitionGetParam(model.mat1.getMatrixId, pkey)
      val future = client.get(func, param)
      futures.put(pkey, future)
    }

    while (futures.nonEmpty) {
      val keys = futures.keySet.iterator
      while (keys.hasNext) {
        val pkey = keys.next()
        val future = futures(pkey)
        if (future.isDone) {
          val operator = queue.take()
          future.get() match {
            case csr: FloatPartCSRResult => executor.execute(new MultiTask(operator, pkey, csr, bkey, batch, 1))
            case _ => throw new AngelException("should by FloatPartCSRResult")
          }
          futures.remove(pkey)
        }
      }
    }

    val iter2 = pkeyM2.iterator()
    while (iter2.hasNext) {
      val pkey = iter2.next()
      val param = new PartitionGetParam(model.mat2.getMatrixId, pkey)
      val future = client.get(func, param)
      futures.put(pkey, future)
    }

    while (futures.nonEmpty) {
      val keys = futures.keySet.iterator
      while (keys.hasNext) {
        val pkey = keys.next()
        val future = futures(pkey)
        if (future.isDone) {
          val operator = queue.take()
          future.get() match {
            case csr: FloatPartCSRResult => executor.execute(new MultiTask(operator, pkey, csr, bkey, batch, 2))
            case _ => throw new AngelException("should by FloatPartCSRResult")
          }
          futures.remove(pkey)
        }
      }
    }

    val result: Array[Array[Float]] = Array.ofDim[Float](len, model.R)

    val iter3 = pkeyR.iterator()
    while (iter3.hasNext) {
      val pkey = iter3.next()
      val param = new PartitionGetParam(model.wtMat.getMatrixId, pkey)
      val future = client.get(func, param)
      futures.put(pkey, future)
    }

    while (futures.nonEmpty) {
      val keys = futures.keySet.iterator
      while (keys.hasNext) {
        val pkey = keys.next()
        val future = futures(pkey)
        if (future.isDone) {
          val operator = queue.take()
          future.get() match {
            case csr: FloatPartCSRResult => executor.execute(new ProjTask(operator, batch, csr, pkey, result))
            case _ => throw new AngelException("should by FloatPartCSRResult")
          }
          futures.remove(pkey)
        }
      }
    }

    batch = null
    (0 until model.threadNum) foreach{ _ => queue.take() }
    if (model.saveMat) savePartResult(result, i, bkey)
    }
  }

  def savePartResult(result:Array[Array[Float]], batch:Int,block: (Int, Int)): Unit = {
    LOG.info(s"save $batch")
    val dir = conf.get(AngelConf.ANGEL_SAVE_MODEL_PATH)
    val base = dir + "/" + s"batch_$batch"
    val part = ctx.getTaskIndex
    val dest = new Path(base,part.toString)
    val fs = dest.getFileSystem(conf)
    val tmp = HdfsUtil.toTmpPath(dest)
    val out = new BufferedOutputStream(fs.create(tmp, 1.toShort))
    val (bs, be) = block
    (bs until be) foreach { b =>
      val sb = new mutable.StringBuilder()
      sb.append(data.rowIds(b))
      val row = result(b - bs)
      row.zipWithIndex.filter(f => f._1 != 0f).foreach{case(v, k) =>
        sb.append(s" $k:$v")
      }
      sb.append("\n")
      out.write(sb.toString().getBytes("UTF-8"))
    }
    out.flush()
    out.close()
    fs.rename(tmp, dest)
  }
}


text:
package consulo.csharp.lang.psi;

import com.intellij.psi.PsiElement;
import consulo.annotation.access.RequiredReadAction;

import javax.annotation.Nonnull;

/**
 * @author VISTALL
 * @since 18.12.2015
 */
public class ToNativeElementTransformers
{
	@Nonnull
	@RequiredReadAction
	public static PsiElement transform(@Nonnull PsiElement element)
	{
		PsiElement transform = ToNativeElementTransformer.EP_NAME.composite().transform(element);
		if(transform != null)
		{
			return transform;
		}
		return element;
	}
}


text:
// Copy assets
var gulp = require('gulp'),
    paths = require('./config/paths'),
    plumber = require('gulp-plumber');

gulp.task('sync:helpers', function() {
  return gulp.src([
    paths.dev.helpers + '/**/',
    paths.dev.helpers + '/.htaccess'
  ], {base: paths.dev.helpers})
    .pipe(plumber())
    .pipe(gulp.dest(paths.build.main));
});

gulp.task('sync:helpers:changed', function() {
  gulp.src([
    paths.dev.helpers + '/**/',
    paths.dev.helpers + '/.htaccess'
  ], {base: paths.dev.helpers})
    .pipe(plumber())
    .pipe(gulp.dest(paths.build.main));
});


text:
module Statistics.Regression
    (
      olsRegress
    , ols
    , rSquare
    , bootstrapRegress
    ) where

import Control.Concurrent.Async (forConcurrently)
import Control.DeepSeq (rnf)
import Control.Monad (when)
import Data.List (nub)
import GHC.Conc (getNumCapabilities)
import Prelude hiding (pred, sum)
import Statistics.Function as F
import Statistics.Matrix hiding (map)
import Statistics.Matrix.Algorithms (qr)
import Statistics.Resampling (splitGen)
import Statistics.Types      (Estimate(..),ConfInt,CL,estimateFromInterval,significanceLevel)
import Statistics.Sample (mean)
import Statistics.Sample.Internal (sum)
import System.Random.MWC (GenIO, uniformR)
import qualified Data.Vector as V
import qualified Data.Vector.Generic as G
import qualified Data.Vector.Unboxed as U
import qualified Data.Vector.Unboxed.Mutable as M

-- | Perform an ordinary least-squares regression on a set of
-- predictors, and calculate the goodness-of-fit of the regression.
--
-- The returned pair consists of:
--
-- * A vector of regression coefficients.  This vector has /one more/
--   element than the list of predictors; the last element is the
--   /y/-intercept value.
--
-- * /R²/, the coefficient of determination (see 'rSquare' for
--   details).
olsRegress :: [Vector]
              -- ^ Non-empty list of predictor vectors.  Must all have
              -- the same length.  These will become the columns of
              -- the matrix /A/ solved by 'ols'.
           -> Vector
              -- ^ Responder vector.  Must have the same length as the
              -- predictor vectors.
           -> (Vector, Double)
olsRegress preds@(_:_) resps
  | any (/=n) ls        = error $ "predictor vector length mismatch " ++
                                  show lss
  | G.length resps /= n = error $ "responder/predictor length mismatch " ++
                                  show (G.length resps, n)
  | otherwise           = (coeffs, rSquare mxpreds resps coeffs)
  where
    coeffs    = ols mxpreds resps
    mxpreds   = transpose .
                fromVector (length lss + 1) n .
                G.concat $ preds ++ [G.replicate n 1]
    lss@(n:ls) = map G.length preds
olsRegress _ _ = error "no predictors given"

-- | Compute the ordinary least-squares solution to /A x = b/.
ols :: Matrix     -- ^ /A/ has at least as many rows as columns.
    -> Vector     -- ^ /b/ has the same length as columns in /A/.
    -> Vector
ols a b
  | rs < cs   = error $ "fewer rows than columns " ++ show d
  | otherwise = solve r (transpose q `multiplyV` b)
  where
    d@(rs,cs) = dimension a
    (q,r)     = qr a

-- | Solve the equation /R x = b/.
solve :: Matrix     -- ^ /R/ is an upper-triangular square matrix.
      -> Vector     -- ^ /b/ is of the same length as rows\/columns in /R/.
      -> Vector
solve r b
  | n /= l    = error $ "row/vector mismatch " ++ show (n,l)
  | otherwise = U.create $ do
  s <- U.thaw b
  rfor n 0 $ \i -> do
    si <- (/ unsafeIndex r i i) <$> M.unsafeRead s i
    M.unsafeWrite s i si
    F.for 0 i $ \j -> F.unsafeModify s j $ subtract (unsafeIndex r j i * si)
  return s
  where n = rows r
        l = U.length b

-- | Compute /R²/, the coefficient of determination that
-- indicates goodness-of-fit of a regression.
--
-- This value will be 1 if the predictors fit perfectly, dropping to 0
-- if they have no explanatory power.
rSquare :: Matrix               -- ^ Predictors (regressors).
        -> Vector               -- ^ Responders.
        -> Vector               -- ^ Regression coefficients.
        -> Double
rSquare pred resp coeff = 1 - r / t
  where
    r   = sum $ flip U.imap resp $ \i x -> square (x - p i)
    t   = sum $ flip U.map resp $ \x -> square (x - mean resp)
    p i = sum . flip U.imap coeff $ \j -> (* unsafeIndex pred i j)

-- | Bootstrap a regression function.  Returns both the results of the
-- regression and the requested confidence interval values.
bootstrapRegress
  :: GenIO
  -> Int         -- ^ Number of resamples to compute.
  -> CL Double   -- ^ Confidence level.
  -> ([Vector] -> Vector -> (Vector, Double))
     -- ^ Regression function.
  -> [Vector]    -- ^ Predictor vectors.
  -> Vector      -- ^ Responder vector.
  -> IO (V.Vector (Estimate ConfInt Double), Estimate ConfInt Double)
bootstrapRegress gen0 numResamples cl rgrss preds0 resp0
  | numResamples < 1   = error $ "bootstrapRegress: number of resamples " ++
                                 "must be positive"
  | otherwise = do

  -- some error checks so that we do not run into vector index out of bounds.
  case nub (map U.length preds0) of
    [] -> error "bootstrapRegress: predictor vectors must not be empty"
    [plen] -> do
        let rlen = U.length resp0
        when (plen /= rlen) $
            error $ "bootstrapRegress: responder vector length ["
                ++ show rlen
                ++ "] must be the same as predictor vectors' length ["
                ++ show plen ++ "]"
    xs -> error $ "bootstrapRegress: all predictor vectors must be of the same \
        \length, lengths provided are: " ++ show xs

  caps <- getNumCapabilities
  gens <- splitGen caps gen0
  vs <- forConcurrently (zip gens (balance caps numResamples)) $ \(gen,count) -> do
      v <- V.replicateM count $ do
           let n = U.length resp0
           ixs <- U.replicateM n $ uniformR (0,n-1) gen
           let resp  = U.backpermute resp0 ixs
               preds = map (flip U.backpermute ixs) preds0
           return $ rgrss preds resp
      rnf v `seq` return v
  let (coeffsv, r2v) = G.unzip (V.concat vs)
  let coeffs  = flip G.imap (G.convert coeffss) $ \i x ->
                est x . U.generate numResamples $ \k -> (coeffsv G.! k) G.! i
      r2      = est r2s (G.convert r2v)
      (coeffss, r2s) = rgrss preds0 resp0
      est s v = estimateFromInterval s (w G.! lo, w G.! hi) cl
        where w  = F.sort v
              bounded i = min (U.length w - 1) (max 0 i)
              lo = bounded $ round c
              hi = bounded $ truncate (n - c)
              n  = fromIntegral numResamples
              c  = n * (significanceLevel cl / 2)
  return (coeffs, r2)

-- | Balance units of work across workers.
balance :: Int -> Int -> [Int]
balance numSlices numItems = zipWith (+) (replicate numSlices q)
                                         (replicate r 1 ++ repeat 0)
 where (q,r) = numItems `quotRem` numSlices


text:
if debug == nil then
	error("Overload.lua requires the debug library")
end

local deviations = {
	["nil"] = {
		"nil",
		"null",
	},
	["number"] = {
		"number",
		"num",
		"int",
		"float",
		"double",
		"real",
	},
	["boolean"] = {
		"bool",
		"boolean",
		"bit",
	},
	["string"] = {
		"string",
		"str",
		"char",
		"byte",
	},
	["table"] = {
		"table",
		"tbl",
		"array",
		"list",
	},
	["function"] = {
		"function",
		"func",
		"method",
	},
	["thread"] = {
		"thread",
	},
	["userdata"] = {
		"userdata",
		"user-data",
		"memory"
	}
}

local function typesEqual(typeName, identifier)
	if deviations[typeName] == nil then
		error("Type is not lua type: " .. typeName)
	end
	if type(identifier) == "string" then identifier = {identifier} end

	for _,v in ipairs(deviations[typeName]) do
		for _,v2 in ipairs(identifier) do
			if v:lower() == v2:lower() then
				return true
			end
		end
	end
	return false
end

function checkParameters(parameterList, defaultList)
	if debug.getinfo(2, "f") == nil then
		error("Called from outside function")
	end

	local paramNum = 1
	while true do
		local name, value = debug.getlocal(2, paramNum)
		if name == nil then break end

		if value == nil and defaultList ~= nil then
			debug.setlocal(2, paramNum, defaultList[paramNum])
			value = defaultList[paramNum]
		end
		if parameterList[paramNum] ~= nil and not typesEqual(type(value), parameterList[paramNum]) then
			return false
		end
		paramNum = paramNum + 1
	end
	return true
end


text:
import pulsar

from agile.app import AgileManager

from lux.core import LuxCommand

class Command(LuxCommand):
    help = "Run agile commands for development"

    def __call__(self, argv):
        app = self.app
        server = self.pulsar_app(argv, AgileManager)

        if not server.logger:   # pragma    nocover
            app._started = server()
            pulsar.arbiter().start()


text:
 Featured Projects

 Project Title

 Featured Skills

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

      Check it out

 Project Title

 Featured Skills

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

      Check it out


text:
require 'bio-ucsc'
describe "Bio::Ucsc::Hg18::EncodeUWRegulomeBaseHeLa" do

  describe "#find_by_interval" do
    context "given range chr5:1-140,000,000" do
      it 'returns a record (r.chrom == "chr5")' do
        Bio::Ucsc::Hg18::DBConnection.default
        Bio::Ucsc::Hg18::DBConnection.connect
        i = Bio::GenomicInterval.parse("chr5:1-140,000,000")
        r = Bio::Ucsc::Hg18::EncodeUWRegulomeBaseHeLa.find_by_interval(i)
        r.chrom.should == "chr5"
      end
    end
  end
end


text:
package com.p_v.flexiblecalendar.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;

import com.p_v.flexiblecalendar.entity.Event;
import com.p_v.fliexiblecalendar.R;

import java.util.List;

/**
 * Cell view with the event count
 *
 * @author p-v
 */
public class EventCountCellView extends BaseCellView{

    private Paint mPaint;
    private Paint mTextPaint;
    private int mEventCount;
    private int eventCircleY;
    private int eventCircleX;
    private int mTextY;

    private int radius;
    private int eventTextColor;
    private int eventBackground;
    private int eventTextSize;

    public EventCountCellView(Context context) {
        super(context);
    }

    public EventCountCellView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public EventCountCellView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs){
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.EventCountCellView);
        try{
            radius = (int)a.getDimension(R.styleable.EventCountCellView_event_count_radius,15);
            eventBackground = a.getColor(R.styleable.EventCountCellView_event_background,
                    getResources().getColor(android.R.color.black));
            eventTextColor = a.getColor(R.styleable.EventCountCellView_event_count_text_color,
                    getResources().getColor(android.R.color.white));
            eventTextSize = (int)a.getDimension(R.styleable.EventCountCellView_event_text_size,-1);
        }finally {
            a.recycle();
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        if(mEventCount>0) {
            Paint p = new Paint();
            p.setTextSize(getTextSize());

            Rect rect = new Rect();
            p.getTextBounds("31", 0, 1, rect); // measuring using fake text

            eventCircleY = (getHeight() - rect.height()) / 4;
            eventCircleX = (3 * getWidth() + rect.width()) / 4;

            mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mTextPaint.setStyle(Paint.Style.FILL);
            mTextPaint.setTextSize(eventTextSize==-1?getTextSize() / 2 : eventTextSize);
            mTextPaint.setColor(eventTextColor);
            mTextPaint.setTextAlign(Paint.Align.CENTER);

            mTextY = eventCircleY + radius/2;
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if(mEventCount>0 && mPaint!=null && mTextPaint!= null) {
            canvas.drawCircle(eventCircleX, eventCircleY, radius, mPaint);
            canvas.drawText(String.valueOf(mEventCount), eventCircleX, mTextY, mTextPaint);
        }
    }

    @Override
    public void setEvents(List<? extends Event> colorList) {
        if(colorList!=null && !colorList.isEmpty()){
            mEventCount = colorList.size();
            mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
            mPaint.setStyle(Paint.Style.FILL);
            mPaint.setColor(eventBackground);
            invalidate();
            requestLayout();
        }
    }
}


text:
<?php namespace Congredi\NotificationSystem\Facades;

use Illuminate\Support\Facades\Facade;

class NotificationSystem extends Facade
{
	/**
	 * Get the registered name of the component.
	 *
	 * @return string
	 */
	protected static function getFacadeAccessor()
	{
		return 'notificationSystem.manager';
	}
}


text:
<title>
Bhandarkar's 'Fashion' runs into casting trouble : India Entertainment
</title>
<link rel="alternate" type="application/rss+xml" title="Earthtimes News RSS" href="http://feeds.earthtimes.org/earthtimes/entertainment/india">

<link href="/etcss.css" rel="stylesheet" type="text/css">

Bhandarkar's 'Fashion' runs into casting trouble

Posted                                         :

Mon, 07 Jan 2008                                        04:07:06                  GMT

Author                                         :

Subhash K Jha

Category                                         :

India (Entertainment)

News                                         Alerts

by Email

click                                         here

)

Create                                                   your own RSS

India Entertainment                  News

|

Home

Mumbai, Jan 7 - Queer are the ways of showbiz. After getting the female leads Priyanka Chopra and Kangana Ranuat in place, Madhur Bhandarkar's casting for 'Fashion' is in trouble.

The male lead, requiring a charismatic star to play a prominent costume designer, remains 'un-cast despite months of efforts', sources say.

Reason? No major star in Bollywood is willing to play a gay designer even 'if it is only make-belief'. The director has approached several marquee names, but they have all recoiled in horror and laughed off Bhandarkar's offer.

It is an instant replay of the situation with Rituparno Ghosh some years ago when he had approached Akshay Kumar to play a gay man's character.

Bhandarkar is at his wit's end, 'This a strange situation. None of our actors wants to play a challenging role. I don't know what to do, probably settle for a new theatre actor.'

A young actor, Jay Karla, had played a gay character in Bhandarkar's 'Page 3'.   Not much has been heard of him since then. Many years ago, Kalpana Lajmi had offered Shah Rukh Khan the role of a eunuch in 'Darmiyaan'. Arif Zakaria, who took over the part, faded out from the scene.

(c) Indo-Asian News Service

»

Print                                       this article

»

Email                                                     this article

 Share                                           this article on

Have                                                   your Say

<form action="javascript:void(0)" name="form1">

Name

<input name="author" id="author3" size="43" type="text">

Email

<input name="authoremail" id="authoremail" size="43" type="text">

Subject

<input name="subject" id="subject" size="43" type="text">

Your                                                       Comment

<textarea name="comment" cols="40" rows="6" id="textarea"></textarea>

<input class="x-nc-invisible">

Enter                                                         Verification code

<input name="vcode" id="vcode" value="" type="text">

<input name="Submit" value="Submit" type="submit">

<input name="Submit2" value="Reset" type="reset">

</form>

<form id="searchbox_000501353801138064958:vxk8apruzui" action="javascript:void(0)">
<input class="x-nc-invisible">

<input class="x-nc-invisible">

<input name="q" size="20" type="text">

<input name="sa" value="Search" type="submit">

</form>

Current                                   News

Adman shot Taare... song because of Aamir's 'integrity'

Anurag Basu casts mentor Mahesh Bhatt's son in film

Now a catfight between leading ladies of 'Bigg Boss'

Rajnikanth to star in Shankar's 'Robot'

Madonna prays at Nathdwara, Eklingji temples

Tamil actors shooting in Malaysia

Have                                             Your Say

News                                   by Category

Business

Entertainment

-                                                   India

-                                                   UK

-                                                   US

Environment

General

Health

Sports

Technology

World

Related                               Articles

-                               Bhandarkar's 'Fashion' has competition

|                         22 Dec 2007

-                               Harsh Chhaya to play gay in 'Fashion'

|                         05 Jan 2008

Your                             Comments

Ha Ha Shubash Jha Jha

By:                                       Alfred Hitchrooster                  ,                   Mon, 07 Jan 2008                  17:22:12                  GMT

Pretty Cool dude. "Queer" indeed are the ways of showbiz. Nice choice of words. And funny too. How much do these chaps pay you pal? If they're reading this they ought to give you a pay hike. wotsay?

More                           India (Entertainment)        News

click         here

Home

|

News                   Archives

|

Browse

|

Feedback

|

About                   us

|

Disclaimer

|

Mobile/PDA

|

News                   Alerts

(c) 2008

Earthtimes.org

, All Rights Reserved.

The views expressed in the articles are not necessarily those of earthtimes.org and we accept no responsibility for the views or opinions expressed in the articles either direct or indirect.


text:
package lighthouse.threading;

import com.google.common.util.concurrent.*;
import javafx.application.*;
import lighthouse.protocol.*;
import org.bitcoinj.core.*;
import org.slf4j.*;

import java.time.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import java.util.function.*;

import static com.google.common.base.Preconditions.*;
import static lighthouse.protocol.LHUtils.*;

/** An extended executor interface that supports thread affinity assertions and short circuiting. */
public interface AffinityExecutor extends Executor {
    /** Returns true if the current thread is equal to the thread this executor is backed by. */
    boolean isOnThread();
    /** Throws an IllegalStateException if the current thread is equal to the thread this executor is backed by. */
    void checkOnThread();
    /** If isOnThread() then runnable is invoked immediately, otherwise the closure is queued onto the backing thread. */
    void executeASAP(LHUtils.UncheckedRunnable runnable);

    /**
     * Runs the given function on the executor, blocking until the result is available. Be careful not to deadlock this
     * way! Make sure the executor can't possibly be waiting for the calling thread.
     */
    default <T> T fetchFrom(Supplier<T> fetcher) {
        if (isOnThread())
            return fetcher.get();
        else
            return checkedGet(CompletableFuture.supplyAsync(fetcher, this));
    }

    abstract class BaseAffinityExecutor implements AffinityExecutor {
        protected final Thread.UncaughtExceptionHandler exceptionHandler;

        protected BaseAffinityExecutor() {
            exceptionHandler = Thread.currentThread().getUncaughtExceptionHandler();
        }

        @Override
        public abstract boolean isOnThread();

        @Override
        public void checkOnThread() {
            checkState(isOnThread(), "On wrong thread: %s", Thread.currentThread());
        }

        @Override
        public void executeASAP(LHUtils.UncheckedRunnable runnable) {
            final Runnable command = () -> {
                try {
                    runnable.run();
                } catch (Throwable throwable) {
                    exceptionHandler.uncaughtException(Thread.currentThread(), throwable);
                }
            };
            if (isOnThread())
                command.run();
            else {
                execute(command);
            }
        }

        // Must comply with the Executor definition w.r.t. exceptions here.
        @Override
        public abstract void execute(Runnable command);
    }

    AffinityExecutor UI_THREAD = new BaseAffinityExecutor() {
        @Override
        public boolean isOnThread() {
            return Platform.isFxApplicationThread();
        }

        @Override
        public void execute(Runnable command) {
            Platform.runLater(command);
        }
    };

    AffinityExecutor SAME_THREAD = new BaseAffinityExecutor() {
        @Override
        public boolean isOnThread() {
            return true;
        }

        @Override
        public void execute(Runnable command) {
            command.run();
        }
    };

    class ServiceAffinityExecutor extends BaseAffinityExecutor {
        private static final Logger log = LoggerFactory.getLogger(ServiceAffinityExecutor.class);

        protected AtomicReference<Thread> whichThread = new AtomicReference<>(null);
        private final Thread.UncaughtExceptionHandler handler = Thread.currentThread().getUncaughtExceptionHandler();
        public final ScheduledThreadPoolExecutor service;

        public ServiceAffinityExecutor(String threadName) {
            Context bcjContext = Context.get();
            service = new ScheduledThreadPoolExecutor(1, runnable -> {
                Thread thread = new Thread(() -> {
                    Context.propagate(bcjContext);
                    runnable.run();
                });
                thread.setDaemon(true);
                thread.setName(threadName);
                whichThread.set(thread);
                return thread;
            }, (runnable, executor) -> {
                // log.error("Ignored execution attempt due to shutdown", new Throwable());
            });
        }

        @Override
        public boolean isOnThread() {
            return Thread.currentThread() == whichThread.get();
        }

        @Override
        public void execute(Runnable command) {
            service.execute(() -> {
                try {
                    command.run();
                } catch (Throwable e) {
                    if (handler != null)
                        handler.uncaughtException(Thread.currentThread(), e);
                    else
                        e.printStackTrace();
                }
            });
        }

        public <T> ScheduledFuture<T> executeIn(Duration time, Callable<T> command) {
            return service.schedule(command::call, time.toMillis(), TimeUnit.MILLISECONDS);
        }

        public ScheduledFuture<?> executeIn(Duration time, Runnable runnable) {
            return service.schedule(() -> {
                try {
                    runnable.run();
                } catch (Throwable e) {
                    if (handler != null)
                        handler.uncaughtException(Thread.currentThread(), e);
                    else
                        e.printStackTrace();
                }
            }, time.toMillis(), TimeUnit.MILLISECONDS);
        }
    }

    /**
     * An executor useful for unit tests: allows the current thread to block until a command arrives from another
     * thread, which is then executed. Inbound closures/commands stack up until they are cleared by looping.
     */
    class Gate extends BaseAffinityExecutor {
        private final Thread thisThread = Thread.currentThread();
        private final LinkedBlockingQueue<Runnable> commandQ = new LinkedBlockingQueue<>();
        private final boolean alwaysQueue;

        public Gate() {
            this(false);
        }

        /** If alwaysQueue is true, executeASAP will never short-circuit and will always queue up. */
        public Gate(boolean alwaysQueue) {
            this.alwaysQueue = alwaysQueue;
        }

        @Override
        public boolean isOnThread() {
            return !alwaysQueue && Thread.currentThread() == thisThread;
        }

        @Override
        public void execute(Runnable command) {
            Uninterruptibles.putUninterruptibly(commandQ, command);
        }

        public void waitAndRun() {
            final Runnable runnable = Uninterruptibles.takeUninterruptibly(commandQ);
            runnable.run();
        }

        public int getTaskQueueSize() {
            return commandQ.size();
        }
    }
}


text:
package eBayPrep;

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

public class _118PascalsTriangle {

	public static class TreeLinkNode {
		int val;
		TreeLinkNode left, right, next;
		TreeLinkNode(int x) { val = x; }
	}
	public static void main(String[] args) {
		System.out.println(generate(5));
	}
	public static List<List<Integer>> generate(int numRows) {
		List<List<Integer>> outputList=new ArrayList<>();
		if(numRows==0)return outputList;
		List<Integer> individualList=new ArrayList<>();
		individualList.add(1);
		outputList.add(individualList);
		if(numRows==1)
			return outputList;
		else{
			for (int i = 2; i <=numRows; i++) {
				individualList=outputList.get(outputList.size()-1);
				List<Integer> tempList=new ArrayList<>();
				for (int j = 0; j <=individualList.size(); j++) {
					if(j==0||j==individualList.size())
					{
						tempList.add(individualList.get(0));
					}
					else{
						tempList.add(individualList.get(j)+individualList.get(j-1));
					}
				}
				outputList.add(tempList);
			}
		}
		return outputList;
	}

}


text:
module.exports = function (grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		jasmine: {
			unit: {
				src: 'public/js/**/*.js',
				options: {
					specs: [
						'test/**/*.test.js'
					],
					vendor: [
						'public/vendor/angular/angular.js',
						'public/vendor/angular-mocks/angular-mocks.js'
					]
				}
			}
		}
	});

	grunt.loadNpmTasks('grunt-recess');
	grunt.loadNpmTasks('grunt-contrib-jasmine');

	grunt.registerTask('default', ['jasmine']);
};


text:
@interface NSError (FLStreamController)
+ (NSError*) errorFromStreamError:(CFStreamError) streamError;
@end

NS_INLINE
NSError* FLCreateErrorFromStreamError(const CFStreamError* streamError) {
    if(streamError && streamError->domain != 0 && streamError->error != 0) {
        return [NSError errorFromStreamError:*streamError];
    }

    return nil;
}


text:
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>BlackOwl</groupId>
    <artifactId>BlackOwl</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>BlackOwl Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <org.springframework.version>4.2.4.RELEASE</org.springframework.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.2.Final</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.2.Final</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${org.springframework.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${org.springframework.version}</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.7.2</version>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.2</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>BlackOwl</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <url>http://localhost:8080/manager/text</url>
                    <server>TomcatServer</server>
                    <path>/</path>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
	itemFrame.lua
		A void storage item frame. Three kinds:
			nil -> deposited items
			DEPOSIT -> items to deposit
			WITHDRAW -> items to withdraw
--]]

local ItemFrame = Bagnon:NewClass('VaultItemFrame', 'Button', Bagnon.ItemFrame)
ItemFrame.Button = Bagnon.VaultSlot
ItemFrame.TransposeLayout = true

function ItemFrame:RegisterEvents()
	self:UnregisterEvents()
	self:RegisterMessage(self:GetFrameID() .. '_PLAYER_CHANGED', 'OnShow')
	self:RegisterMessage('UPDATE_ALL', 'RequestLayout')

	if self:IsCached() then
		self:RegisterEvent('GET_ITEM_INFO_RECEIVED', 'ForAll', 'Update')
		self:RegisterEvent('VOID_STORAGE_OPEN', 'RegisterEvents')
	else
		if self:Type() == DEPOSIT then
			self:RegisterEvent('VOID_STORAGE_DEPOSIT_UPDATE', 'RequestLayout')
		elseif self:Type() == WITHDRAW then
			self:RegisterEvent('VOID_STORAGE_CONTENTS_UPDATE', 'RequestLayout')
		else
			self:RegisterEvent('VOID_STORAGE_CONTENTS_UPDATE', 'ForAll', 'Update')
			self:RegisterEvent('VOID_STORAGE_UPDATE', 'ForAll', 'Update')
			self:RegisterEvent('VOID_TRANSFER_DONE', 'ForAll', 'Update')
		end
	end
end

function ItemFrame:NumSlots()
	if self:Type() == DEPOSIT then
		return GetNumVoidTransferDeposit()
	elseif self:Type() == WITHDRAW then
		return GetNumVoidTransferWithdrawal()
	else
		return 80 * 2
	end
end

function ItemFrame:Type()
	return self.bags[1]
end