text:
package com.pingan.listviewdemo;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.util.LruCache;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Author:liupeng on 2017/08/27 15:41
 * Address:liupeng502@pingan.com.cn
 * 使用tagflag 实现异步加载而不会乱
 */
public class ImageAdapter2 extends ArrayAdapter<String> {

    private LruCache<String, BitmapDrawable> mLruCache;
    private ListView                         mListview;

    public ImageAdapter2(Context context, int resource, String[] objects) {
        super(context, resource, objects);
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 8;

        mLruCache = new LruCache<String, BitmapDrawable>(cacheSize) {
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                return value.getBitmap().getByteCount();
            }
        };
    }

    /*public ImageAdapter(Context context, int resource, int textViewResourceId) {
        super(context, resource, textViewResourceId);
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 8;

        mLruCache = new LruCache<String, BitmapDrawable>(cacheSize) {
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                return value.getBitmap().getByteCount();
            }
        };
    }*/

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        /*增加 findViewwithFlag */
        if (mListview == null) {
            mListview = (ListView) parent;
        }
        String url = getItem(position);
        View view;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(R.layout.item, null);
        } else {
            view = convertView;
        }
        ImageView image = (ImageView) view.findViewById(R.id.image);
        image.setImageResource(R.mipmap.ic_launcher);
        image.setTag(url); //设置tag标止
        BitmapDrawable drawable = getBitmapFromMemoryCache(url);
        if (drawable != null) {
            image.setImageDrawable(drawable);
        } else {
            BitmapWorkerTask task = new BitmapWorkerTask(image);
            task.execute(url);
        }
        return view;
    }

    /**
     * 将一张图片存储到LruCache中。
     *
     * @param key      LruCache的键,这里传入图片的URL地址。
     * @param drawable LruCache的值,这里传入从网络上下载的BitmapDrawable对象。
     */
    public void addBitmapToMemoryCache(String key, BitmapDrawable drawable) {
        if (key == null) {
            mLruCache.put(key, drawable);
        }
    }

    /**
     * 从LruCache中获取一张图片,如果不存在就返回null。
     *
     * @param key LruCache的键,这里传入图片的URL地址。
     * @return 对应传入键的BitmapDrawable对象,或者null。
     */
    public BitmapDrawable getBitmapFromMemoryCache(String key) {
        return mLruCache.get(key);
    }

    /**
     * 建立HTTP请求,并获取Bitmap对象。
     *
     * @param
     * @return 解析后的Bitmap对象
     */
    private class BitmapWorkerTask extends AsyncTask<String, Void, BitmapDrawable> {

        private ImageView mImageView;
        private String mImageUrl;

        public BitmapWorkerTask(ImageView imageView) {
            super();
            //mImageView = imageView;
        }

        @Override
        protected BitmapDrawable doInBackground(String... strings) {
            mImageUrl = strings[0];
            Bitmap bitmap = downloadBitmap(mImageUrl);
            BitmapDrawable drawable = new BitmapDrawable(getContext().getResources(), bitmap);
            addBitmapToMemoryCache(mImageUrl, drawable);
            return drawable;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(BitmapDrawable drawable) {
            // 获取标志
            ImageView imageview = (ImageView) mListview.findViewWithTag(mImageUrl);
            if (imageview != null && drawable != null) {
                imageview.setImageDrawable(drawable);
            }
        }

        private Bitmap downloadBitmap(String imageUrl) {
            Bitmap bitmap = null;
            HttpURLConnection con = null;
            try {
                URL url = new URL(imageUrl);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(10 * 1000);
                bitmap = BitmapFactory.decodeStream(con.getInputStream());
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
            }
            return bitmap;
        }
    }
}


text:
@implementation Amplitude (Test)

@dynamic backgroundQueue;
@dynamic initializerQueue;
@dynamic eventsData;
@dynamic initialized;
@dynamic sessionId;
@dynamic lastEventTime;

- (void)flushQueue {
    [self flushQueueWithQueue:[self backgroundQueue]];
}

- (void)flushQueueWithQueue:(NSOperationQueue*) queue {
    [queue waitUntilAllOperationsAreFinished];
}

- (NSDictionary *)getEvent:(NSInteger) fromEnd {
    NSArray *events = [self eventsData][@"events"];
    return [events objectAtIndex:[events count] - fromEnd - 1];
}

- (NSDictionary *)getLastEvent {
    return [[self eventsData][@"events"] lastObject];
}

- (NSUInteger)queuedEventCount {
    return [[self eventsData][@"events"] count];
}

- (void)flushUploads:(void (^)())handler {
    [self performSelector:@selector(uploadEvents)];
    [self flushQueue];

    // Wait a second for the upload response to get into the queue.
    dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, 2.0 * NSEC_PER_SEC);
    dispatch_after(delay, dispatch_get_main_queue(), ^(void){
        [self flushQueue];
        handler();
    });
}

@end

redpajama_set_name: RedPajamaGithub


text:
void hzero_(void *out, size_t size, const char *file, int line) {
        hostErrCheck_(hostMemset(out, 0, size), file, line);
}

#define dzero(out, size) { dzero_((out), (size), __FILE__, __LINE__); }
void dzero_(void *out, size_t size, const char *file, int line) {
        cudaErrCheck_(cudaMemset(out, 0, size), file, line);
}


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>DIHCache (Solr 6.3.0 API)</title>
<meta name="date" content="2016-11-02">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.solr.handler.dataimport

Interface DIHCache

All Superinterfaces:

Iterable<Map<String,Object>>

All Known Implementing Classes:

SortedMapBackedCache

public interface DIHCache
extends Iterable<Map<String,Object>>

 A cache that allows a DIH entity's data to persist locally prior being joined
 to other data and/or indexed.

WARNING: This API is experimental and might change in incompatible ways in the next release.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

void
add(Map<String,Object> rec)

 Adds a document.

void
close()

 Releases resources used by this cache, if possible.

void
delete(Object key)

 Delete all documents associated with the given key

void
deleteAll()

 Delete all data from the cache,leaving the empty cache intact.

void
destroy()

 Closes the cache, if open.

void
flush()

 Persists any pending data to the cache

Iterator<Map<String,Object>>
iterator()

 Returns an iterator, allowing callers to iterate through the entire cache
 in key, then insertion, order.

Iterator<Map<String,Object>>
iterator(Object key)

 Returns an iterator, allowing callers to iterate through all documents that
 match the given key in insertion order.

void
open(Context context)

 Opens the cache using the specified properties.

Methods inherited from interface java.lang.Iterable

forEach, spliterator

Method Detail

open

void open(Context context)

 Opens the cache using the specified properties. The Context
 includes any parameters needed by the cache impl. This must be called
 before any read/write operations are permitted.

close

void close()

 Releases resources used by this cache, if possible. The cache is flushed
 but not destroyed.

flush

void flush()

 Persists any pending data to the cache

destroy

void destroy()

 Closes the cache, if open. Then removes all data, possibly removing the
 cache entirely from persistent storage.

add

void add(Map<String,Object> rec)

 Adds a document. If a document already exists with the same key, both
 documents will exist in the cache, as the cache allows duplicate keys. To
 update a key's documents, first call delete(Object key).

iterator

Iterator<Map<String,Object>> iterator()

 Returns an iterator, allowing callers to iterate through the entire cache
 in key, then insertion, order.

Specified by:

iterator in interface Iterable<Map<String,Object>>

iterator

Iterator<Map<String,Object>> iterator(Object key)

 Returns an iterator, allowing callers to iterate through all documents that
 match the given key in insertion order.

delete

void delete(Object key)

 Delete all documents associated with the given key

deleteAll

void deleteAll()

 Delete all data from the cache,leaving the empty cache intact.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

          Copyright © 2000-2016 Apache Software Foundation.  All Rights Reserved.


