text:
package com.jfinal.plugin.ehcache;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.servlet.http.HttpServletRequest;
import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;

/**
 * CacheInterceptor.
 */
public class CacheInterceptor implements Interceptor {

	private static final String renderKey = "$renderKey$";
	private static volatile ConcurrentHashMap<String, ReentrantLock> lockMap = new ConcurrentHashMap<String, ReentrantLock>();

	private ReentrantLock getLock(String key) {
		ReentrantLock lock = lockMap.get(key);
		if (lock != null)
			return lock;

		lock = new ReentrantLock();
		ReentrantLock previousLock = lockMap.putIfAbsent(key, lock);
		return previousLock == null ? lock : previousLock;
	}

	final public void intercept(ActionInvocation ai) {
		Controller controller = ai.getController();
		String cacheName = buildCacheName(ai, controller);
		String cacheKey = buildCacheKey(ai, controller);
		Map<String, Object> cacheData = CacheKit.get(cacheName, cacheKey);
		if (cacheData == null) {
			Lock lock = getLock(cacheName);
			lock.lock();					// prevent cache snowslide
			try {
				cacheData = CacheKit.get(cacheName, cacheKey);
				if (cacheData == null) {
					ai.invoke();
					cacheAction(cacheName, cacheKey, controller);
					return ;
				}
			}
			finally {
				lock.unlock();
			}
		}

		useCacheDataAndRender(cacheData, controller);
	}

	// TODO 考虑与 EvictInterceptor 一样强制使用  @CacheName
	private String buildCacheName(ActionInvocation ai, Controller controller) {
		CacheName cacheName = ai.getMethod().getAnnotation(CacheName.class);
		if (cacheName != null)
			return cacheName.value();
		cacheName = controller.getClass().getAnnotation(CacheName.class);
		return (cacheName != null) ? cacheName.value() : ai.getActionKey();
	}

	private String buildCacheKey(ActionInvocation ai, Controller controller) {
		StringBuilder sb = new StringBuilder(ai.getActionKey());
		String urlPara = controller.getPara();
		if (urlPara != null)
			sb.append("/").append(urlPara);

		String queryString = controller.getRequest().getQueryString();
		if (queryString != null)
			sb.append("?").append(queryString);
		return sb.toString();
	}

	private void cacheAction(String cacheName, String cacheKey, Controller controller) {
		HttpServletRequest request = controller.getRequest();
		Map<String, Object> cacheData = new HashMap<String, Object>();
		for (Enumeration<String> names=request.getAttributeNames(); names.hasMoreElements();) {
			String name = names.nextElement();
			cacheData.put(name, request.getAttribute(name));
		}

		cacheData.put(renderKey, new RenderInfo(controller.getRender()));		// cache RenderInfo
		CacheKit.put(cacheName, cacheKey, cacheData);
	}

	private void useCacheDataAndRender(Map<String, Object> cacheData, Controller controller) {
		HttpServletRequest request = controller.getRequest();
		Set<Entry<String, Object>> set = cacheData.entrySet();
		for (Iterator<Entry<String, Object>> it=set.iterator(); it.hasNext();) {
			Entry<String, Object> entry = it.next();
			request.setAttribute(entry.getKey(), entry.getValue());
		}
		request.removeAttribute(renderKey);

		controller.render(((RenderInfo)cacheData.get(renderKey)).createRender());		// set render from cacheData
	}
}


text:
package godocker

import (
	"context"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io"
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/docker/docker/api/types"
	"github.com/docker/docker/api/types/filters"
	"github.com/docker/docker/builder"
	"github.com/docker/docker/builder/dockerignore"
	"github.com/docker/docker/client"
	"github.com/docker/docker/pkg/archive"
	"github.com/docker/docker/pkg/fileutils"
	"github.com/docker/docker/pkg/jsonmessage"
	"github.com/pkg/errors"
)

const (
	defaultDockerAPIVersion = "v1.23"
	defaultDockerfile       = "Dockerfile"
	defaultDockerHost       = "tcp://127.0.0.1:2376"
)

// ImageSummary of a docker image
type ImageSummary struct {
	Containers  int64             `json:"Containers"`
	Created     int64             `json:"Created"`
	ID          string            `json:"Id"`
	Labels      map[string]string `json:"Labels"`
	ParentID    string            `json:"ParentId"`
	RepoDigests []string          `json:"RepoDigests"`
	RepoTags    []string          `json:"RepoTags"`
	SharedSize  int64             `json:"SharedSize"`
	Size        int64             `json:"Size"`
	VirtualSize int64             `json:"VirtualSize"`
}