text:
<openerp>
    <data>

    <record id="view_partner_property_form" model="ir.ui.view">
            <field name="name">res.partner.purchase.property.form.inherit</field>
            <field name="model">res.partner</field>
            <field name="inherit_id" ref="base.view_partner_form"/>
            <field name="priority">36</field>
            <field name="groups_id" eval="[(4, ref('base.group_multi_currency'))]"/>
            <field name="arch" type="xml">
                <group name="purchase" position="inside">
                    <field name="property_purchase_currency_id"/>
                </group>
            </field>
    </record>
    <record id="act_res_partner_2_purchase_order" model="ir.actions.act_window">
            <field name="name">RFQs and Purchases</field>
            <field name="res_model">purchase.order</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form,graph</field>
            <field name="context">{'search_default_partner_id': active_id}</field>
            <field name="groups_id" eval="[(4, ref('purchase.group_purchase_user'))]"/>
            <field name="help" type="html">

                    This vendor has no purchase order. Click to create a new RfQ.

                    The request for quotation is the first step of the purchases flow. Once
                    converted into a purchase order, you will be able to control the receipt
                    of the products and the vendor bill.

            </field>
        </record>

        <record model="ir.ui.view" id="purchase_partner_kanban_view">
            <field name="name">res.partner.kanban.purchaseorder.inherit</field>
            <field name="model">res.partner</field>
            <field name="inherit_id" ref="base.res_partner_kanban_view"/>
            <field name="groups_id" eval="[(4, ref('purchase.group_purchase_user'))]"/>
            <field name="arch" type="xml">
                <field name="mobile" position="after">
                    <field name="purchase_order_count"/>
                </field>
                <xpath expr="//div[@class='oe_kanban_partner_links']" position="inside">
                    0" class="badge"><t t-esc="record.purchase_order_count.value"/>
                </xpath>
            </field>
        </record>

    <record id="act_res_partner_2_supplier_invoices" model="ir.actions.act_window">
            <field name="name">Vendor Bills</field>
            <field name="res_model">account.invoice</field>
            <field name="view_type">form</field>
            <field name="view_mode">tree,form,graph</field>
            <field name="domain">[('type','=','in_invoice')]</field>
            <field name="context">{'search_default_partner_id': active_id, 'default_type': 'in_invoice', 'type': 'in_invoice', 'journal_type': 'purchase'}</field>
            <field name="help" type="html">

                    Click here to record a vendor bill.

                    Vendors bills can be pre-generated based on purchase
                    orders or receipts. This allows you to control bills
                    you receive from your vendor according to the draft
                    document in Odoo.

            </field>
        </record>

        <record id="res_partner_view_purchase_buttons" model="ir.ui.view">
            <field name="name">res.partner.view.purchase.buttons</field>
            <field name="model">res.partner</field>
            <field name="inherit_id" ref="base.view_partner_form" />
            <field name="priority" eval="20"/>
            <field name="groups_id" eval="[(4, ref('purchase.group_purchase_user'))]"/>
            <field name="arch" type="xml">

                    <button class="oe_stat_button" name="%(purchase.act_res_partner_2_purchase_order)d" type="action"
                        attrs="{'invisible': [('supplier', '=', False)]}" icon="fa-shopping-cart">
                        <field string="Purchases" name="purchase_order_count" widget="statinfo"/>
                    </button>

            </field>
        </record>

        <record id="res_partner_view_purchase_account_buttons" model="ir.ui.view">
            <field name="name">res.partner.view.purchase.account.buttons</field>
            <field name="model">res.partner</field>
            <field name="inherit_id" ref="base.view_partner_form" />
            <field name="priority" eval="20"/>
            <field name="groups_id" eval="[(4, ref('account.group_account_invoice'))]"/>
            <field name="arch" type="xml">

                    <button class="oe_stat_button" name="%(purchase.act_res_partner_2_supplier_invoices)d" type="action"
                        attrs="{'invisible': [('supplier', '=', False)]}" icon="fa-pencil-square-o" help="Vendor Bills">
                        <field string="Vendor Bills." name="supplier_invoice_count" widget="statinfo"/>
                    </button>

            </field>
        </record>
    </data>
</openerp>


text:
"use strict";

const IgnorePlugin = require("../../../../").IgnorePlugin;

module.exports = {
	entry: "./test.js",
	plugins: [
		new IgnorePlugin({
			resourceRegExp: /ignored-module/,
			contextRegExp: /folder-b/
		})
	]
};


text:
package org.pac4j.oauth.profile.facebook;

import java.util.Date;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.pac4j.oauth.profile.JsonObject;

import static org.pac4j.core.util.CommonHelper.newDate;

/**
 * This class represents a Facebook info (id + name + category + created_time).
 *
 * @author Jerome Leleu
 * @since 1.1.0
 */
public final class FacebookInfo extends JsonObject {

    private static final long serialVersionUID = -6023752317085418350L;

    private String id;

    private String category;

    private String name;

    @JsonProperty("created_time")
    @JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ssz")
    private Date createdTime;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getCategory() {
        return category;
    }