// Docker is an interface that contains some operations which can be used to build a image from source code
type Docker interface {
	Build(ctx context.Context, contextDirectory, imagePath string, args map[string]*string) error
	Pull(ctx context.Context, imagePath string) error
	Push(ctx context.Context, imagePath string) error
	List(ctx context.Context, filters map[string]string) ([]*ImageSummary, error)
	Tag(ctx context.Context, imagePath, newImagePath string) error
	Rmi(ctx context.Context, imagePath string) error
}

type dockerCmd struct {
	cli                *client.Client
	dockerHost         string
	registry           string
	registryAuthString string
	registryAuthMap    map[string]types.AuthConfig
	noCache            bool
	forceRm            bool
	pull               bool
}

// Configs is used to create the docker client
type Configs struct {
	Host     string
	Registry string
	User     string
	Passwd   string
}

// NewClient will return a docker image builder client
func NewClient(cfg Configs) (Docker, error) {
	cli, err := client.NewClient(cfg.Host, defaultDockerAPIVersion, nil, nil)
	if err != nil {
		return nil, err
	}
	auth := types.AuthConfig{
		Username: cfg.User,
		Password: cfg.Passwd,
	}
	authBytes, _ := json.Marshal(auth)
	authBase64 := base64.URLEncoding.EncodeToString(authBytes)

	docker := &dockerCmd{
		cli:                cli,
		dockerHost:         cfg.Host,
		registry:           cfg.Registry,
		registryAuthString: authBase64,
		registryAuthMap: map[string]types.AuthConfig{
			cfg.Registry: auth,
		},
		noCache: true,
		forceRm: true,
		pull:    true,
	}

	return docker, nil
}

func (docker *dockerCmd) Build(ctx context.Context, contextDirectory, imagePath string, args map[string]*string) error {
	dockerfile := defaultDockerfile

	buildCtx, err := CreateTar(contextDirectory, dockerfile)
	if err != nil {
		return err
	}
	defer buildCtx.Close()

	response, err := docker.cli.ImageBuild(ctx, buildCtx, types.ImageBuildOptions{
		Tags:        []string{imagePath},
		NoCache:     docker.noCache,
		Remove:      true,
		ForceRemove: docker.forceRm,
		PullParent:  docker.pull,
		Dockerfile:  defaultDockerfile,
		AuthConfigs: docker.registryAuthMap,
		BuildArgs:   args,
	})
	defer response.Body.Close()
	if err != nil {
		return err
	}

	//body, err := ioutil.ReadAll(response.Body)
	if err = detectErrorMessage(response.Body); err != nil {
		return err
	}

	return nil
}

func (docker *dockerCmd) Pull(ctx context.Context, imagePath string) error {
	resp, err := docker.cli.ImagePull(ctx, imagePath, types.ImagePullOptions{
	//RegistryAuth: docker.registryAuthString,
	})
	if resp != nil {
		defer resp.Close()
	}
	if err != nil {
		return err
	}
	if err = detectErrorMessage(resp); err != nil {
		return err
	}

	return nil
}

func (docker *dockerCmd) Push(ctx context.Context, imagePath string) error {
	resp, err := docker.cli.ImagePush(ctx, imagePath, types.ImagePushOptions{
		RegistryAuth: docker.registryAuthString,
	})
	if resp != nil {
		defer resp.Close()
	}
	if err != nil {
		return err
	}
	//body, err := ioutil.ReadAll(resp)
	if err = detectErrorMessage(resp); err != nil {
		return err
	}

	return nil
}

func (docker *dockerCmd) List(ctx context.Context, filter map[string]string) ([]*ImageSummary, error) {
	args := filters.NewArgs()
	for k, v := range filter {
		args.Add(k, v)
	}
	imageSummaryList, err := docker.cli.ImageList(ctx, types.ImageListOptions{
		Filters: args,
	})
	if err != nil {
		return nil, err
	}
	var imageSummaryPointerList []*ImageSummary
	for _, summary := range imageSummaryList {
		imageSummaryPointerList = append(imageSummaryPointerList, &ImageSummary{
			Containers:  summary.Containers,
			Created:     summary.Created,
			ID:          summary.ID,
			Labels:      summary.Labels,
			ParentID:    summary.ParentID,
			RepoDigests: summary.RepoDigests,
			RepoTags:    summary.RepoTags,
			SharedSize:  summary.SharedSize,
			Size:        summary.Size,
			VirtualSize: summary.VirtualSize,
		})
	}
	return imageSummaryPointerList, nil
}
func (docker *dockerCmd) Tag(ctx context.Context, imagePath, newImagePath string) error {
	err := docker.cli.ImageTag(ctx, imagePath, newImagePath)
	if err != nil {
		return err
	}
	return nil
}
func (docker *dockerCmd) Rmi(ctx context.Context, imagePath string) error {
	_, err := docker.cli.ImageRemove(ctx, imagePath, types.ImageRemoveOptions{})
	if err != nil {
		return err
	}
	return nil
}

// CreateTar create a build context tar for the specified project and service name.
func CreateTar(contextDirectory, dockerfile string) (io.ReadCloser, error) {
	dockerfileName := filepath.Join(contextDirectory, dockerfile)

	absContextDirectory, err := filepath.Abs(contextDirectory)
	if err != nil {
		return nil, err
	}

	filename := dockerfileName

	if dockerfile == "" {
		dockerfileName = defaultDockerfile
		filename = filepath.Join(absContextDirectory, dockerfileName)

		// Just to be nice ;-) look for 'dockerfile' too but only
		// use it if we found it, otherwise ignore this check
		if _, err = os.Lstat(filename); os.IsNotExist(err) {
			tmpFN := path.Join(absContextDirectory, strings.ToLower(dockerfileName))
			if _, err = os.Lstat(tmpFN); err == nil {
				dockerfileName = strings.ToLower(dockerfileName)
				filename = tmpFN
			}
		}
	}

	origDockerfile := dockerfileName // used for error msg
	if filename, err = filepath.Abs(filename); err != nil {
		return nil, err
	}

	// Now reset the dockerfileName to be relative to the build context
	dockerfileName, err = filepath.Rel(absContextDirectory, filename)
	if err != nil {
		return nil, err
	}

	// And canonicalize dockerfile name to a platform-independent one
	dockerfileName, err = archive.CanonicalTarNameForPath(dockerfileName)
	if err != nil {
		return nil, fmt.Errorf("Cannot canonicalize dockerfile path %s: %v", dockerfileName, err)
	}

	if _, err = os.Lstat(filename); os.IsNotExist(err) {
		return nil, fmt.Errorf("Cannot locate Dockerfile: %s", origDockerfile)
	}
	var includes = []string{"."}
	var excludes []string

	dockerIgnorePath := path.Join(contextDirectory, ".dockerignore")
	dockerIgnore, err := os.Open(dockerIgnorePath)
	if err != nil {
		if !os.IsNotExist(err) {
			return nil, err
		}
		excludes = make([]string, 0)
	} else {
		excludes, err = dockerignore.ReadAll(dockerIgnore)
		if err != nil {
			return nil, err
		}
	}

	// If .dockerignore mentions .dockerignore or the Dockerfile
	// then make sure we send both files over to the daemon
	// because Dockerfile is, obviously, needed no matter what, and
	// .dockerignore is needed to know if either one needs to be
	// removed.  The deamon will remove them for us, if needed, after it
	// parses the Dockerfile.
	keepThem1, _ := fileutils.Matches(".dockerignore", excludes)
	keepThem2, _ := fileutils.Matches(dockerfileName, excludes)
	if keepThem1 || keepThem2 {
		includes = append(includes, ".dockerignore", dockerfileName)
	}

	if err := builder.ValidateContextDirectory(contextDirectory, excludes); err != nil {
		return nil, fmt.Errorf("Error checking context is accessible: '%s'. Please check permissions and try again.", err)
	}

	options := &archive.TarOptions{
		Compression:     archive.Uncompressed,
		ExcludePatterns: excludes,
		IncludeFiles:    includes,
	}

	return archive.TarWithOptions(contextDirectory, options)
}

func detectErrorMessage(in io.Reader) error {
	dec := json.NewDecoder(in)

	for {
		var jm jsonmessage.JSONMessage
		if err := dec.Decode(&jm); err != nil {
			if err == io.EOF {
				break
			}
			return err
		}
		//log.Printf("docker resp: %+v", jm)
		// skip progress message
		//if jm.Progress == nil {
		//glog.Infof("%v", jm)
		//}
		if jm.Error != nil {
			return jm.Error
		}

		if len(jm.ErrorMessage) > 0 {
			return errors.New(jm.ErrorMessage)
		}
	}
	return nil
}

redpajama_set_name: RedPajamaGithub


text:
package org;

import org.bo.Customer;
import org.bo.User;
import org.ujorm.implementation.orm.OrmTable;
import org.ujorm.implementation.orm.RelationToMany;
import org.ujorm.orm.annot.Db;
import org.ujorm.orm.dialect.*;