    public void setCategory(String category) {
        this.category = category;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreatedTime() {
        return newDate(createdTime);
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = newDate(createdTime);
    }
}


text:
package org.testcontainers.containers;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.core.LocalDirectorySSLConfig;
import com.github.dockerjava.transport.SSLConfig;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.Uninterruptibles;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;
import org.testcontainers.DockerClientFactory;
import org.testcontainers.containers.output.OutputFrame;
import org.testcontainers.containers.output.Slf4jLogConsumer;
import org.testcontainers.containers.startupcheck.IndefiniteWaitOneShotStartupCheckStrategy;
import org.testcontainers.containers.wait.strategy.Wait;
import org.testcontainers.containers.wait.strategy.WaitAllStrategy;
import org.testcontainers.containers.wait.strategy.WaitStrategy;
import org.testcontainers.dockerclient.TransportConfig;
import org.testcontainers.images.RemoteDockerImage;
import org.testcontainers.lifecycle.Startable;
import org.testcontainers.utility.AuditLogger;
import org.testcontainers.utility.Base58;
import org.testcontainers.utility.CommandLine;
import org.testcontainers.utility.DockerImageName;
import org.testcontainers.utility.DockerLoggerFactory;
import org.testcontainers.utility.ImageNameSubstitutor;
import org.testcontainers.utility.LogUtils;
import org.testcontainers.utility.MountableFile;
import org.testcontainers.utility.PathUtils;
import org.testcontainers.utility.ResourceReaper;
import org.zeroturnaround.exec.InvalidExitValueException;
import org.zeroturnaround.exec.ProcessExecutor;
import org.zeroturnaround.exec.stream.slf4j.Slf4jStream;

import java.io.File;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Container which launches Docker Compose, for the purposes of launching a defined set of containers.
 */
@Slf4j
public class DockerComposeContainer<SELF extends DockerComposeContainer<SELF>>
    extends FailureDetectingExternalResource
    implements Startable {

    /**
     * Random identifier which will become part of spawned containers names, so we can shut them down
     */
    private final String identifier;

    private final List<File> composeFiles;

    private DockerComposeFiles dockerComposeFiles;

    private final Map<String, Integer> scalingPreferences = new HashMap<>();

    private DockerClient dockerClient;

    private boolean localCompose;

    private boolean pull = true;

    private boolean build = false;

    private Set<String> options = new HashSet<>();

    private boolean tailChildContainers;

    private String project;

    private final AtomicInteger nextAmbassadorPort = new AtomicInteger(2000);

    private final Map<String, Map<Integer, Integer>> ambassadorPortMappings = new ConcurrentHashMap<>();

    private final Map<String, ComposeServiceWaitStrategyTarget> serviceInstanceMap = new ConcurrentHashMap<>();

    private final Map<String, WaitAllStrategy> waitStrategyMap = new ConcurrentHashMap<>();

    private final SocatContainer ambassadorContainer = new SocatContainer();

    private final Map<String, List<Consumer<OutputFrame>>> logConsumers = new ConcurrentHashMap<>();

    private static final Object MUTEX = new Object();

    private List<String> services = new ArrayList<>();

    /**
     * Properties that should be passed through to all Compose and ambassador containers (not
     * necessarily to containers that are spawned by Compose itself)
     */
    private Map<String, String> env = new HashMap<>();

    private RemoveImages removeImages;

    @Deprecated
    public DockerComposeContainer(File composeFile, String identifier) {
        this(identifier, composeFile);
    }

    public DockerComposeContainer(File... composeFiles) {
        this(Arrays.asList(composeFiles));
    }

    public DockerComposeContainer(List<File> composeFiles) {
        this(Base58.randomString(6).toLowerCase(), composeFiles);
    }

    public DockerComposeContainer(String identifier, File... composeFiles) {
        this(identifier, Arrays.asList(composeFiles));
    }

    public DockerComposeContainer(String identifier, List<File> composeFiles) {
        this.composeFiles = composeFiles;
        this.dockerComposeFiles = new DockerComposeFiles(composeFiles);

        // Use a unique identifier so that containers created for this compose environment can be identified
        this.identifier = identifier;
        this.project = randomProjectId();

        this.dockerClient = DockerClientFactory.lazyClient();
    }

    @Override
    @Deprecated
    public Statement apply(Statement base, Description description) {
        return super.apply(base, description);
    }

    @Override
    @Deprecated
    public void starting(Description description) {
        start();
    }

    @Override
    @Deprecated
    protected void succeeded(Description description) {}

    @Override
    @Deprecated
    protected void failed(Throwable e, Description description) {}

    @Override
    @Deprecated
    public void finished(Description description) {
        stop();
    }

    @Override
    public void start() {
        synchronized (MUTEX) {
            registerContainersForShutdown();
            if (pull) {
                try {
                    pullImages();
                } catch (ContainerLaunchException e) {
                    log.warn("Exception while pulling images, using local images if available", e);
                }
            }
            createServices();
            startAmbassadorContainers();
            waitUntilServiceStarted();
        }
    }

    private void pullImages() {
        // Pull images using our docker client rather than compose itself,
        // (a) as a workaround for https://github.com/docker/compose/issues/5854, which prevents authenticated image pulls being possible when credential helpers are in use
        // (b) so that credential helper-based auth still works when compose is running from within a container
        dockerComposeFiles
            .getDependencyImages()
            .forEach(imageName -> {
                try {
                    log.info(
                        "Preemptively checking local images for '{}', referenced via a compose file or transitive Dockerfile. If not available, it will be pulled.",
                        imageName
                    );
                    new RemoteDockerImage(DockerImageName.parse(imageName))
                        .withImageNameSubstitutor(ImageNameSubstitutor.noop())
                        .get();
                } catch (Exception e) {
                    log.warn(
                        "Unable to pre-fetch an image ({}) depended upon by Docker Compose build - startup will continue but may fail. Exception message was: {}",
                        imageName,
                        e.getMessage()
                    );
                }
            });
    }

    public SELF withServices(@NonNull String... services) {
        this.services = Arrays.asList(services);
        return self();
    }

    private void createServices() {
        // services that have been explicitly requested to be started. If empty, all services should be started.
        final String serviceNameArgs = Stream
            .concat(
                services.stream(), // services that have been specified with `withServices`
                scalingPreferences.keySet().stream() // services that are implicitly needed via `withScaledService`
            )
            .distinct()
            .collect(Collectors.joining(" "));

        // Apply scaling for the services specified using `withScaledService`
        final String scalingOptions = scalingPreferences
            .entrySet()
            .stream()
            .map(entry -> "--scale " + entry.getKey() + "=" + entry.getValue())
            .distinct()
            .collect(Collectors.joining(" "));

        String command = optionsAsString() + "up -d";

        if (build) {
            command += " --build";
        }

        if (!Strings.isNullOrEmpty(scalingOptions)) {
            command += " " + scalingOptions;
        }

        if (!Strings.isNullOrEmpty(serviceNameArgs)) {
            command += " " + serviceNameArgs;
        }

        // Run the docker-compose container, which starts up the services
        runWithCompose(command);
    }

    private String optionsAsString() {
        String optionsString = options.stream().collect(Collectors.joining(" "));
        if (optionsString.length() != 0) {
            // ensures that there is a space between the options and 'up' if options are passed.
            return optionsString + " ";
        } else {
            // otherwise two spaces would appear between 'docker-compose' and 'up'
            return StringUtils.EMPTY;
        }
    }

    private void waitUntilServiceStarted() {
        listChildContainers().forEach(this::createServiceInstance);

        Set<String> servicesToWaitFor = waitStrategyMap.keySet();
        Set<String> instantiatedServices = serviceInstanceMap.keySet();
        Sets.SetView<String> missingServiceInstances = Sets.difference(servicesToWaitFor, instantiatedServices);

        if (!missingServiceInstances.isEmpty()) {
            throw new IllegalStateException(
                "Services named " +
                missingServiceInstances +
                " " +
                "do not exist, but wait conditions have been defined " +
                "for them. This might mean that you misspelled " +
                "the service name when defining the wait condition."
            );
        }

        serviceInstanceMap.forEach(this::waitUntilServiceStarted);
    }

    private void createServiceInstance(Container container) {
        String serviceName = getServiceNameFromContainer(container);
        final ComposeServiceWaitStrategyTarget containerInstance = new ComposeServiceWaitStrategyTarget(
            dockerClient,
            container,
            ambassadorContainer,
            ambassadorPortMappings.getOrDefault(serviceName, new HashMap<>())
        );

        String containerId = containerInstance.getContainerId();
        if (tailChildContainers) {
            followLogs(containerId, new Slf4jLogConsumer(log).withPrefix(container.getNames()[0]));
        }
        //follow logs using registered consumers for this service
        logConsumers
            .getOrDefault(serviceName, Collections.emptyList())
            .forEach(consumer -> followLogs(containerId, consumer));
        serviceInstanceMap.putIfAbsent(serviceName, containerInstance);
    }

    private void waitUntilServiceStarted(String serviceName, ComposeServiceWaitStrategyTarget serviceInstance) {
        final WaitAllStrategy waitAllStrategy = waitStrategyMap.get(serviceName);
        if (waitAllStrategy != null) {
            waitAllStrategy.waitUntilReady(serviceInstance);
        }
    }

    private String getServiceNameFromContainer(Container container) {
        final String containerName = container.getLabels().get("com.docker.compose.service");
        final String containerNumber = container.getLabels().get("com.docker.compose.container-number");
        return String.format("%s_%s", containerName, containerNumber);
    }

    private void runWithCompose(String cmd) {
        Preconditions.checkNotNull(composeFiles);
        Preconditions.checkArgument(!composeFiles.isEmpty(), "No docker compose file have been provided");

        final DockerCompose dockerCompose;
        if (localCompose) {
            dockerCompose = new LocalDockerCompose(composeFiles, project);
        } else {
            dockerCompose = new ContainerisedDockerCompose(composeFiles, project);
        }

        dockerCompose.withCommand(cmd).withEnv(env).invoke();
    }

    private void registerContainersForShutdown() {
        ResourceReaper
            .instance()
            .registerLabelsFilterForCleanup(Collections.singletonMap("com.docker.compose.project", project));
    }

    @VisibleForTesting
    List<Container> listChildContainers() {
        return dockerClient
            .listContainersCmd()
            .withShowAll(true)
            .exec()
            .stream()
            .filter(container -> Arrays.stream(container.getNames()).anyMatch(name -> name.startsWith("/" + project)))
            .collect(Collectors.toList());
    }

    private void startAmbassadorContainers() {
        if (!ambassadorPortMappings.isEmpty()) {
            ambassadorContainer.start();
        }
    }

    @Override
    public void stop() {
        synchronized (MUTEX) {
            try {
                // shut down the ambassador container
                ambassadorContainer.stop();

                // Kill the services using docker-compose
                String cmd = "down -v";
                if (removeImages != null) {
                    cmd += " --rmi " + removeImages.dockerRemoveImagesType();
                }
                runWithCompose(cmd);
            } finally {
                project = randomProjectId();
            }
        }
    }

    public SELF withExposedService(String serviceName, int servicePort) {
        return withExposedService(serviceName, servicePort, Wait.defaultWaitStrategy());
    }

    public DockerComposeContainer withExposedService(String serviceName, int instance, int servicePort) {
        return withExposedService(serviceName + "_" + instance, servicePort);
    }

    public DockerComposeContainer withExposedService(
        String serviceName,
        int instance,
        int servicePort,
        WaitStrategy waitStrategy
    ) {
        return withExposedService(serviceName + "_" + instance, servicePort, waitStrategy);
    }

    public SELF withExposedService(String serviceName, int servicePort, @NonNull WaitStrategy waitStrategy) {
        String serviceInstanceName = getServiceInstanceName(serviceName);

        /*
         * For every service/port pair that needs to be exposed, we register a target on an 'ambassador container'.
         *
         * The ambassador container's role is to link (within the Docker network) to one of the
         * compose services, and proxy TCP network I/O out to a port that the ambassador container
         * exposes.
         *
         * This avoids the need for the docker compose file to explicitly expose ports on all the
         * services.
         *
         * {@link GenericContainer} should ensure that the ambassador container is on the same network
         * as the rest of the compose environment.
         */

        // Ambassador container will be started together after docker compose has started
        int ambassadorPort = nextAmbassadorPort.getAndIncrement();
        ambassadorPortMappings
            .computeIfAbsent(serviceInstanceName, __ -> new ConcurrentHashMap<>())
            .put(servicePort, ambassadorPort);
        ambassadorContainer.withTarget(ambassadorPort, serviceInstanceName, servicePort);
        ambassadorContainer.addLink(new FutureContainer(this.project + "_" + serviceInstanceName), serviceInstanceName);
        addWaitStrategy(serviceInstanceName, waitStrategy);
        return self();
    }

    private String getServiceInstanceName(String serviceName) {
        String serviceInstanceName = serviceName;
        if (!serviceInstanceName.matches(".*_[0-9]+")) {
            serviceInstanceName += "_1"; // implicit first instance of this service
        }
        return serviceInstanceName;
    }

    /*
     * can have multiple wait strategies for a single container, e.g. if waiting on several ports
     * if no wait strategy is defined, the WaitAllStrategy will return immediately.
     * The WaitAllStrategy uses an long timeout, because timeouts should be handled by the inner strategies.
     */
    private void addWaitStrategy(String serviceInstanceName, @NonNull WaitStrategy waitStrategy) {
        final WaitAllStrategy waitAllStrategy = waitStrategyMap.computeIfAbsent(
            serviceInstanceName,
            __ -> {
                return new WaitAllStrategy(WaitAllStrategy.Mode.WITH_MAXIMUM_OUTER_TIMEOUT)
                    .withStartupTimeout(Duration.ofMinutes(30));
            }
        );
        waitAllStrategy.withStrategy(waitStrategy);
    }

    /**
     * Specify the {@link WaitStrategy} to use to determine if the container is ready.
     *
     * @param serviceName  the name of the service to wait for
     * @param waitStrategy the WaitStrategy to use
     * @return this
     * @see org.testcontainers.containers.wait.strategy.Wait#defaultWaitStrategy()
     */
    public SELF waitingFor(String serviceName, @NonNull WaitStrategy waitStrategy) {
        String serviceInstanceName = getServiceInstanceName(serviceName);
        addWaitStrategy(serviceInstanceName, waitStrategy);
        return self();
    }

    /**
     * Get the host (e.g. IP address or hostname) that an exposed service can be found at, from the host machine
     * (i.e. should be the machine that's running this Java process).
     *

     * The service must have been declared using DockerComposeContainer#withExposedService.
     *
     * @param serviceName the name of the service as set in the docker-compose.yml file.
     * @param servicePort the port exposed by the service container.
     * @return a host IP address or hostname that can be used for accessing the service container.
     */
    public String getServiceHost(String serviceName, Integer servicePort) {
        return ambassadorContainer.getHost();
    }

    /**
     * Get the port that an exposed service can be found at, from the host machine
     * (i.e. should be the machine that's running this Java process).
     *

     * The service must have been declared using DockerComposeContainer#withExposedService.
     *
     * @param serviceName the name of the service as set in the docker-compose.yml file.
     * @param servicePort the port exposed by the service container.
     * @return a port that can be used for accessing the service container.
     */
    public Integer getServicePort(String serviceName, Integer servicePort) {
        Map<Integer, Integer> portMap = ambassadorPortMappings.get(getServiceInstanceName(serviceName));

        if (portMap == null) {
            throw new IllegalArgumentException(
                "Could not get a port for '" +
                serviceName +
                "'. " +
                "Testcontainers does not have an exposed port configured for '" +
                serviceName +
                "'. " +
                "To fix, please ensure that the service '" +
                serviceName +
                "' has ports exposed using .withExposedService(...)"
            );
        } else {
            return ambassadorContainer.getMappedPort(portMap.get(servicePort));
        }
    }

    public SELF withScaledService(String serviceBaseName, int numInstances) {
        scalingPreferences.put(serviceBaseName, numInstances);

        return self();
    }

    public SELF withEnv(String key, String value) {
        env.put(key, value);
        return self();
    }

    public SELF withEnv(Map<String, String> env) {
        env.forEach(this.env::put);
        return self();
    }

    /**
     * Use a local Docker Compose binary instead of a container.
     *
     * @return this instance, for chaining
     */
    public SELF withLocalCompose(boolean localCompose) {
        this.localCompose = localCompose;
        return self();
    }

    /**
     * Whether to pull images first.
     *
     * @return this instance, for chaining
     */
    public SELF withPull(boolean pull) {
        this.pull = pull;
        return self();
    }

    /**
     * Whether to tail child container logs.
     *
     * @return this instance, for chaining
     */
    public SELF withTailChildContainers(boolean tailChildContainers) {
        this.tailChildContainers = tailChildContainers;
        return self();
    }

    /**
     * Attach an output consumer at container startup, enabling stdout and stderr to be followed, waited on, etc.
     *

     * More than one consumer may be registered.
     *
     * @param serviceName the name of the service as set in the docker-compose.yml file
     * @param consumer    consumer that output frames should be sent to
     * @return this instance, for chaining
     */
    public SELF withLogConsumer(String serviceName, Consumer<OutputFrame> consumer) {
        String serviceInstanceName = getServiceInstanceName(serviceName);
        final List<Consumer<OutputFrame>> consumers =
            this.logConsumers.getOrDefault(serviceInstanceName, new ArrayList<>());
        consumers.add(consumer);
        this.logConsumers.putIfAbsent(serviceInstanceName, consumers);
        return self();
    }

    /**
     * Whether to always build images before starting containers.
     *
     * @return this instance, for chaining
     */
    public SELF withBuild(boolean build) {
        this.build = build;
        return self();
    }

    /**
     * Adds options to the docker-compose command, e.g. docker-compose --compatibility.
     *
     * @return this instance, for chaining
     */
    public SELF withOptions(String... options) {
        this.options = new HashSet<>(Arrays.asList(options));
        return self();
    }

    /**
     * Remove images after containers shutdown.
     *
     * @return this instance, for chaining
     */
    public SELF withRemoveImages(RemoveImages removeImages) {
        this.removeImages = removeImages;
        return self();
    }

    public Optional<ContainerState> getContainerByServiceName(String serviceName) {
        return Optional.ofNullable(serviceInstanceMap.get(serviceName));
    }

    private void followLogs(String containerId, Consumer<OutputFrame> consumer) {
        LogUtils.followOutput(dockerClient, containerId, consumer);
    }

    private SELF self() {
        return (SELF) this;
    }

    private String randomProjectId() {
        return identifier + Base58.randomString(6).toLowerCase();
    }

    public enum RemoveImages {
        /**
         * Remove all images used by any service.
         */
        ALL("all"),

        /**
         * Remove only images that don't have a custom tag set by the `image` field.
         */
        LOCAL("local");

        private final String dockerRemoveImagesType;

        RemoveImages(final String dockerRemoveImagesType) {
            this.dockerRemoveImagesType = dockerRemoveImagesType;
        }

        public String dockerRemoveImagesType() {
            return dockerRemoveImagesType;
        }
    }
}

interface DockerCompose {
    String ENV_PROJECT_NAME = "COMPOSE_PROJECT_NAME";
    String ENV_COMPOSE_FILE = "COMPOSE_FILE";