/**
 * An table mapping to a database (a sample of usage).
 * @hidden
 */
@Db(schema="db1", dialect=H2Dialect.class, user="sa", password="", jdbcUrl="jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1")
//@Db(schema="db1", dialect=PostgreSqlDialect.class, user="sa", password="sa", jdbcUrl="jdbc:postgresql://127.0.0.1:5432/db1")
//@Db(schema="db1", dialect=DerbyDialect.class, user="sa", password="", jdbcUrl="jdbc:derby:C:\\temp\\derby-sample;create=true")
//@Db(schema="db1", dialect=MySqlDialect.class, user="sa", password="sa", jdbcUrl="jdbc:mysql://127.0.0.1:3306/db1")
//@Db(schema="db1", dialect=HsqldbDialect.class, user="sa", password="", jdbcUrl="jdbc:hsqldb:mem:db1")
//@Db(schema= ""  , dialect=FirebirdDialect.class, user="sysdba", password="masterkey", jdbcUrl="jdbc:firebirdsql:localhost/3050:c:\\progra~1\\firebird\\db\\db1.fdb?lc_ctype=UTF8")
//@Db(schema="db1", dialect=OracleDialect.class, user="sa", password="", jdbcUrl="jdbc:oracle:thin:@myhost:1521:orcl")
public class Database extends OrmTable<Database> {

    /** User */
    public static final RelationToMany<Database,User> users = newRelation();

    /** Customer extends User */
    public static final RelationToMany<Database,Customer> customers = newRelation();

}


text:
package net.violet.vadmin.objects.data;

public class TagTmpData {

	private String tagTmp_type;
	private String tagTmp_lastDay;
	private String tagTmp_ip;

	public TagTmpData(String inType, String inLastDay, String inIP){
		this.tagTmp_type = inType;
		this.tagTmp_lastDay = inLastDay;
		this.tagTmp_ip = inIP;
	}

	public String getTagTmp_type() {
		return this.tagTmp_type;
	}

	public void setTagTmp_type(String tagTmp_type) {
		this.tagTmp_type = tagTmp_type;
	}

	public String getTagTmp_lastDay() {
		return this.tagTmp_lastDay;
	}

	public void setTagTmp_lastDay(String tagTmp_lastDay) {
		this.tagTmp_lastDay = tagTmp_lastDay;
	}

	public String getTagTmp_ip() {
		return this.tagTmp_ip;
	}

	public void setTagTmp_ip(String tagTmp_ip) {
		this.tagTmp_ip = tagTmp_ip;
	}

}


text:
#include "bytecode/bytecode.h"
#include "bytecode/opcodes.h"
#include "select/propset.h"
#include "select/propget.h"
#include "utils/utils.h"

#include "select/properties/properties.h"
#include "select/properties/helpers.h"

css_error css__cascade_min_width(uint32_t opv, css_style *style,
		css_select_state *state)
{
	return css__cascade_length(opv, style, state, set_min_width);
}

css_error css__set_min_width_from_hint(const css_hint *hint,
		css_computed_style *style)
{
	return set_min_width(style, hint->status,
			hint->data.length.value, hint->data.length.unit);
}

css_error css__initial_min_width(css_select_state *state)
{
	return set_min_width(state->computed, CSS_MIN_WIDTH_SET, 0, CSS_UNIT_PX);
}

css_error css__compose_min_width(const css_computed_style *parent,
		const css_computed_style *child,
		css_computed_style *result)
{
	css_fixed length = 0;
	css_unit unit = CSS_UNIT_PX;
	uint8_t type = get_min_width(child, &length, &unit);

	if (type == CSS_MIN_WIDTH_INHERIT) {
		type = get_min_width(parent, &length, &unit);
	}

	return set_min_width(result, type, length, unit);
}


text:
/**
 *
 * Creare order and wait for order approve message
 *
 */
var path = require('path'),
    fs = require('fs'),
    childProcess = require('child_process'),
    slimerjs = require('slimerjs'),
    binPath = slimerjs.path,
    later = require('later'),
    Imap = require('imap'),
    inspect = require('util').inspect,
    moment = require('moment'),
    sendAlert = require('./lib/mailer'),
    mail_config = require('./config.json');

var mail_checker_schedule = null,
    mail_checker_schedule_abort_controller = null,
    childArgs = [path.join(__dirname, 'order-creator.js')],
    STATE_OK = false;

var log = function(msg) {
    fs.appendFile('log/info.log', "[" + moment().format('Y-M-D hh:mm:ss') + "] ~ " + msg + "\n");
}