    DockerCompose withCommand(String cmd);

    DockerCompose withEnv(Map<String, String> env);

    void invoke();
}

/**
 * Use Docker Compose container.
 */
class ContainerisedDockerCompose extends GenericContainer<ContainerisedDockerCompose> implements DockerCompose {

    public static final char UNIX_PATH_SEPERATOR = ':';

    public static final DockerImageName DEFAULT_IMAGE_NAME = DockerImageName.parse("docker/compose:1.29.2");

    public ContainerisedDockerCompose(List<File> composeFiles, String identifier) {
        super(DEFAULT_IMAGE_NAME);
        addEnv(ENV_PROJECT_NAME, identifier);

        // Map the docker compose file into the container
        final File dockerComposeBaseFile = composeFiles.get(0);
        final String pwd = dockerComposeBaseFile.getAbsoluteFile().getParentFile().getAbsolutePath();
        final String containerPwd = convertToUnixFilesystemPath(pwd);

        final List<String> absoluteDockerComposeFiles = composeFiles
            .stream()
            .map(File::getAbsolutePath)
            .map(MountableFile::forHostPath)
            .map(MountableFile::getFilesystemPath)
            .map(this::convertToUnixFilesystemPath)
            .collect(Collectors.toList());
        final String composeFileEnvVariableValue = Joiner.on(UNIX_PATH_SEPERATOR).join(absoluteDockerComposeFiles); // we always need the UNIX path separator
        logger().debug("Set env COMPOSE_FILE={}", composeFileEnvVariableValue);
        addEnv(ENV_COMPOSE_FILE, composeFileEnvVariableValue);
        addFileSystemBind(pwd, containerPwd, BindMode.READ_WRITE);

        // Ensure that compose can access docker. Since the container is assumed to be running on the same machine
        //  as the docker daemon, just mapping the docker control socket is OK.
        // As there seems to be a problem with mapping to the /var/run directory in certain environments (e.g. CircleCI)
        //  we map the socket file outside of /var/run, as just /docker.sock
        addFileSystemBind(
            DockerClientFactory.instance().getRemoteDockerUnixSocketPath(),
            "/docker.sock",
            BindMode.READ_WRITE
        );
        addEnv("DOCKER_HOST", "unix:///docker.sock");
        setStartupCheckStrategy(new IndefiniteWaitOneShotStartupCheckStrategy());
        setWorkingDirectory(containerPwd);
    }