var createOrder = function() {
    log('create order');
    STATE_OK = false;
    /** some code to create order */
    childProcess.execFileSync(binPath, childArgs);
    mail_checker_schedule = later.setInterval(checkMail, later.parse.text('every 1 minute'));
    mail_checker_schedule_abort_controller = later.setTimeout(function(){
        log('20 minute elapsed. STATE_OK=' + STATE_OK);
        mail_checker_schedule.clear();// stop checker after 20 min
        if (!STATE_OK) {
            fs.writeFileSync('res/error.log', 'error!');
            sendAlert();
        }
    }, later.parse.text('every 20 minute'));
}

var checkMail = function() {
    log('check mail');
    var imap = new Imap({
        user: mail_config.user,
        password: mail_config.password,
        host: mail_config.imap,
        port: mail_config.imap_port,
        tls: mail_config.imap_tls
    });

    function openInbox(cb) {
        imap.openBox('INBOX', true, cb);
    }

    imap.once('ready', function() {
        openInbox(function(err, box) {
            if (err) throw err;
            var f = imap.seq.fetch('1:3', {
                bodies: 'HEADER.FIELDS (FROM TO SUBJECT DATE)',
                struct: true
            });
            f.on('message', function(msg, seqno) { // handle incoming message
                console.log('Message #%d', seqno);
                var prefix = '(#' + seqno + ') ';
                msg.on('body', function(stream, info) {
                    var buffer = '';
                    stream.on('data', function(chunk) {
                        buffer += chunk.toString('utf8');
                    });
                    stream.once('end', function() {
                        // console.log(prefix + 'Parsed header: %s', inspect(Imap.parseHeader(buffer)));
                        var headers = Imap.parseHeader(buffer);
                        var subj = headers.subject[0];
                        var from = headers.from[0];
                        var date = parseInt(moment(new Date(headers.date[0])).toNow('m'));
                        log('subj=' + subj);
                        if (/game\@questoria\.ru/.test(from) && date < 20) {
                                log('matched!');
                                mail_checker_schedule.clear();// тушим таймер
                                if (mail_checker_schedule_abort_controller) {
                                    mail_checker_schedule_abort_controller.clear();
                                }
                                fs.writeFileSync('res/tmp.txt', "ok\n");
                                STATE_OK = true;
                        }
                    });
                });
                msg.once('end', function() {
                    console.log(prefix + 'Finished');
                });
            });
            f.once('error', function(err) {
                console.log('Fetch error: ' + err);
            });
            f.once('end', function() {
                console.log('Done fetching all messages!');
                imap.end();
            });
        });
    });

    imap.once('error', function(err) {
        console.log(err);
    });

    imap.once('end', function() {
        console.log('Connection ended');
    });

    imap.connect();
}

setInterval(createOrder, 7200 * 1000);


text:
#pragma once

#include "paddle/phi/backends/all_context.h"
#include "paddle/phi/core/kernel_registry.h"
#include "paddle/phi/kernels/erf_kernel.h"
#include "paddle/phi/kernels/funcs/eigen/common.h"
#include "paddle/phi/kernels/funcs/eigen/eigen_function.h"

namespace phi {

template <typename T, typename Context>
void ErfKernel(const Context& dev_ctx, const DenseTensor& x, DenseTensor* out) {
  dev_ctx.template Alloc<T>(out);

  auto eigen_out = EigenVector<T>::Flatten(*out);
  auto eigen_in = EigenVector<T>::Flatten(x);
  auto& place = *dev_ctx.eigen_device();
  phi::funcs::EigenErf<std::decay_t<decltype(place)>, T>::Eval(
      place, eigen_out, eigen_in);
}

}  // namespace phi


text:
package org.perfcake.idea.editor.components;

import com.intellij.util.xml.ui.BasicDomElementComponent;
import org.perfcake.idea.editor.actions.EditAction;
import org.perfcake.idea.editor.actions.PropertyAddAction;
import org.perfcake.idea.editor.actions.ReporterAddAction;
import org.perfcake.idea.editor.colors.ColorType;
import org.perfcake.idea.editor.dragndrop.ComponentTransferHandler;
import org.perfcake.idea.editor.dragndrop.DropAction;
import org.perfcake.idea.editor.dragndrop.PropertyDropAction;
import org.perfcake.idea.editor.dragndrop.ReporterDropAction;
import org.perfcake.idea.editor.menu.ActionType;
import org.perfcake.idea.editor.menu.PopClickListener;
import org.perfcake.idea.editor.swing.JPerfCakeIdeaRectangle;
import org.perfcake.idea.model.Reporter;
import org.perfcake.idea.model.Reporting;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;

/**
 * Created by miron on 21.10.2014.
 */
public class ReportingComponent extends BasicDomElementComponent<Reporting> {

    private static final String TITLE = "Reporting";

    private JPerfCakeIdeaRectangle reportingGui;

    public ReportingComponent(Reporting domElement) {
        super((Reporting) domElement.createStableCopy());

        reportingGui = new JPerfCakeIdeaRectangle(TITLE, ColorType.REPORTING_FOREGROUND, ColorType.REPORTING_BACKGROUND);

        createSetActions();

        reportingGui.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    reportingGui.getActionMap().get(ActionType.EDIT).actionPerformed(new ActionEvent(e.getSource(), ActionEvent.ACTION_PERFORMED, null));
                }
            }
        });
        reportingGui.addMouseListener(new PopClickListener(getDomElement(), getComponent()));

        //set dropping from toolbar to this component
        HashMap<String, DropAction> prefixDropActions = new HashMap<>();
        prefixDropActions.put("Reporters", new ReporterDropAction(getDomElement()));
        prefixDropActions.put("Properties", new PropertyDropAction(getDomElement()));
        reportingGui.setTransferHandler(new ComponentTransferHandler(prefixDropActions));

        addReporters();
    }

    private void createSetActions() {
        ActionMap actionMap = new ActionMap();

        ReporterAddAction addAction = new ReporterAddAction(getDomElement(), getComponent());
        PropertyAddAction addAction2 = new PropertyAddAction(getDomElement(), getComponent());

        EditAction editAction = new EditAction<Reporting>("Edit Reporting", getDomElement(), getComponent());

        actionMap.put(ActionType.ADD, addAction);
        actionMap.put(ActionType.ADD2, addAction2);
        actionMap.put(ActionType.EDIT, editAction);

        reportingGui.setActionMap(actionMap);
    }

    @Override
    public JComponent getComponent() {
        return reportingGui;
    }

    private void addReporters() {
        if (getDomElement().isValid()) {
            for (Reporter r : getDomElement().getReporters()) {
                ReporterComponent reporterComponent = new ReporterComponent(r);
                addComponent(reporterComponent);
                reportingGui.addComponent(reporterComponent.getComponent());
            }
        }
    }

    @Override
    public void reset() {
        super.reset();
        getChildren().clear();
        reportingGui.removeAllComponents();

        addReporters();
    }
}


text:
    {% if paginator.previous_page %}
        {% if paginator.previous_page == 1 %}
            « Mais recentes
        {% else %}
            « Mais recentes
      {% endif %}
    {% endif %}
     Page {{paginator.page}} of {{paginator.total_pages}}
    {% if paginator.next_page %}
        Mais antigos »
    {% endif %}


text:
package com.graphhopper.routing;

import com.carrotsearch.hppc.cursors.IntCursor;
import com.graphhopper.routing.querygraph.QueryGraph;
import com.graphhopper.util.Parameters;
import com.graphhopper.util.StopWatch;

import java.util.Collections;
import java.util.List;

import static com.graphhopper.util.EdgeIterator.ANY_EDGE;

public class FlexiblePathCalculator implements PathCalculator {
    private final QueryGraph queryGraph;
    private final RoutingAlgorithmFactory algoFactory;
    private AlgorithmOptions algoOpts;
    private String debug;
    private int visitedNodes;

    public FlexiblePathCalculator(QueryGraph queryGraph, RoutingAlgorithmFactory algoFactory, AlgorithmOptions algoOpts) {
        this.queryGraph = queryGraph;
        this.algoFactory = algoFactory;
        this.algoOpts = algoOpts;
    }

    @Override
    public List<Path> calcPaths(int from, int to, EdgeRestrictions edgeRestrictions) {
        RoutingAlgorithm algo = createAlgo();
        return calcPaths(from, to, edgeRestrictions, algo);
    }

    private RoutingAlgorithm createAlgo() {
        StopWatch sw = new StopWatch().start();
        RoutingAlgorithm algo = algoFactory.createAlgo(queryGraph, algoOpts);
        debug = ", algoInit:" + (sw.stop().getNanos() / 1000) + " μs";
        return algo;
    }