    @Override
    public void invoke() {
        super.start();

        this.followOutput(new Slf4jLogConsumer(logger()));

        // wait for the compose container to stop, which should only happen after it has spawned all the service containers
        logger()
            .info("Docker Compose container is running for command: {}", Joiner.on(" ").join(this.getCommandParts()));
        while (this.isRunning()) {
            logger().trace("Compose container is still running");
            Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
        }
        logger().info("Docker Compose has finished running");

        AuditLogger.doComposeLog(this.getCommandParts(), this.getEnv());

        final Integer exitCode = getDockerClient()
            .inspectContainerCmd(getContainerId())
            .exec()
            .getState()
            .getExitCode();

        if (exitCode == null || exitCode != 0) {
            throw new ContainerLaunchException(
                "Containerised Docker Compose exited abnormally with code " +
                exitCode +
                " whilst running command: " +
                StringUtils.join(this.getCommandParts(), ' ')
            );
        }
    }

    private String convertToUnixFilesystemPath(String path) {
        return SystemUtils.IS_OS_WINDOWS ? PathUtils.createMinGWPath(path).substring(1) : path;
    }
}

/**
 * Use local Docker Compose binary, if present.
 */
class LocalDockerCompose implements DockerCompose {

    /**
     * Executable name for Docker Compose.
     */
    private static final String COMPOSE_EXECUTABLE = SystemUtils.IS_OS_WINDOWS
        ? "docker-compose.exe"
        : "docker-compose";

    private final List<File> composeFiles;

    private final String identifier;

    private String cmd = "";

    private Map<String, String> env = new HashMap<>();

    public LocalDockerCompose(List<File> composeFiles, String identifier) {
        this.composeFiles = composeFiles;
        this.identifier = identifier;
    }

    @Override
    public DockerCompose withCommand(String cmd) {
        this.cmd = cmd;
        return this;
    }

    @Override
    public DockerCompose withEnv(Map<String, String> env) {
        this.env = env;
        return this;
    }

    @VisibleForTesting
    static boolean executableExists() {
        return CommandLine.executableExists(COMPOSE_EXECUTABLE);
    }

    @Override
    public void invoke() {
        // bail out early
        if (!executableExists()) {
            throw new ContainerLaunchException(
                "Local Docker Compose not found. Is " + COMPOSE_EXECUTABLE + " on the PATH?"
            );
        }

        final Map<String, String> environment = Maps.newHashMap(env);
        environment.put(ENV_PROJECT_NAME, identifier);

        TransportConfig transportConfig = DockerClientFactory.instance().getTransportConfig();
        SSLConfig sslConfig = transportConfig.getSslConfig();
        if (sslConfig != null) {
            if (sslConfig instanceof LocalDirectorySSLConfig) {
                environment.put("DOCKER_CERT_PATH", ((LocalDirectorySSLConfig) sslConfig).getDockerCertPath());
                environment.put("DOCKER_TLS_VERIFY", "true");
            } else {
                logger()
                    .warn(
                        "Couldn't set DOCKER_CERT_PATH. `sslConfig` is present but it's not LocalDirectorySSLConfig."
                    );
            }
        }
        String dockerHost = transportConfig.getDockerHost().toString();
        environment.put("DOCKER_HOST", dockerHost);

        final Stream<String> absoluteDockerComposeFilePaths = composeFiles
            .stream()
            .map(File::getAbsolutePath)
            .map(Objects::toString);

        final String composeFileEnvVariableValue = absoluteDockerComposeFilePaths.collect(
            Collectors.joining(File.pathSeparator + "")
        );
        logger().debug("Set env COMPOSE_FILE={}", composeFileEnvVariableValue);

        final File pwd = composeFiles.get(0).getAbsoluteFile().getParentFile().getAbsoluteFile();
        environment.put(ENV_COMPOSE_FILE, composeFileEnvVariableValue);

        logger().info("Local Docker Compose is running command: {}", cmd);

        final List<String> command = Splitter
            .onPattern(" ")
            .omitEmptyStrings()
            .splitToList(COMPOSE_EXECUTABLE + " " + cmd);

        try {
            new ProcessExecutor()
                .command(command)
                .redirectOutput(Slf4jStream.of(logger()).asInfo())
                .redirectError(Slf4jStream.of(logger()).asInfo()) // docker-compose will log pull information to stderr
                .environment(environment)
                .directory(pwd)
                .exitValueNormal()
                .executeNoTimeout();

            logger().info("Docker Compose has finished running");
        } catch (InvalidExitValueException e) {
            throw new ContainerLaunchException(
                "Local Docker Compose exited abnormally with code " +
                e.getExitValue() +
                " whilst running command: " +
                cmd
            );
        } catch (Exception e) {
            throw new ContainerLaunchException("Error running local Docker Compose command: " + cmd, e);
        }
    }

    /**
     * @return a logger
     */
    private Logger logger() {
        return DockerLoggerFactory.getLogger(COMPOSE_EXECUTABLE);
    }
}


text:
FactoryGirl.define do
  factory :state do
    name "A state"
  end
end


text:
--+ holdcas on;
set system parameters 'dont_reuse_heap_file=yes';
create table t1(  a char(1200),   b varchar(1200),  c nchar(1200),  d NCHAR VARYING(1200),  e BIT(1200),  f BIT VARYING(1200),  g int,  h SMALLINT,  i BIGINT,  j NUMERIC,  k FLOAT,  l DOUBLE,  m MONETARY,  n DATE,  o TIME,  p TIMESTAMP,  q DATETIME);

insert into t1 values (
  '1234567890',
  '1234567890',
  N'abc',
  N'ABC',
  B'1111111111',
  B'1111111111',
  10,
  255,
  9223372036854775807,
  0,
  0,
  0,
  -100,
  DATE '2008-10-31',
  TIME '00:00:00',
  TIMESTAMP '2010-10-31 01:15:45',
  DATETIME  '2008-10-31 13:15:45');
insert into t1 values (null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null);

create index i_t1_a2q on t1(a);
create index i_t1_a2p on t1(b);
create index i_t1_a2o on t1(c);
create index i_t1_a2n on t1(d);
create index i_t1_a2m on t1(e);
create index i_t1_a2l on t1(f);
create index i_t1_a2k on t1(g);
create index i_t1_a2j on t1(h);
create index i_t1_a2i on t1(i);
create index i_t1_a2h on t1(j);
create index i_t1_a2g on t1(k);
create index i_t1_a2f on t1(l);
create index i_t1_a2e on t1(m);
create index i_t1_a2d on t1(n);
create index i_t1_a2c on t1(o);
create index i_t1_a2b on t1(p);
create index i_t1_a2a on t1(q);

delete from t1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ a from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ b from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ c from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ d from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ e from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ f from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ g from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ h from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ i from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ j from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ k from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ l from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ m from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ n from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ o from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ p from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

PREPARE stmt1 FROM 'select /*+ RECOMPILE */ q from t1'
--TEST: result should be null
execute stmt1
DEALLOCATE PREPARE stmt1;

drop table t1;set system parameters 'dont_reuse_heap_file=no';
commit;
--+ holdcas off;


text:
import abc
from abc import ABCMeta
from collections import namedtuple
import json

class Msg:
    """
    An abstract base class for all messages used for communicating between
    the WebServices.

    The minimal functionality is the ability to instantiate a Msg from JSON
    and to write a Msg instance to JSON.

    We use namedtuples because they are lightweight and immutable. The splat
    operator (*) that we inherit from namedtuple is also convenient. We empty
    __slots__ to avoid unnecessary overhead.
    """

    __metaclass__ = ABCMeta

    @abc.abstractmethod
    def for_json(self):
        d = self._asdict()
        type_str = self.__class__.__name__
        d.update({"type": type_str})
        return d

    @abc.abstractmethod
    def to_json(self):
        return json.dumps(self.for_json())

    @staticmethod
    def from_json(str):
        d = json.loads(str)
        type_str = d["type"]
        del d["type"]
        return eval(type_str)(**d)

class LoadSuccessful(
    namedtuple(
        "LoadSuccessful", ["uri", "path", "version", "is_update", "endpoint_type"]
    ),
    Msg,
):
    __slots__ = ()

class LoadFailed(namedtuple("LoadFailed", ["uri", "version", "error_msg"]), Msg):
    __slots__ = ()

class LoadInProgress(
    namedtuple(
        "LoadInProgress", ["uri", "path", "version", "is_update", "endpoint_type"]
    ),
    Msg,
):
    __slots__ = ()

class Query(namedtuple("Query", ["uri", "params"]), Msg):
    __slots__ = ()

class QuerySuccessful(
    namedtuple("QuerySuccessful", ["uri", "version", "response"]), Msg
):
    __slots__ = ()

class LoadObject(
    namedtuple("LoadObject", ["uri", "url", "version", "is_update", "endpoint_type"]),
    Msg,
):
    __slots__ = ()

class DeleteObjects(namedtuple("DeleteObjects", ["uris"]), Msg):
    __slots__ = ()

# Used for testing to flush out objects
class FlushObjects(namedtuple("FlushObjects", []), Msg):
    __slots__ = ()

class ObjectsDeleted(namedtuple("ObjectsDeleted", ["uris"]), Msg):
    __slots__ = ()

class ObjectsFlushed(namedtuple("ObjectsFlushed", ["n_before", "n_after"]), Msg):
    __slots__ = ()

class CountObjects(namedtuple("CountObjects", []), Msg):
    __slots__ = ()

class ObjectCount(namedtuple("ObjectCount", ["count"]), Msg):
    __slots__ = ()

class ListObjects(namedtuple("ListObjects", []), Msg):
    __slots__ = ()

class ObjectList(namedtuple("ObjectList", ["objects"]), Msg):
    __slots__ = ()

class UnknownURI(namedtuple("UnknownURI", ["uri"]), Msg):
    __slots__ = ()

class UnknownMessage(namedtuple("UnknownMessage", ["msg"]), Msg):
    __slots__ = ()

class DownloadSkipped(
    namedtuple("DownloadSkipped", ["uri", "version", "msg", "host"]), Msg
):
    __slots__ = ()

class QueryFailed(namedtuple("QueryFailed", ["uri", "error"]), Msg):
    __slots__ = ()

class QueryError(namedtuple("QueryError", ["uri", "error"]), Msg):
    __slots__ = ()

class CheckHealth(namedtuple("CheckHealth", []), Msg):
    __slots__ = ()

class Healthy(namedtuple("Healthy", []), Msg):
    __slots__ = ()

class Unhealthy(namedtuple("Unhealthy", []), Msg):
    __slots__ = ()

class Ping(namedtuple("Ping", ["id"]), Msg):
    __slots__ = ()

class Pong(namedtuple("Pong", ["id"]), Msg):
    __slots__ = ()

class Listening(namedtuple("Listening", []), Msg):
    __slots__ = ()

class EngineFailure(namedtuple("EngineFailure", ["error"]), Msg):
    __slots__ = ()

class FlushLogs(namedtuple("FlushLogs", []), Msg):
    __slots__ = ()

class LogsFlushed(namedtuple("LogsFlushed", []), Msg):
    __slots__ = ()

class ServiceError(namedtuple("ServiceError", ["error"]), Msg):
    __slots__ = ()


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

<title>org.warriors2583.frc2013.shooter</title>
<meta name="date" content="2013-11-04">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.warriors2583.frc2013.shooter

Classes

C_FeederExtend

C_FeederRetract

C_MoveToTargetAngle

C_SetTargetAngle

C_StartShooter

CG_GotoAngle

CG_ShootFrisbee

SS_Shooter

SS_ShooterTray


text:
"""Commands to be used as console scripts for the git-origin project."""

from sys import argv
from os import makedirs, environ, sep
from os.path import join, isabs
from errno import EEXIST
from sys import exit, stderr
from subprocess import call
from StringIO import StringIO
from git.repo import Repo
from git.cmd import Git
from git.errors import GitCommandError
from git.commit import Commit

if "GIT_NOTES_REF" in environ:
    del environ["GIT_NOTES_REF"]

notes_ref = "refs/notes/origins"
blacklist_filename = "blacklist"
origin_usage = """git-origin ORIGIN [COMMIT]

ORIGIN - Commit to mark as an origin.
COMMIT - Commit which has ORIGIN as an origin (default=HEAD)."""
blacklist_usage = """git-blacklist COMMIT

COMMIT - Commit to add to the blacklist."""
cherry_usage = """git-cherry-origins [UPSTREAM [LOCAL]]

LOCAL - Local branch to compare against upstream, defaults to HEAD.
UPSTREAM - Upstream branch to compare against local, defaults to the remote
           the local branch is tracking."""

def _commit(repo, ref="HEAD"):
    return Commit(repo, repo.git.rev_parse(ref, verify=True))

def _existing_origins(repo, data):
    for id in data.splitlines():
        try:
            id = repo.git.rev_parse(id, verify=True)
            yield id
        except GitCommandError:
            continue

class Index(object):
    def __init__(self, repo, path=None):
        if path is None:
            path = join(repo.path, "index")
            self.git = repo.git
        else:
            self.git = Git(repo.wd)
            env = {
                "GIT_INDEX_FILE": path,
            }
            if not repo.bare:
                env["GIT_WORK_TREE"] = repo.wd
            self.git.extra["env"] = env