    private List<Path> calcPaths(int from, int to, EdgeRestrictions edgeRestrictions, RoutingAlgorithm algo) {
        StopWatch sw = new StopWatch().start();
        // todo: so far 'heading' is implemented like this: we mark the unfavored edges on the query graph and then
        // our weighting applies a penalty to these edges. however, this only works for virtual edges and to make
        // this compatible with edge-based routing we would have to use edge keys instead of edge ids. either way a
        // better approach seems to be making the weighting (or the algorithm for that matter) aware of the unfavored
        // edges directly without changing the graph
        for (IntCursor c : edgeRestrictions.getUnfavoredEdges())
            queryGraph.unfavorVirtualEdge(c.value);

        List<Path> paths;
        if (edgeRestrictions.getSourceOutEdge() != ANY_EDGE || edgeRestrictions.getTargetInEdge() != ANY_EDGE) {
            if (!(algo instanceof BidirRoutingAlgorithm))
                throw new IllegalArgumentException("To make use of the " + Parameters.Routing.CURBSIDE + " parameter you need a bidirectional algorithm, got: " + algo.getName());
            paths = Collections.singletonList(((BidirRoutingAlgorithm) algo).calcPath(from, to, edgeRestrictions.getSourceOutEdge(), edgeRestrictions.getTargetInEdge()));
        } else {
            paths = algo.calcPaths(from, to);
        }

        // reset all direction enforcements in queryGraph to avoid influencing next path
        // todo: is this correct? aren't we taking a second look at these edges later when we calc times or
        // instructions etc.?
        queryGraph.clearUnfavoredStatus();

        if (paths.isEmpty())
            throw new IllegalStateException("Path list was empty for " + from + " -> " + to);
        if (algo.getVisitedNodes() >= algoOpts.getMaxVisitedNodes())
            throw new IllegalArgumentException("No path found due to maximum nodes exceeded " + algoOpts.getMaxVisitedNodes());
        visitedNodes = algo.getVisitedNodes();
        debug += ", " + algo.getName() + "-routing:" + sw.stop().getMillis() + " ms";
        return paths;
    }

    @Override
    public String getDebugString() {
        return debug;
    }

    @Override
    public int getVisitedNodes() {
        return visitedNodes;
    }

    public AlgorithmOptions getAlgoOpts() {
        return algoOpts;
    }

    public void setAlgoOpts(AlgorithmOptions algoOpts) {
        this.algoOpts = algoOpts;
    }
}


text:
/**
 * @author mrdoob / http://mrdoob.com/
 */

THREE.OriginalImageLoader = THREE.ImageLoader;

THREE.DropboxImageLoader = function ( manager ) {
	this.realImageLoader = new THREE.OriginalImageLoader( manager );
	this.urlTranslator = new THREE.DropboxURLTranslation();

};

THREE.DropboxImageLoader.prototype = {

	constructor: THREE.DropboxImageLoader,

	load: function ( url, onLoad, onProgress, onError ) {
		var newUrl = this.urlTranslator.translate(url);
		console.log('DropboxImageLoader :: url = ' + url + ' -> ' + newUrl);
		return this.realImageLoader.load(newUrl, onLoad, onProgress, onError);
	},

	setCrossOrigin: function ( value ) {
		return this.realImageLoader.setCrossOrigin(value);
	}

};

THREE.ImageLoader = THREE.DropboxImageLoader;


text:
package simpledesign.section7ProceduralPolymorphism;

import static org.junit.Assert.*;

import org.junit.Test;

public class CellTest {

	@Test
	public void aDeadCellShouldStayDeadWithLessThan3LiveNeighbors() {
		assertFalse(Cell.DeadCell().isAliveInNextGeneration(0));
	}

	@Test
   public void aDeadCellShouldComeAliveWith3LiveNeighbors() throws Exception {
		assertTrue(Cell.DeadCell().isAliveInNextGeneration(3));
   }

	@Test
   public void aLiveCellShouldDieWithFewerThan2LiveNeighbors() throws Exception {
	   assertFalse(Cell.LiveCell().isAliveInNextGeneration(1));
   }

	@Test
   public void aLiveCellShouldDieWithMoreThan3LiveNeighbors() throws Exception {
	   assertFalse(Cell.LiveCell().isAliveInNextGeneration(4));
   }

	@Test
   public void aLiveCellWith2LiveNeighborsShouldLiveOn() throws Exception {
	   assertTrue(Cell.LiveCell().isAliveInNextGeneration(2));
   }

	@Test
   public void aLiveCellWith3LiveNeighborsShouldLiveOn() throws Exception {
	   assertTrue(Cell.LiveCell().isAliveInNextGeneration(3));
   }
}


text:
import quex.core_engine.generator.state_machine_coder as state_machine_coder
from   quex.core_engine.generator.state_machine_decorator import StateMachineDecorator
from   quex.frs_py.string_handling import blue_print