        self.path = path
        self.repo = repo

    def data_update(self, path, data, mode="0644", **kwargs):
        path = str(path)
        if isabs(path):
            path = path[1:]

        hash = self.repo.git.hash_object(stdin=True, t="blob", w=True,
                                         input=data, path=path)
        self.git.update_index("--cacheinfo", mode, hash, path, **kwargs)

    def checkout(self, wd=None, **kwargs):
        if wd is None:
            git = self.git
            wd = self.repo.wd
        else:
            git = Git(wd)
            git.extra = dict(self.git.extra)
            git.extra["env"]["GIT_WORK_TREE"] = wd

        try:
            makedirs(wd)
        except OSError, exc:
            if exc.errno != EEXIST:
                raise
        return git.checkout_index(**kwargs)

    def merge(self, remoteref, wd=None, **kwargs):
        if wd is None:
            git = self.git
        else:
            git = Git(wd)
            git.extra = dict(self.git.extra)
            git.extra["env"]["GIT_WORK_TREE"] = wd
        git.merge(remoteref)

    def merge_index(self, *args, **kwargs):
        wd = kwargs.get("work_tree")
        if wd is None:
            git = self.git
        else:
            git = Git(wd)
            git.extra = dict(self.git.extra)
            git.extra["env"]["GIT_WORK_TREE"] = wd
        return git.merge_index(*args, **kwargs)

    def read_tree(self, *args, **kwargs):
        return self.git.read_tree(*args, **kwargs)

    def write_tree(self, *args, **kwargs):
        return self.git.write_tree(*args, **kwargs)

    def update(self, path, **kwargs):
        self.git.update_index(path, **kwargs)

class Origins(object):
    def __init__(self, repo):
        self.repo = repo
        self.wd = join(repo.path, "origins-wd")
        self.index = Index(repo, join(repo.path, "origins-index"))
        self.ref = notes_ref

    def push(self, remote):
        self.repo.git.push(remote, notes_ref)

    def pull(self, remote):
        fetches = self.repo.git.config("remote.%s.fetch" % remote, get_all=True)
        remote_ref = "refs/remotes/%s/origins" % remote
        refspec = "+%s:%s" % (self.ref, remote_ref)
        if not refspec in fetches.splitlines():
            self.repo.git.config("remote.%s.fetch" % remote, refspec, add=True)

        print(self.repo.git.fetch(remote))

        try:
            notes = self.repo.git.rev_parse(self.ref, verify=True)
        except GitCommandError:
            self.repo.git.update_ref(self.ref, remote_ref)
            return

        base = self.repo.git.merge_base(notes, remote_ref)
        self.index.read_tree(base, notes, remote_ref,
                             m=True, aggressive=True)
        self.index.checkout(self.wd, a=True, f=True)
        self.index.merge_index("-o", "git-merge-origins-driver", "-a")
        self._commit("Merge %s" % remote_ref, "-p", remote_ref)

    def _commit(self, msg, *commitargs):
        parent = _commit(self.repo, self.ref)
        newtreeid = self.index.write_tree()
        if newtreeid != parent.tree.id:
            newcommitid = self.repo.git.commit_tree(newtreeid, "-p", parent.id,
                                                    input=msg, *commitargs)
            self.repo.git.update_ref(self.ref, newcommitid)
            return self.repo.commit(newcommitid)

    def _checkout(self):
        self.index.read_tree(self.ref)
        self.index.checkout(self.wd, a=True, f=True)

    def __getitem__(self, commit):
        head = _commit(self.repo, self.ref)
        try:
            blob = head.tree[str(commit)]
        except KeyError:
            return

        return (Commit(self.repo, id) for id in _existing_origins(self.repo, blob.data))

    def __setitem__(self, commit, origins):
        msg = "Set origins for %s\n\nOrigins:\n%s"
        origindata = "\n".join(c.id for c in origins)

        self.index.read_tree(self.ref)
        self.index.data_update(str(commit), origindata, add=True)
        self._commit(msg % (commit, origindata))

    def __delitem__(self, commit):
        self.index.read_tree(self.ref)
        self.index.update(str(commit), force_remove=True)
        self._commit("Remove origins for %s" % commit)

    def __iter__(self):
        self.index.read_tree(self.ref)
        commitids = self.index.git.ls_files().splitlines()
        return (self.repo.commit(c) for c in commitids if c.strip() != blacklist_filename)

def add_origin(repo, origin, commit="HEAD"):
    origin, commit = (_commit(repo, origin), _commit(repo, commit))

    origindata = Origins(repo)
    origins = list(origindata[commit] or "")

    if not origin.id in set(c.id for c in origins):
        origins.append(origin)
        origindata[commit] = origins
        print("Added origin %s to commit %s" % (origin, commit))
    else:
        print("Origin already set")

# Commands
def origin():
    """Add the supplied commit-ish as an origin on HEAD (or the second supplied commit-ish)."""

    if "GIT_NOTES_REF" in environ:
        del environ["GIT_NOTES_REF"]

    if 1 < len(argv) < 4:
        repo = Repo()
        try:
            add_origin(repo, *argv[1:])
        except GitCommandError, exc:
            exit("Failed to add origin when executing %s:\n%s" % (exc.command, exc.stderr))
    else:
        print >>stderr, origin_usage
        exit(2)

def add_blacklist(repo, commit):
    commit = _commit(repo, commit)

    origindata = Origins(repo)
    bldata = list(origindata[blacklist_filename] or "")

    if not commit.id in set(c.id for c in bldata):
        bldata.append(commit)
        origindata[blacklist_filename] = bldata
        print("Added commit %s to blacklist" % commit)
    else:
        print("Commit already in the blacklist")

def blacklist():
    """Add the supplied commit-ish to the blacklist."""

    if len(argv) == 2:
        repo = Repo()
        try:
            add_blacklist(repo, argv[1])
        except GitCommandError, exc:
            exit("Failed to add commit to blacklist when executing %s:\n%s" % (exc.command, exc.stderr))
    else:
        print >>stderr, blacklist_usage
        exit(2)

def left_right(repo, left, right, *args):
    def _rev_left_right(left, right):
        if args:
            revinfo = repo.git.rev_list("%s...%s" % (left, right), left_right=True, *args)
        else:
            revinfo = repo.git.rev_list("%s...%s" % (left, right), left_right=True)

        for rev in revinfo.splitlines():
            c = Commit(repo, rev[1:])
            c.direction = rev[0]
            yield c

    def _origins_batch(commits):
        blobs = "\n".join("%s:%s" % (notes_ref, c) for c in commits)
        contentstr = repo.git.cat_file(batch=True, input=blobs)
        content = StringIO(contentstr)
        while content:
            line = content.readline().rstrip()
            if not line:
                break

            words = line.split()
            if words[1] == "missing":
                yield None
                continue

            (hash, type, size) = words
            data = content.read(int(size))
            content.read(1) # Kill the trailing LF

            yield (Commit(repo, sha1) for sha1 in _existing_origins(repo, data))

    commits = list(_rev_left_right(left, right))
    commitmap = dict((c.id, c) for c in commits)
    commitids = set(c.id for c in commits)
    origindata = dict(zip(commits, _origins_batch(commits)))
    blorigins = Origins(repo)[blacklist_filename]
    if blorigins:
        blacklist = set(c.id for c in blorigins)
    else:
        blacklist = set()

    for (commit, origins) in origindata.iteritems():
        if commit.id in blacklist:
            commit.direction = "-"
        elif origins is not None:
            for o in origins:
                if o.id in commitmap:
                    commitmap[o.id].direction = "-"

            if all(o.id in commitids for o in origins):
                commit.direction = "-"

    return commits

def cherry():
    """Display a git-cherry-like view of the commits between two branches."""

    args = len(argv)
    repo = Repo()

    if args > 1:
        upstream = argv[1]
    else:
        headref = repo.git.rev_parse("HEAD", symbolic_full_name=True)
        if not headref:
            exit("Must supply upstream ref when using a detached HEAD.")

        upstream = repo.git.for_each_ref(headref, format="%(upstream)")
        if not upstream:
            exit("No remote tracking branch for this branch, please supply upstream ref.")

    if args > 2:
        local = argv[2]
    else:
        local = "HEAD"

    try:
        upstream, local = (_commit(repo, upstream), _commit(repo, local))
        extra = argv[3:]
        if extra:
            commits = reversed(left_right(repo, upstream, local, *extra))
        else:
            commits = reversed(left_right(repo, upstream, local))

        for c in commits:
            if c.direction == "-":
                print("%s %s" % (c.direction, c))
            elif c.direction == ">":
                print("+ %s" % c)
    except GitCommandError, exc:
        exit("Failed to display commits when executing %s:\n%s" % (exc.command, exc.stderr))

def _traverse(tree, path):
    parts = path.split(sep)
    while parts:
        piece = parts.pop(0)
        obj = tree[piece]
        if hasattr(obj, "mime_type"):
            yield obj

        tree = obj

def file():
    """For a given file, compare its history against UPSTREAM."""

    repo = Repo()
    fn = argv[1]
    upstream = argv[2]
    try:
        local = argv[3]
    except IndexError:
        local = "HEAD"

    lstart = Commit.find_all(repo, local, fn)[-1]
    initialblob = _traverse(lstart.tree, fn).next()
    def _commit_for_blob(ref, fn):
        upstream = Commit.find_all(repo, ref, fn)
        for commit in upstream:
            try:
                blob = _traverse(commit.tree, fn).next()
            except KeyError:
                return

            if blob.id == initialblob.id:
                return commit

    ustart = _commit_for_blob(upstream, fn)
    if ustart:
        upstream_precommits = set(c.id for c in Commit.find_all(repo, ustart, fn))
    else:
        print >>stderr, "Warning: upstream does not have the initial blob for %s." % fn

    upstream, local = (_commit(repo, upstream), _commit(repo, local))
    commits = reversed(left_right(repo, upstream, local, fn))
    for commit in commits:
        if ustart:
            if commit.direction != "-" and \
               commit.id in upstream_precommits:
                commit.direction = "-"
        print("%s %s" % (commit.direction, commit))

def pull():
    remote = argv[1]
    repo = Repo()
    origins = Origins(repo)
    try:
        origins.pull(remote)
    except GitCommandError, exc:
        exit("Unable to pull when executing %s:\n%s" % (exc.command, exc.stderr))

def push():
    remote = argv[1]
    repo = Repo()
    origins = Origins(repo)
    try:
        origins.push(remote)
    except GitCommandError, exc:
        exit("Unable to push when executing %s:\n%s" % (exc.command, exc.stderr))

def merge():
    repo = Repo()
    fn = argv[4]
    base = Blob(repo, argv[1], name=fn)
    left = Blob(repo, argv[2], name=fn)
    right = Blob(repo, argv[3], name=fn)

    origins = set(left.data.splitlines())
    base_origins = set(base.data.splitlines())
    right_origins = set(right.data.splitlines())

    removed = base_origins.difference(right_origins)
    for rem in removed:
        if rem in origins:
            origins.remove(rem)

    added = right_origins.difference(base_origins)
    for add in added:
        if not add in origins:
            origins.add(add)

    open(fn, "w").write(linesep.join(leftorigins))


text:
struct Transformation
{
  float s; // ou fov
  float dof;
  float textureFade;
  quaternion q;
  vector3f v;
  bool use_spline;
};

#endif		// TRANSFORMATION_HH


text:
#include "GffSimpleHandler.h"

namespace gff {

  GffSimpleHandler::GffSimpleHandler()
  {
  }

  GffSimpleHandler::~GffSimpleHandler()
  {
    cout << "GffSimpleHandler::~GffSimpleHandler()" << endl;
  }

  void GffSimpleHandler::start()
  {
    cout << "begin parsing." << endl;
    countLines = 0;
  }

  bool GffSimpleHandler::newline(string & str)
  {
    //cout << "----" << endl << str << endl;
    countLines++;
  }

  void GffSimpleHandler::end()
  {
    cout << countLines << " lines parsed." << endl;
  }

}


text:
package com.groupon.vertx.memcache;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import io.vertx.core.json.JsonObject;

import com.groupon.vertx.utils.Logger;

/**
 * An object representing the required config for a Memcache cluster.
 *
 * @author Stuart Siegrist (fsiegrist at groupon dot com)
 * @since 1.1.0
 */
public class MemcacheClusterConfig implements MemcacheKeys {
    private static final Logger log = Logger.getLogger(MemcacheClusterConfig.class);

    private String eventBusAddressPrefix;
    private long retryInterval = MemcacheConfig.DEFAULT_RETRY_INTERVAL;
    private Map<String, MemcacheConfig> clusterMap = new HashMap<>();

    public MemcacheClusterConfig(JsonObject jsonConfig) {
        if (jsonConfig == null) {
            log.error("initialize", "exception", "noConfigFound");
            throw new MemcacheException("No Memcache cluster config found");
        }

        this.eventBusAddressPrefix = jsonConfig.getString(EVENT_BUS_ADDRESS_PREFIX_KEY);
        this.retryInterval = jsonConfig.getLong(RETRY_INTERVAL, MemcacheConfig.DEFAULT_RETRY_INTERVAL);
        JsonObject clusters = jsonConfig.getJsonObject(CLUSTERS_KEY, new JsonObject());

        if (eventBusAddressPrefix != null && !eventBusAddressPrefix.isEmpty() && clusters.size() > 0) {
            for (String clusterKey : clusters.fieldNames()) {
                JsonObject clusterConfig = clusters.getJsonObject(clusterKey, new JsonObject()).copy();
                clusterConfig.put(EVENT_BUS_ADDRESS_KEY, eventBusAddressPrefix);
                clusterConfig.put(RETRY_INTERVAL, retryInterval);
                clusterMap.put(clusterKey, new MemcacheConfig(clusterConfig));
            }
        } else {
            log.error("initialize", "exception", "invalidConfigFound", new String[] {"config"}, jsonConfig.encode());
            throw new MemcacheException("Invalid Memcache config defined");
        }

        log.info("initialize", "success", new String[]{"eventBusAddressPrefix", "clusters"}, eventBusAddressPrefix, clusterMap.size());
    }

    public String getEventBusAddressPrefix() {
        return eventBusAddressPrefix;
    }

    public long getRetryInterval() {
        return retryInterval;
    }

    public Set<String> getClusterNames() {
        return Collections.unmodifiableSet(clusterMap.keySet());
    }

    public MemcacheConfig getCluster(String clusterName) {
        return clusterMap.get(clusterName);
    }

    public Set<String> getServers() {
        Set<String> servers = new HashSet<>();
        for (MemcacheConfig config : clusterMap.values()) {
            servers.addAll(config.getServers());
        }
        return Collections.unmodifiableSet(servers);
    }
}


text:
package org.apache.hadoop.hive.metastore.events;

import org.apache.hadoop.hive.metastore.HiveMetaStore.HMSHandler;
import org.apache.hadoop.hive.metastore.api.Database;

public class CreateDatabaseEvent extends ListenerEvent {

  private final Database db;

  public CreateDatabaseEvent (Database db, boolean status, HMSHandler handler) {
    super (status, handler);
    this.db = db;
  }

  /**
   * @return the db
   */
  public Database getDatabase () {
    return db;
  }
}