function_str = """
#include <quex/code_base/temporary_macros_on>
QUEX_INLINE void
PAPC_input_postion_backward_detector_$$ID$$(QuexAnalyser* me)
{
$$LOCAL_VARIABLES$$
$$STATE_MACHINE$$
$$FUNCTION_BODY$$
}
#include <quex/code_base/temporary_macros_off>
"""

def do(sm, LanguageDB, PrintStateMachineF):

    decorated_state_machine = StateMachineDecorator(sm,
                                                    "BACKWARD_DETECTOR_" + repr(sm.get_id()),
                                                    PostContextSM_ID_List = [],
                                                    BackwardLexingF=True,
                                                    BackwardInputPositionDetectionF=True)

    function_body = state_machine_coder.do(decorated_state_machine)

    sm_str = "    " + LanguageDB["$comment"]("state machine") + "\n"
    if PrintStateMachineF:
        sm_str += LanguageDB["$ml-comment"](sm.get_string(NormalizeF=False)) + "\n"

    # -- input position detectors simply the next 'catch' and return
    function_body += LanguageDB["$label-def"]("$terminal-general", True) + "\n"
    function_body += LanguageDB["$input/seek_position"]("end_of_core_pattern_position") + "\n"
    function_body += LanguageDB["$input/increment"] + "\n"

    variables_txt = LanguageDB["$local-variable-defs"](
            [["QUEX_CHARACTER_TYPE",          "input",                        "(QUEX_CHARACTER_TYPE)(0x0)"],
             ["QUEX_CHARACTER_POSITION_TYPE", "end_of_core_pattern_position", "(QUEX_CHARACTER_TYPE*)(0x0)"]])

    return blue_print(function_str,
                      [["$$ID$$",              repr(sm.get_id()).replace("L", "")],
                       ["$$FUNCTION_BODY$$",   function_body],
                       ["$$LOCAL_VARIABLES$$", variables_txt],
                       ["$$STATE_MACHINE$$",   sm_str],
                      ])


text:
<?php

require_once "../config.php";
require_once "data/data_util.php";
require_once "data/names.php";
require_once "data/locations.php";

use \Tsugi\Core\LTIX;
use \Tsugi\Util\LTI;
use \Tsugi\Util\Net;

$LAUNCH = LTIX::requireData();
$p = $CFG->dbprefix;

if ( ! $USER->instructor ) die('Must be instructor');

$sanity = array(
  'urllib' => 'You should use urllib to retrieve the data from the API',
  'urlencode' => 'You should use urlencode add parameters to the API url',
  'json' => 'You should use the json library to parse the API data'
);

echo("
\n");
echo("Running test...\n");
// Run though all the locations
// var_dump($LOCATIONS);
$url = LTIX::curPageUrlScript();
$i = 500;
foreach ($LOCATIONS as $key => $location) {
    // echo(htmlentities($location)."\n");
    $api_url = str_replace('geo_test.php','data/geojson',$url);
    $sample_url = $api_url . '?sensor=false&address=' . urlencode($location);
    $sample_data = Net::doGet($sample_url);
    $sample_count = strlen($sample_data);
    $response = Net::getLastHttpResponse();
    $sample_json = json_decode($sample_data);
    if ( $response != 200 || $sample_json == null || ( !isset($sample_json->results[0])) ) {
        echo("*** Bad response=$response url=$sample_url json_error=".json_last_error_msg()."\n");
        echo(LTI::jsonIndent($sample_data));
        continue;
    }
    // echo("
\n");echo(\Tsugi\Util\LTI::jsonIndent(json_encode($sample_json)));echo("
\n");
    if ( !isset($sample_json->results[0]->place_id) ) {
        echo("*** Could not find place_id $location\n");
        // echo(\Tsugi\Util\LTI::jsonIndent($sample_data));
        continue;
    }
    $sample_place =  $sample_json->results[0]->place_id;
    echo("location=$location place=$sample_place\n");
    if ( $i-- < 1 ) break;
}
echo("
\n");


text:
var SauceConnect = require('./lib/sauce_connect');
var SauceLauncher = require('./lib/sauce_launcher');
var SauceReporter = require('./lib/sauce_reporter');

// PUBLISH DI MODULE
module.exports = {
  'sauceConnect': ['type', SauceConnect],
  'launcher:SauceLabs': ['type', SauceLauncher],
  'reporter:saucelabs': ['type', SauceReporter],

  // We keep a mapping from Karma launch IDs to Sauce job IDs here, to report the pass/fail results.
  // We also keep the Sauce credentials here - theoretically different credentials can be used for
  // different browsers in the same session.
  'sauce:jobMapping': ['value', {}]
};