text:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.util.Timer;
import java.util.TimerTask;

public class DrawArea extends Observer {

    // PUBLIC

    public DrawArea(DoodleModel model, Dimension size) {
        super(model);
        this.doodleModel = model;
        this.previousPoint = null;
        this.playTimer = null;
        this.playTime = 0;
        this.defaultCanvasSize = new Dimension(size);
        this.setBackground(Constants.CANVAS_BACKGROUND_COLOR);
        this.setCanvasSize(size);
        this.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                super.mousePressed(e);
                if((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
                    DrawArea.this.doodleModel.newStroke();
                    if(DrawArea.this.doodleModel.isActualSize()) {
                        DrawArea.this.previousPoint = new Point((int) (e.getPoint().x / Doodle.ratioDPI), (int) (e.getPoint().y / Doodle.ratioDPI));
                    } else {
                        double ratio;
                        if (DrawArea.this.getSize().getHeight() / DrawArea.this.getCanvasSize().getHeight() < DrawArea.this.getSize().getWidth() / DrawArea.this.getCanvasSize().getWidth()) {
                            ratio = DrawArea.this.getSize().getHeight() / DrawArea.this.getCanvasSize().getHeight();
                        } else {
                            ratio = DrawArea.this.getSize().getWidth() / DrawArea.this.getCanvasSize().getWidth();
                        }
                        DrawArea.this.previousPoint = new Point((int) (e.getPoint().x / Doodle.ratioDPI / ratio), (int) (e.getPoint().y / Doodle.ratioDPI / ratio));
                    }
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                super.mouseReleased(e);
                if(DrawArea.this.previousPoint != null) {
                    if(DrawArea.this.doodleModel.isActualSize()) {
                        DrawArea.this.addLine(DrawArea.this.previousPoint, new Point((int) (e.getPoint().x / Doodle.ratioDPI), (int) (e.getPoint().y / Doodle.ratioDPI)));
                    } else {
                        double ratio;
                        if (DrawArea.this.getSize().getHeight() / DrawArea.this.getCanvasSize().getHeight() < DrawArea.this.getSize().getWidth() / DrawArea.this.getCanvasSize().getWidth()) {
                            ratio = DrawArea.this.getSize().getHeight() / DrawArea.this.getCanvasSize().getHeight();
                        } else {
                            ratio = DrawArea.this.getSize().getWidth() / DrawArea.this.getCanvasSize().getWidth();
                        }
                        DrawArea.this.addLine(DrawArea.this.previousPoint, new Point((int) (e.getPoint().x / Doodle.ratioDPI / ratio), (int) (e.getPoint().y / Doodle.ratioDPI / ratio)));
                    }
                    DrawArea.this.doodleModel.endStroke();
                    DrawArea.this.previousPoint = null;
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                super.mouseEntered(e);
                if((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK) {
                    DrawArea.this.doodleModel.newStroke();
                    if(DrawArea.this.doodleModel.isActualSize()) {
                        DrawArea.this.previousPoint = new Point((int) (e.getPoint().x / Doodle.ratioDPI), (int) (e.getPoint().y / Doodle.ratioDPI));
                    } else {
                        double ratio;
                        if (DrawArea.this.getSize().getHeight() / DrawArea.this.getCanvasSize().getHeight() < DrawArea.this.getSize().getWidth() / DrawArea.this.getCanvasSize().getWidth()) {
                            ratio = DrawArea.this.getSize().getHeight() / DrawArea.this.getCanvasSize().getHeight();
                        } else {
                            ratio = DrawArea.this.getSize().getWidth() / DrawArea.this.getCanvasSize().getWidth();
                        }
                        DrawArea.this.previousPoint = new Point((int) (e.getPoint().x / Doodle.ratioDPI / ratio), (int) (e.getPoint().y / Doodle.ratioDPI / ratio));
                    }
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                super.mouseExited(e);
                if(DrawArea.this.previousPoint != null) {
                    if(DrawArea.this.doodleModel.isActualSize()) {
                        DrawArea.this.addLine(DrawArea.this.previousPoint, new Point((int) (e.getPoint().x / Doodle.ratioDPI), (int) (e.getPoint().y / Doodle.ratioDPI)));
                    } else {
                        double ratio;
                        if (DrawArea.this.getSize().getHeight() / DrawArea.this.getCanvasSize().getHeight() < DrawArea.this.getSize().getWidth() / DrawArea.this.getCanvasSize().getWidth()) {
                            ratio = DrawArea.this.getSize().getHeight() / DrawArea.this.getCanvasSize().getHeight();
                        } else {
                            ratio = DrawArea.this.getSize().getWidth() / DrawArea.this.getCanvasSize().getWidth();
                        }
                        DrawArea.this.addLine(DrawArea.this.previousPoint, new Point((int) (e.getPoint().x / Doodle.ratioDPI / ratio), (int) (e.getPoint().y / Doodle.ratioDPI / ratio)));
                    }
                    DrawArea.this.doodleModel.endStroke();
                    DrawArea.this.previousPoint = null;
                }
            }
        });
        this.addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                super.mouseDragged(e);
                if(DrawArea.this.previousPoint != null) {
                    Point newPoint;
                    if(DrawArea.this.doodleModel.isActualSize()) {
                        newPoint = new Point((int) (e.getPoint().x / Doodle.ratioDPI), (int) (e.getPoint().y / Doodle.ratioDPI));
                    } else {
                        double ratio;
                        if(DrawArea.this.getSize().getHeight() / DrawArea.this.getCanvasSize().getHeight() < DrawArea.this.getSize().getWidth() / DrawArea.this.getCanvasSize().getWidth()) {
                            ratio = DrawArea.this.getSize().getHeight() / DrawArea.this.getCanvasSize().getHeight();
                        } else {
                            ratio = DrawArea.this.getSize().getWidth() / DrawArea.this.getCanvasSize().getWidth();
                        }
                        newPoint = new Point((int) (e.getPoint().x / Doodle.ratioDPI / ratio), (int) (e.getPoint().y / Doodle.ratioDPI / ratio));
                    }
                    DrawArea.this.addLine(DrawArea.this.previousPoint, newPoint);
                    DrawArea.this.previousPoint = newPoint;
                }
            }

            @Override
            public void mouseMoved(MouseEvent e) {
                super.mouseMoved(e);
            }
        });
    }

    public Dimension getCanvasSize() {
        return new Dimension(this.canvasSize);
    }

    public BufferedImage getImage() {
        BufferedImage bi;
        if(this.doodleModel.isActualSize()) {
            bi = new BufferedImage(this.getCanvasSize().width, this.getCanvasSize().height, BufferedImage.TYPE_INT_ARGB);
        } else {
            bi = new BufferedImage(this.getSize().width, this.getSize().height, BufferedImage.TYPE_INT_ARGB);
        }
        this.paint(bi.getGraphics());
        return bi;
    }

    @Override
    public void update() {
        if(this.doodleModel.isActualSize()) {
            if (this.canvasSize.width < (int) (this.doodleModel.getDoodleSize().width * Doodle.ratioDPI)) {
                this.canvasSize.width = (int) (this.doodleModel.getDoodleSize().width * Doodle.ratioDPI);
                this.setPreferredSize(this.getCanvasSize());
                this.setMaximumSize(this.getCanvasSize());
            }
            if (this.canvasSize.height < (int) (this.doodleModel.getDoodleSize().height * Doodle.ratioDPI)) {
                this.canvasSize.height = (int) (this.doodleModel.getDoodleSize().height * Doodle.ratioDPI);
                this.setPreferredSize(this.getCanvasSize());
                this.setMaximumSize(this.getCanvasSize());
            }
        } else {
            if(this.doodleModel.getDoodleSize().width == 0 || this.doodleModel.getDoodleSize().height == 0) {
                this.setCanvasSize(defaultCanvasSize);
            }
            this.setPreferredSize(new Dimension(0, 0));
        }
        this.revalidate();
        this.repaint();
    }

    // Private

    private DoodleModel doodleModel;
    private Point previousPoint;
    private final Dimension defaultCanvasSize;
    private Dimension canvasSize;
    private Timer playTimer;
    private long playTime;

    private void addLine(Point prevPoint, Point newPoint) {
        this.doodleModel.addLine(prevPoint, newPoint);
    }

    private void paintLine(Graphics2D g2d, Line line) {
        if(this.doodleModel.isActualSize()) {
            g2d.setStroke(new BasicStroke((float) (line.getThickness() * Doodle.ratioDPI), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
            g2d.setColor(line.getColor());
            g2d.drawLine((int) (line.getSrc().x * Doodle.ratioDPI), (int) (line.getSrc().y * Doodle.ratioDPI), (int) (line.getDest().x * Doodle.ratioDPI), (int) (line.getDest().y * Doodle.ratioDPI));
        } else {
            double ratio;
            if(this.getSize().getHeight() / this.getCanvasSize().getHeight() < this.getSize().getWidth() / this.getCanvasSize().getWidth()) {
                ratio = this.getSize().getHeight() / this.getCanvasSize().getHeight();
            } else {
                ratio = this.getSize().getWidth() / this.getCanvasSize().getWidth();
            }
            g2d.setStroke(new BasicStroke((float) (line.getThickness() * Doodle.ratioDPI * ratio), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
            g2d.setColor(line.getColor());
            g2d.drawLine((int) (line.getSrc().x * Doodle.ratioDPI * ratio), (int) (line.getSrc().y * Doodle.ratioDPI * ratio), (int) (line.getDest().x * Doodle.ratioDPI * ratio), (int) (line.getDest().y * Doodle.ratioDPI * ratio));
        }
    }

    private void setCanvasSize(Dimension size) {
        this.canvasSize = size;
    }

    // PROTECTED

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        if(this.doodleModel.willStartPlaying()) {
            if(this.playTimer != null) {
                this.playTimer.cancel();
            }
            this.playTimer = new Timer();
            this.playTimer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    DrawArea.this.playTime++;
                    DrawArea.this.repaint();
                }
            }, 10, 10);
            if(this.doodleModel.getNumTotalStrokes() > 0) {
                this.doodleModel.setDoodleStrokes(this.doodleModel.getNumPrevStrokes() + 1);
            } else {
                this.doodleModel.stopPlaying();
            }
        }
        if(this.doodleModel.isPlaying()) {
            boolean nextStroke = false;
            for(Stroke stroke : this.doodleModel.getStrokes().subList(0, this.doodleModel.getNumPrevStrokes() - 1)) {
                for(Line line : stroke.getLines()) {
                    this.paintLine(g2d, line);
                }
            }
            Stroke lastStroke = this.doodleModel.getStrokes().get(this.doodleModel.getNumPrevStrokes() - 1);
            for (Line line : lastStroke.getLines()) {
                if (line.getTime() <= this.playTime) {
                    this.paintLine(g2d, line);
                    if (line == lastStroke.getLines().get(lastStroke.getLines().size() - 1)) {
                        nextStroke = true;
                    }
                }
            }
            if(nextStroke) {
                if(this.doodleModel.getNumPrevStrokes() < this.doodleModel.getNumTotalStrokes()) {
                    this.doodleModel.setDoodleStrokes(this.doodleModel.getNumPrevStrokes() + 1);
                    this.playTime = 0;
                } else {
                    this.doodleModel.stopPlaying();
                    this.playTime = 0;
                    this.playTimer.cancel();
                    this.playTimer = null;
                }
            }
        } else {
            if(this.playTimer != null) {
                this.playTimer.cancel();
                this.playTimer = null;
            }
            for(Stroke stroke : this.doodleModel.getStrokes()) {
                for(Line line : stroke.getLines()) {
                    this.paintLine(g2d, line);
                }
            }
            if(this.doodleModel.getCurrentStroke() != null) {
                for(Line line : this.doodleModel.getCurrentStroke().getLines()) {
                    this.paintLine(g2d, line);
                }
            }
        }
    }
}


text:
class BankAccount:
    pass

redpajama_set_name: RedPajamaGithub


text:
redirect_from:
  - /reference/commandline/network_inspect/
description: The network inspect command description and usage
keywords:
- network, inspect, user-defined
title: docker network inspect
---

```markdown
Usage:  docker network inspect [OPTIONS] NETWORK [NETWORK...]

Display detailed information on one or more networks

Options:
  -f, --format string   Format the output using the given go template
      --help            Print usage
```

Returns information about one or more networks. By default, this command renders all results in a JSON object. For example, if you connect two containers to the default `bridge` network:

```bash
$ sudo docker run -itd --name=container1 busybox
f2870c98fd504370fb86e59f32cd0753b1ac9b69b7d80566ffc7192a82b3ed27

$ sudo docker run -itd --name=container2 busybox
bda12f8922785d1f160be70736f26c1e331ab8aaf8ed8d56728508f2e2fd4727
```

The `network inspect` command shows the containers, by id, in its
results. For networks backed by multi-host network driver, such as Overlay,
this command also shows the container endpoints in other hosts in the
cluster. These endpoints are represented as "ep-{endpoint-id}" in the output.
You can specify an alternate format to execute a given
template for each result. Go's
[text/template](http://golang.org/pkg/text/template/) package describes all the
details of the format.

```bash
$ sudo docker network inspect bridge
[
    {
        "Name": "bridge",
        "Id": "b2b1a2cba717161d984383fd68218cf70bbbd17d328496885f7c921333228b0f",
        "Scope": "local",
        "Driver": "bridge",
        "IPAM": {
            "Driver": "default",
            "Config": [
                {
                    "Subnet": "172.17.42.1/16",
                    "Gateway": "172.17.42.1"
                }
            ]
        },
        "Internal": false,
        "Containers": {
            "bda12f8922785d1f160be70736f26c1e331ab8aaf8ed8d56728508f2e2fd4727": {
                "Name": "container2",
                "EndpointID": "0aebb8fcd2b282abe1365979536f21ee4ceaf3ed56177c628eae9f706e00e019",
                "MacAddress": "02:42:ac:11:00:02",
                "IPv4Address": "172.17.0.2/16",
                "IPv6Address": ""
            },
            "f2870c98fd504370fb86e59f32cd0753b1ac9b69b7d80566ffc7192a82b3ed27": {
                "Name": "container1",
                "EndpointID": "a00676d9c91a96bbe5bcfb34f705387a33d7cc365bac1a29e4e9728df92d10ad",
                "MacAddress": "02:42:ac:11:00:01",
                "IPv4Address": "172.17.0.1/16",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        }
    }
]
```

Returns the information about the user-defined network:

```bash
$ docker network create simple-network
69568e6336d8c96bbf57869030919f7c69524f71183b44d80948bd3927c87f6a
$ docker network inspect simple-network
[
    {
        "Name": "simple-network",
        "Id": "69568e6336d8c96bbf57869030919f7c69524f71183b44d80948bd3927c87f6a",
        "Scope": "local",
        "Driver": "bridge",
        "IPAM": {
            "Driver": "default",
            "Config": [
                {
                    "Subnet": "172.22.0.0/16",
                    "Gateway": "172.22.0.1/16"
                }
            ]
        },
        "Containers": {},
        "Options": {}
    }
]
```

## Related information

* [network disconnect ](network_disconnect.md)
* [network connect](network_connect.md)
* [network create](network_create.md)
* [network ls](network_ls.md)
* [network rm](network_rm.md)
* [Understand Docker container networks](../../userguide/networking/index.md)


text:
<?xml version="1.0" encoding="utf-8" ?>
<accesslevel xmlns="http://schemas.google.com/gCal/2005" value="owner"/>


text:
'''
Dejitter
========

Prevent blob jittering.

A problem that is often faced (esp. in optical MT setups) is that of
jitterish BLOBs caused by bad camera characteristics. With this module
you can get rid of that jitter. You just define a threshold
`jitter_distance` in your config, and all touch movements that move
the touch by less than the jitter distance are considered 'bad'
movements caused by jitter and will be discarded.
'''

__all__ = ('InputPostprocDejitter', )

from kivy.config import Config

class InputPostprocDejitter(object):
    '''
    Get rid of jitterish BLOBs.
    Example::

        [postproc]
        jitter_distance = 0.004
        jitter_ignore_devices = mouse,mactouch

    :Configuration:
        `jitter_distance`: float
            A float in range 0-1.
        `jitter_ignore_devices`: string
            A comma-separated list of device identifiers that
            should not be processed by dejitter (because they're
            very precise already).
    '''

    def __init__(self):
        self.jitterdist = Config.getfloat('postproc', 'jitter_distance')
        ignore_devices = Config.get('postproc', 'jitter_ignore_devices')
        self.ignore_devices = ignore_devices.split(',')
        self.last_touches = {}

    def taxicab_distance(self, p, q):
        # Get the taxicab/manhattan/citiblock distance for efficiency reasons
        return abs(p[0] - q[0]) + abs(p[1] - q[1])

    def process(self, events):
        if not self.jitterdist:
            return events
        processed = []
        for etype, touch in events:
            if not touch.is_touch:
                continue
            if touch.device in self.ignore_devices:
                processed.append((etype, touch))
                continue
            if etype == 'begin':
                self.last_touches[touch.id] = touch.spos
            if etype == 'end':
                del self.last_touches[touch.id]
            if etype != 'update':
                processed.append((etype, touch))
                continue
            # Check whether the touch moved more than the jitter distance
            last_spos = self.last_touches[touch.id]
            dist = self.taxicab_distance(last_spos, touch.spos)
            if dist > self.jitterdist:
                # Only if the touch has moved more than the jitter dist we take
                # it into account and dispatch it. Otherwise suppress it.
                self.last_touches[touch.id] = touch.spos
                processed.append((etype, touch))
        return processed


text:
package org.dizitart.no2.sync;

import org.dizitart.no2.Document;
import org.dizitart.no2.sync.data.ChangeFeed;
import org.dizitart.no2.sync.data.FeedOptions;

import java.util.List;

/**
 * An interface for the DataGate sync operations.
 *
 * @since 1.0
 * @author Anindya Chatterjee.
 */
public interface SyncTemplate {
    /**
     * Downloads the list of changes from the server.
     *
     * @param feedOptions options to fetch the change feed
     * @return the list of changes
     */
    ChangeFeed changedSince(FeedOptions feedOptions);

    /**
     * Uploads the local changes to the server.
     *
     * @param changeFeed the list of changes to upload
     * @return `true` if the operation is successful; `false` otherwise.
     */
    boolean change(ChangeFeed changeFeed);

    /**
     * Fetches all documents from remote.
     *
     * @param offset pagination offset
     * @param limit pagination limit
     * @return list of documents from remote.
     */
    List<Document> fetch(int offset, int limit);

    /**
     * Gets the size of the remote collection.
     *
     * @return the size in long
     */
    long size();

    /**
     * Clears the remote collection.
     */
    void clear();

    /**
     * Checks if the server is online and reachable.
     *
     * @return `true` if online; `false` otherwise.
     */
    boolean isOnline();

    /**
     * Gets the name of the remote collection.
     *
     * @return the name of the remote collection.
     */
    String getCollectionName();

    /**
     * Tries to acquire a synchronization lock on the remote collection.
     * Before start of replication, a sync lock must be acquired on remote
     * collection. If the acquisition is unsuccessful, replication will
     * not occur and it will be retried in next iteration.
     *
     * If the expiryDelay is expired, then a new lock will be acquired overwriting
     * previous lock information.
     *
     * [icon="{@docRoot}/note.png"]
     * NOTE: Lock information should be maintain as a metadata in the remote database
     * in a separate collection/table than the remote collection.
     *
     * @param expiryDelay the expiry delay
     * @param issuer originator of the change feed
     * @return the boolean
     */
    boolean trySyncLock(TimeSpan expiryDelay, String issuer);

    /**
     * Releases the synchronization lock on the remote collection.
     */
    void releaseLock(String issuer);
}


text:
import sys
import os
import codecs
import time

sys.path.append("/Libs/jsoup-1.8.2.jar")
sys.path.append("/Libs/lucene-analyzers-common-4.10.4.jar")
sys.path.append("/Libs/lucene-core-4.10.4.jar")
sys.path.append("/Libs/lucene-queries-4.10.4.jar")
sys.path.append("/Libs/lucene-queryparser-4.10.4.jar")
sys.path.append("/Libs/jython-standalone-2.7.0.jar")
sys.path.append("/Libs/mysql-connector-java-5.1.22-bin.jar")
sys.path.append("/Libs/py4j-0.9.jar")
sys.path.append("/Libs/org.apache.commons.lang_2.6.0.v201205030909.jar")
sys.path.append("/Libs/org.eclipse.cdt.core_5.6.0.201402142303.jar")
sys.path.append("/Libs/org.eclipse.core.contenttype_3.4.200.v20120523-2004.jar")
sys.path.append("/Libs/org.eclipse.core.jobs_3.5.200.v20120521-2346.jar")
sys.path.append("/Libs/org.eclipse.core.resources.win32.x86_3.5.100.v20110423-0524.jar")
sys.path.append("/Libs/org.eclipse.core.resources_3.8.0.v20120522-2034.jar")
sys.path.append("/Libs/org.eclipse.core.runtime_3.8.0.v20120521-2346.jar")
sys.path.append("/Libs/org.eclipse.equinox.common_3.6.100.v20120522-1841.jar")
sys.path.append("/Libs/org.eclipse.equinox.common_3.6.200.v20130402-1505.jar")
sys.path.append("/Libs/org.eclipse.equinox.preferences_3.5.0.v20120522-1841.jar")
sys.path.append("/Libs/org.eclipse.jdt.core_3.8.1.v20120531-0637.jar")
sys.path.append("/Libs/org.eclipse.jdt.ui_3.8.2.v20130107-165834.jar")
sys.path.append("/Libs/org.eclipse.jface.text_3.8.0.v20120531-0600.jar")
sys.path.append("/Libs/org.eclipse.ltk.core.refactoring_3.6.100.v20130605-1748.jar")
sys.path.append("/Libs/org.eclipse.osgi_3.8.0.v20120529-1548.jar")
sys.path.append("/Libs/org.eclipse.text_3.5.0.jar")
sys.path.append("/Libs/bson-3.0.2.jar")
sys.path.append("/Libs/mongodb-driver-3.0.2.jar")
sys.path.append("/Libs/mongodb-driver-core-3.0.2.jar")

from java.io import IOException, File, StringReader
from org.apache.lucene.analysis.en import EnglishAnalyzer
from org.apache.lucene.document import Document, Field, StringField
from org.apache.lucene.index import IndexWriter, IndexWriterConfig, CorruptIndexException
from org.apache.lucene.store import SimpleFSDirectory, LockObtainFailedException, RAMDirectory, FSDirectory
from org.apache.lucene.analysis.core import KeywordAnalyzer
from org.apache.lucene.analysis.standard import StandardAnalyzer
from org.apache.lucene.analysis.miscellaneous import PerFieldAnalyzerWrapper
from org.apache.lucene.util import Version
from GitSearch.MyUtils import md5, so_tokenizer
from GitSearch.Indexer.NewJavaParser import parse
from GitSearch.Indexer.Indexer_Counter import Counter
from GitSearch.Analyzer.PorterAnalyzer import PorterAnalyzer
from GitSearch.Analyzer.JavaCodeAnalyzer import JavaCodeAnalyzer

# source_path = "/Users/Falcon/Desktop/test/test_result/"
# dest_path = '/Users/Falcon/Desktop/New_Indices/IJA_Indices'
source_path = "/Users/Falcon/Desktop/IJA/Dataset_by_func/"
dest_path = '/Users/Falcon/Desktop/New_Indices/IJA_Indices'

hashes = set()

def java_files_from_dir(directory):
	print "java files from the directory"
	javafiles = (os.path.join(dirpath, f)
		for dirpath, dirnames, files in os.walk(directory)
		for f in files if f.endswith('.java'))
	return javafiles

def generate_indices_from_benchmark(writer, counter):
	javafiles = java_files_from_dir(source_path)
	i = 0
	j = 0
	for javafile in javafiles:
		# print javafile
		i += 1
		if i % 1000 == 0:	#1000개 마다 프린트
			print("Counter: %s" % i)
			print "typed_method_call" + str(counter.typed_method_call_count)
		document = Document()
		document.add(Field("file", javafile, Field.Store.YES, Field.Index.NO))
		try:
			with codecs.open(javafile, "r", encoding='utf-8', errors='ignore') as f:
				file_content = f.read().encode("utf-8", errors='ignore')
			f.close()

			ast = parse(file_content, resolve=False)
			if add_code_keyword_into_document(document, file_content, ast, counter):
				writer.addDocument(document)
				j += 1
				if j % 1000 == 0:
					print "Wrote:: %s files" % j

		except Exception as e:
			print("Error: %s" % e)
			continue
	print "Number of files: %s" % i
	print "Number of duplicates: %s" % len(hashes)
	print "%s files has been indexed" % j

def add_code_keyword_into_document(document, file_content, node, counter):
	# Flag is set when at least 1 code characteristics has been stored
	flag = False
	document.add(Field("line_numbers", str(dict(node["line_numbers"])), Field.Store.YES, Field.Index.NO))
	document.add(Field("hash", str(md5(file_content)), Field.Store.YES, Field.Index.NO))
	document.add(Field("code", so_tokenizer(file_content, False), Field.Store.YES, Field.Index.ANALYZED))

	for m in node["typed_method_call"]:
		if m:
			document.add( Field("typed_method_call", m, Field.Store.YES, Field.Index.ANALYZED))
			counter.typed_method_call_count += 1
			flag = True

	for e in node["extends"]:
		if e:
			document.add(Field("extends", e, Field.Store.NO, Field.Index.ANALYZED))
			counter.extends_count += 1

	for c in node["used_classes"]:
		if c:
			document.add( Field("used_classes", str(c), Field.Store.YES, Field.Index.ANALYZED))
			counter.used_classes_count += 1

	for i in node["class_instance_creation"]:
		if i:
			document.add( Field("class_instance_creation", i, Field.Store.YES, Field.Index.ANALYZED) )
			counter.class_instance_creation_count += 1
			flag = True

	for m in node["methods"]:
		if m:
			document.add(Field("methods", m, Field.Store.YES, Field.Index.ANALYZED))
			counter.methods_count += 1

	for m in node["methods_called"]:
		if m:
			document.add(Field("methods_called", m, Field.Store.YES, Field.Index.ANALYZED))
			counter.methods_called_count += 1
			flag = True

	for m in node["unresolved_method_calls"]:
		if m:
			document.add(Field("unresolved_method_calls", m, Field.Store.YES, Field.Index.ANALYZED))
			counter.unresolved_method_calls_count += 1

	for l in node["literals"]:
		if l:
			document.add( StringField("literals", l, Field.Store.YES))
			counter.literals_count += 1
			flag = True

	return flag

def main():
	try:
		indicesDestination = File(dest_path)
		analyzer = KeywordAnalyzer()
		porter_analyzer = PorterAnalyzer(StandardAnalyzer(Version.LUCENE_CURRENT))
		a = {"code": porter_analyzer, "description": porter_analyzer, "typed_method_call": KeywordAnalyzer(),
			 "extends": KeywordAnalyzer(), "used_classes": KeywordAnalyzer(), "methods": KeywordAnalyzer(),
			 "class_instance_creation": KeywordAnalyzer(), "id": KeywordAnalyzer(), "literals": porter_analyzer}
		wrapper_analyzer = PerFieldAnalyzerWrapper(analyzer, a)
		config = IndexWriterConfig(Version.LUCENE_CURRENT, wrapper_analyzer)

		writer = IndexWriter(SimpleFSDirectory(indicesDestination), config)
		counter = Counter()
		generate_indices_from_benchmark(writer, counter)
		writer.close()

		print "All jobs are done.."
		print str(counter)

	except CorruptIndexException as e:		#when index is corrupt
			e.printStackTrace()
	except LockObtainFailedException as e:	#when other writer is using the index
			e.printStackTrace()
	except IOException as e:	#when directory can't be read/written
			e.printStackTrace()

if __name__ == '__main__':
	print("*** Indexing IJaDataset by func. ***\n")
	start_time = time.time()
	main()
	print("--- %s seconds ---" % (time.time() - start_time))


text: Angular JS Developer Guide


text:
class Main {
  private static void printBool(boolean value) {
    //
  }

  public static void main(String... args) {
      <caret>printBool(args.length != 0);
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?><!--
	수정일                 수정자                          수정내용
  =========     =======    =================================================
  2011.9.7   	정진오     	 	resultMap id="commentDetail"   : FRST_REGISTER_ID -> FRST_REGISTER_NM
  							"selectComment"  : FRST_REGISTER_NM
  							두 요소간 불일치로 인한 에러 발생 수정
  2011.10.18       서준식               insertComment	 : select key 태그 삭제
-->
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="ArticleComment">

	<resultMap id="commentList" type="egovframework.com.cop.cmt.service.CommentVO">
		<result property="commentNo" column="ANSWER_NO"/>
		<result property="nttId" column="NTT_ID"/>
		<result property="bbsId" column="BBS_ID"/>
		<result property="wrterId" column="WRTER_ID"/>
		<result property="wrterNm" column="WRTER_NM"/>
		<result property="commentPassword" column="PASSWORD"/>
		<result property="commentCn" column="ANSWER"/>
		<result property="useAt" column="USE_AT"/>
		<result property="frstRegisterPnttm" column="FRST_REGIST_PNTTM"/>
		<result property="frstRegisterNm" column="FRST_REGISTER_ID"/>
	</resultMap>

	<resultMap id="commentDetail" type="egovframework.com.cop.cmt.service.CommentVO">
		<result property="commentNo" column="ANSWER_NO"/>
		<result property="nttId" column="NTT_ID"/>
		<result property="bbsId" column="BBS_ID"/>
		<result property="wrterId" column="WRTER_ID"/>
		<result property="wrterNm" column="WRTER_NM"/>
		<result property="commentPassword" column="PASSWORD"/>
		<result property="commentCn" column="ANSWER"/>
		<result property="useAt" column="USE_AT"/>
		<result property="frstRegisterPnttm" column="FRST_REGIST_PNTTM"/>
		<result property="frstRegisterNm" column="FRST_REGISTER_NM"/>
	</resultMap>

	<select id="selectArticleCommentList" parameterType="egovframework.com.cop.cmt.service.CommentVO" resultMap="commentList">

		SELECT * FROM ( SELECT rownum rn, TB.* FROM (
			SELECT
				a.ANSWER_NO, a.NTT_ID, a.BBS_ID,
				a.WRTER_ID, a.WRTER_NM, a.PASSWORD, a.ANSWER, a.USE_AT,
				TO_CHAR(a.FRST_REGIST_PNTTM, 'YYYY-MM-DD HH24:MI:SS')
				as FRST_REGIST_PNTTM,
				b.USER_NM as FRST_REGISTER_ID
			FROM
				COMTNCOMMENT a
			LEFT OUTER JOIN COMVNUSERMASTER b
				ON a.FRST_REGISTER_ID = b.ESNTL_ID
			WHERE
				a.BBS_ID = #{bbsId} AND a.NTT_ID = #{nttId}
			AND
				a.USE_AT = 'Y'
			ORDER BY a.FRST_REGIST_PNTTM ASC
			) TB ) Z WHERE rn BETWEEN #{subFirstIndex} + 1 AND #{subFirstIndex} + #{subRecordCountPerPage}

	</select>

	<select id="selectArticleCommentListCnt" parameterType="egovframework.com.cop.cmt.service.CommentVO" resultType="java.lang.Integer">

			SELECT
				COUNT(ANSWER_NO)
			FROM
				COMTNCOMMENT
			WHERE
				BBS_ID = #{bbsId} AND NTT_ID = #{nttId}
			AND
				USE_AT = 'Y'

	</select>

	<insert id="insertArticleComment" parameterType="egovframework.com.cop.cmt.service.CommentVO">

			INSERT INTO COMTNCOMMENT
			(ANSWER_NO, NTT_ID, BBS_ID, WRTER_ID, WRTER_NM, PASSWORD,
			 ANSWER, USE_AT,
			 FRST_REGISTER_ID, FRST_REGIST_PNTTM
			 )
			VALUES
			( #{commentNo}, #{nttId}, #{bbsId}, #{wrterId}, #{wrterNm}, #{commentPassword},
			  #{commentCn}, 'Y',
			  #{frstRegisterId}, SYSDATETIME
			 )

	</insert>

	<update id="deleteArticleComment" parameterType="egovframework.com.cop.cmt.service.CommentVO">

			UPDATE COMTNCOMMENT
			SET USE_AT = 'N'
			WHERE ANSWER_NO = #{commentNo}

	</update>

	<select id="selectArticleCommentDetail" parameterType="egovframework.com.cop.cmt.service.CommentVO" resultMap="commentDetail">

			SELECT
				a.ANSWER_NO, a.NTT_ID, a.BBS_ID,
				a.WRTER_ID, a.WRTER_NM, a.PASSWORD, a.ANSWER, a.USE_AT,
				TO_CHAR(a.FRST_REGIST_PNTTM, 'YYYY-MM-DD HH24:MI:SS')
				as FRST_REGIST_PNTTM,
				b.USER_NM as FRST_REGISTER_NM
			FROM
				COMTNCOMMENT a
			LEFT OUTER JOIN COMVNUSERMASTER b
				ON a.FRST_REGISTER_ID = b.ESNTL_ID
			WHERE
				a.ANSWER_NO = #{commentNo}

	</select>

 	 <update id="updateArticleComment" parameterType="egovframework.com.cop.cmt.service.CommentVO">

			UPDATE COMTNCOMMENT SET
				ANSWER = #{commentCn},
				LAST_UPDUSR_ID = #{lastUpdusrId},
				LAST_UPDT_PNTTM = SYSDATETIME
			WHERE ANSWER_NO = #{commentNo}

 	</update>

</mapper>


text:
<?php

namespace Core;

/**
 * Plugin Base class
 *
 * @package  core
 * @author   Frederic Guillot
 */
abstract class PluginBase extends Base
{
    /**
     * Method called for each request
     *
     * @abstract
     * @access public
     */
    abstract public function initialize();

    /**
     * Returns all classes that needs to be stored in the DI container
     *
     * @access public
     * @return array
     */
    public function getClasses()
    {
        return array();
    }

    /**
     * Listen on internal events
     *
     * @access public
     * @param  string   $event
     * @param  callable $callback
     */
    public function on($event, $callback)
    {
        $container = $this->container;

        $this->container['dispatcher']->addListener($event, function() use ($container, $callback) {
            call_user_func($callback, $container);
        });
    }
}


text:
/**
 *
 */
package cque;

/**
 * @author Xiong
 *
 */
public interface IPolicyObjectPool<E extends IPooledObject> {
	E borrowObject();
}


text:
use strict;
use Getopt::Long;
use Bio::EnsEMBL::Compara::Member;
use Bio::EnsEMBL::Compara::Attribute;
use Bio::EnsEMBL::Compara::DBSQL::DBAdaptor;
use Bio::AlignIO;

$| = 1;

my $help = 0;
my $host;
my $dbname;
my $dbuser = "ensro";

GetOptions('help' => \$help,
	   'host=s' => \$host,
	   'dbname=s' => \$dbname,
	   'dbuser=s' => \$dbuser);

my $species_pair = shift @ARGV;

my $db = new Bio::EnsEMBL::Compara::DBSQL::DBAdaptor(-host   => $host,
                                                     -user   => $dbuser,
                                                     -dbname   => $dbname);

open SP, $species_pair || die "Can't open $species_pair\n";

my ($taxon_id1, $taxon_id2);

while (<SP>) {
  ($taxon_id1, $taxon_id2) = split;
}

close SP;

my $prefix = $taxon_id1 . "_" . $taxon_id2 . "_";
my %pair_count;

my $sql = "select \"All\" as description,min(ds) as min,max(ds) as max,sum(ds)/count(*) as mean,count(*) as count from homology where stable_id like \"$prefix%\"";
my $stats = calculate_average_and_other_things($db,$sql);
$pair_count{$stats->[0]->[0]} = $stats->[0]->[-1];

$sql = "select description,min(ds) as min,max(ds) as max,sum(ds)/count(*) as mean,count(*) as count from homology where stable_id like \"$prefix%\" group by description order by description desc";
foreach my $res (@{calculate_average_and_other_things($db,$sql)}) {
  $pair_count{$res->[0]} = $res->[-1];
  push @{$stats}, $res;
}

print_stats($stats);

print "\nMedian calculation for each category\n";
$sql = "select ds from homology where stable_id like \"$prefix%\" order by ds asc";
my $median_all = calculate_median($db,$sql);
print "All $median_all\n";
$sql = "select ds from homology where stable_id like \"$prefix%\" and description=\"SEED\" order by ds asc";
my $median_seed = calculate_median($db,$sql);
print "SEED $median_seed\n";
$sql = "select ds from homology where stable_id like \"$prefix%\" and description=\"PIP\" order by ds asc";
my $median_pip = calculate_median($db,$sql);
print "PIP $median_pip\n";

my $ds_threshold = $median_all*2;
print "\nApplying All pairs median*2 threshold, keeping pair when ds <= $ds_threshold\n";
$sql = "select \"All\" as description,min(ds) as min,max(ds) as max,sum(ds)/count(*) as mean,count(*) as count from homology where stable_id like \"$prefix%\" and ds<=$ds_threshold";
$stats = calculate_average_and_other_things($db,$sql);
$sql = "select description,min(ds) as min,max(ds) as max,sum(ds)/count(*) as mean,count(*) as count from homology where stable_id like \"$prefix%\" and ds<=$ds_threshold group by description order by description desc";
foreach my $res (@{calculate_average_and_other_things($db,$sql)}) {
  push @{$stats}, $res;
}

print_stats($stats);
print "\nMedian calculation for each category\n";
$sql = "select ds from homology where stable_id like \"$prefix%\"  and ds<=$ds_threshold order by ds asc";
print "All ",calculate_median($db,$sql),"\n";
$sql = "select ds from homology where stable_id like \"$prefix%\" and description=\"SEED\"  and ds<=$ds_threshold order by ds asc";
print "SEED ",calculate_median($db,$sql),"\n";
$sql = "select ds from homology where stable_id like \"$prefix%\" and description=\"PIP\"  and ds<=$ds_threshold order by ds asc";
print "PIP ",calculate_median($db,$sql),"\n";

$ds_threshold = $median_seed*2;
print "\nApplying SEED median*2 threshold, keeping pair when ds <= $ds_threshold\n";
$sql = "select \"All\" as description,min(ds) as min,max(ds) as max,sum(ds)/count(*) as mean,count(*) as count from homology where stable_id like \"$prefix%\" and ds<=$ds_threshold";
$stats = calculate_average_and_other_things($db,$sql);
$sql = "select description,min(ds) as min,max(ds) as max,sum(ds)/count(*) as mean,count(*) as count from homology where stable_id like \"$prefix%\" and ds<=$ds_threshold group by description order by description desc";
foreach my $res (@{calculate_average_and_other_things($db,$sql)}) {
  push @{$stats}, $res;
}

print_stats($stats);

print "\nMedian calculation for each category\n";
$sql = "select ds from homology where stable_id like \"$prefix%\"  and ds<=$ds_threshold order by ds asc";
print "All ",calculate_median($db,$sql),"\n";
$sql = "select ds from homology where stable_id like \"$prefix%\" and description=\"SEED\"  and ds<=$ds_threshold order by ds asc";
print "SEED ",calculate_median($db,$sql),"\n";
$sql = "select ds from homology where stable_id like \"$prefix%\" and description=\"PIP\"  and ds<=$ds_threshold order by ds asc";
print "PIP ",calculate_median($db,$sql),"\n";

$ds_threshold = $median_pip*2;
print "\nApplying PIP pairs median*2 threshold, keeping pair when ds <= $ds_threshold\n";
$sql = "select \"All\" as description,min(ds) as min,max(ds) as max,sum(ds)/count(*) as mean,count(*) as count from homology where stable_id like \"$prefix%\" and ds<=$ds_threshold";
$stats = calculate_average_and_other_things($db,$sql);
$sql = "select description,min(ds) as min,max(ds) as max,sum(ds)/count(*) as mean,count(*) as count from homology where stable_id like \"$prefix%\" and ds<=$ds_threshold group by description order by description desc";
foreach my $res (@{calculate_average_and_other_things($db,$sql)}) {
  push @{$stats}, $res;
}

print_stats($stats);
print "\nMedian calculation for each category\n";
$sql = "select ds from homology where stable_id like \"$prefix%\"  and ds<=$ds_threshold order by ds asc";
print "All ",calculate_median($db,$sql),"\n";
$sql = "select ds from homology where stable_id like \"$prefix%\" and description=\"SEED\"  and ds<=$ds_threshold order by ds asc";
print "SEED ",calculate_median($db,$sql),"\n";
$sql = "select ds from homology where stable_id like \"$prefix%\" and description=\"PIP\"  and ds<=$ds_threshold order by ds asc";
print "PIP ",calculate_median($db,$sql),"\n";

sub calculate_average_and_other_things {
  my ($db, $sql) = @_;
  my $sth = $db->prepare($sql);
  $sth->execute;

  my %column;
  $sth->bind_columns( \( @column{ @{$sth->{NAME_lc} } } ));

  my @stats;
  while ($sth->fetch()) {
    push @stats, [$column{'description'}, $column{'min'}, $column{'max'}, $column{'mean'}, $column{'count'}];
  }
  $sth->finish;
  return \@stats;
}

sub calculate_median {
  my ($db, $sql) = @_;

  my $sth = $db->prepare($sql);
  $sth->execute;

  my %column;
  $sth->bind_columns( \( @column{ @{$sth->{NAME_lc} } } ));

  my @ds_values;
  while ($sth->fetch()) {
    push @ds_values, $column{'ds'};
  }

  $sth->finish;

  my $median;

  if (scalar @ds_values%2 == 0) {
#    print STDERR "modulo1 ",scalar @ds_values%2,"\n";
    $median = ($ds_values[scalar @ds_values/2 -1] + $ds_values[scalar @ds_values/2])/2;
  } else {
#    print STDERR "modulo2 ",scalar @ds_values%2,"\n";
    $median = $ds_values[(scalar @ds_values -1)/2];
  }
  return $median;
}

sub print_stats {
  my ($stats) = @_;
  printf "%-10s\t%8s\t%8s\t%8s\t%8s\t%8s\n","pair type","min(ds)","max(ds)","average(ds)","pair count","%pair lost";
  foreach my $res (@{$stats}) {
    printf "%-10s\t%8.3f\t%8.3f\t%8.3f\t%8i\t%8.1f\n",@{$res},$res->[-1]/$pair_count{$res->[0]}*100;
  }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;

/**
 * Base62 encoding which has the nice property that it does not feature any
 * potential word/line-breaking characters, which means encoded strings can
 * usually be selected in one go on web pages or in the terminal.
 *
 * @see Base62 on Wiki
 *
 * @author vekterli
 */
public class Base62 {

    private static final BaseNCodec INSTANCE = BaseNCodec.of("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");

    public static BaseNCodec codec() {
        return INSTANCE;
    }

}


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

<TITLE>
EtmPointMBean (Java Execution Measurement Library)
</TITLE>

<META NAME="date" CONTENT="2009-03-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

etm.core.jmx

Class EtmPointMBean

java.lang.Object
  etm.core.jmx.EtmPointMBean

All Implemented Interfaces:
javax.management.DynamicMBean

public class EtmPointMBean
extends java.lang.Object
implements javax.management.DynamicMBean

MBean for exporting an EtmPoint to JMX.

Since:

1.2.0

Version:

$Revision: 232 $

Author:

void.fm

Constructor Summary

EtmPointMBean(EtmMonitor aEtmMonitor,
              Aggregate aAggregate)

Method Summary

 java.lang.Object
getAttribute(java.lang.String string)

 javax.management.AttributeList
getAttributes(java.lang.String[] strings)

 javax.management.MBeanInfo
getMBeanInfo()

 java.lang.Object
invoke(java.lang.String string,
       java.lang.Object[] aObjects,
       java.lang.String[] aStrings)

 void
setAttribute(javax.management.Attribute aAttribute)

 javax.management.AttributeList
setAttributes(javax.management.AttributeList aAttributeList)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

EtmPointMBean

public EtmPointMBean(EtmMonitor aEtmMonitor,
                     Aggregate aAggregate)

Method Detail

getAttribute

public java.lang.Object getAttribute(java.lang.String string)
                              throws javax.management.AttributeNotFoundException,
                                     javax.management.MBeanException,
                                     javax.management.ReflectionException

Specified by:
getAttribute in interface javax.management.DynamicMBean

Throws:

javax.management.AttributeNotFoundException

javax.management.MBeanException

javax.management.ReflectionException

setAttribute

public void setAttribute(javax.management.Attribute aAttribute)
                  throws javax.management.AttributeNotFoundException,
                         javax.management.InvalidAttributeValueException,
                         javax.management.MBeanException,
                         javax.management.ReflectionException

Specified by:
setAttribute in interface javax.management.DynamicMBean

Throws:

javax.management.AttributeNotFoundException

javax.management.InvalidAttributeValueException

javax.management.MBeanException

javax.management.ReflectionException

getAttributes

public javax.management.AttributeList getAttributes(java.lang.String[] strings)

Specified by:
getAttributes in interface javax.management.DynamicMBean

setAttributes

public javax.management.AttributeList setAttributes(javax.management.AttributeList aAttributeList)

Specified by:
setAttributes in interface javax.management.DynamicMBean

invoke

public java.lang.Object invoke(java.lang.String string,
                               java.lang.Object[] aObjects,
                               java.lang.String[] aStrings)
                        throws javax.management.MBeanException,
                               javax.management.ReflectionException

Specified by:
invoke in interface javax.management.DynamicMBean

Throws:

javax.management.MBeanException

javax.management.ReflectionException

getMBeanInfo

public javax.management.MBeanInfo getMBeanInfo()

Specified by:
getMBeanInfo in interface javax.management.DynamicMBean

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2004,2005, 2006, 2007 void.fm. All Rights Reserved.


text:
package org.olat.presentation.user.administration;

import org.olat.lms.commons.context.ContextEntry;
import org.olat.presentation.commons.context.ContextEntryControllerCreator;
import org.olat.presentation.framework.core.UserRequest;
import org.olat.presentation.framework.core.control.Controller;
import org.olat.presentation.framework.core.control.WindowControl;
import org.olat.presentation.user.administration.site.UserAdminSite;

/**
 * Description:

 * This class offer a way to launch the UserAdminSite
 *

 * Initial Date: 4 sept. 2009

 *
 * @author srosse
 */
public class UserAdminContextEntryControllerCreator implements ContextEntryControllerCreator {

    /**
     * org.olat.presentation.framework.control.WindowControl)
     */
    @Override
    public Controller createController(final ContextEntry ce, final UserRequest ureq, final WindowControl wControl) {
        return null;
    }

    /**
	 */
    @Override
    public String getSiteClassName(final ContextEntry ce) {
        // opened as site not tab
        return UserAdminSite.class.getName();
    }

    /**
	 */
    @Override
    public String getTabName(final ContextEntry ce) {
        return null;
    }

    @Override
    public boolean validateContextEntryAndShowError(final ContextEntry ce, final UserRequest ureq, final WindowControl wControl) {
        return true;
    }
}


text:
@interface NounceAppDelegate : NSObject <NSApplicationDelegate> {
	NCEventController *eventController;
	NCNotificationController *notificationController;
	NCNotificationPaneController *notificationPaneController;
	NCNotificationStatusController *notificationStatusController;
}

@property (retain) NCEventController *eventController;
@property (retain) NCNotificationController *notificationController;
@property (retain) NCNotificationPaneController *notificationPaneController;
@property (retain) NCNotificationStatusController *notificationStatusController;

@end


text:
package org.jvnet.hudson.test.recipes;

import org.jvnet.hudson.test.HudsonTestCase;
import org.jvnet.hudson.test.HudsonHomeLoader.Local;

import java.lang.annotation.Documented;
import java.lang.annotation.Target;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static java.lang.annotation.ElementType.METHOD;

/**
 * Runs a test case with a data set local to test method or the test class.
 *
 *

 * This recipe allows your test case to start with the preset <tt>HUDSON_HOME</tt> data loaded
 * either from your test method or from the test class.
 *
 *

 * For example, if the test method if <tt>org.acme.FooTest.testBar()</tt>, then
 * you can have your test data in one of the following places in resources folder
 * (typically <tt>src/test/resources</tt>):
 *
 *

 *

 * Under <tt>org/acme/FooTest/testBar</tt> directory (that is, you'll have
 * <tt>org/acme/FooTest/testBar/config.xml</tt>), in the same layout as in the real <tt>HUDSON_HOME</tt> directory.
 *

 * In <tt>org/acme/FooTest/testBar.zip</tt> as a zip file.
 *

 * Under <tt>org/acme/FooTest</tt> directory (that is, you'll have
 * <tt>org/acme/FooTest/config.xml</tt>), in the same layout as in the real <tt>HUDSON_HOME</tt> directory.
 *

 * In <tt>org/acme/FooTest.zip</tt> as a zip file.
 *

 *
 *

 * Search is performed in this specific order. The fall back mechanism allows you to write
 * one test class that interacts with different aspects of the same data set, by associating
 * the dataset with a test class, or have a data set local to a specific test method.
 *
 *

 * The choice of zip and directory depends on the nature of the test data, as well as the size of it.
 *
 * @author Kohsuke Kawaguchi
 */
@Documented
@Recipe(LocalData.RunnerImpl.class)
@Target(METHOD)
@Retention(RUNTIME)
public @interface LocalData {
    public class RunnerImpl extends Recipe.Runner<LocalData> {
        public void setup(HudsonTestCase testCase, LocalData recipe) throws Exception {
            testCase.with(new Local(testCase.getClass().getMethod(testCase.getName())));
        }
    }
}


text:
/*
 * @test
 * @bug 5030212
 * @summary please add a typesafe cast for Class<?> types
 * @author gafter
 *
 * @compile -Xlint:unchecked -Werror BasicUnit.java
 * @run main BasicUnit
 */

interface Int {
    void main();
}

class MyInt implements Int {
    public void main() {
        System.out.println("Hello, world!");
    }
}

public class BasicUnit {
    static <T extends Int> T factory(Class<T> c) throws Throwable {
        return c.newInstance();
    }
    public static void main(String[] args) throws Throwable {
        factory(Class.forName("MyInt").asSubclass(Int.class)).main();
    }
}


text:
using blink::WebCanvas;
using blink::WebMediaPlayer;
using blink::WebRect;
using blink::WebSize;

namespace content {

namespace {

// This function copies a YV12 or NATIVE_TEXTURE to a new YV12
// media::VideoFrame.
scoped_refptr<media::VideoFrame> CopyFrameToYV12(
    const scoped_refptr<media::VideoFrame>& frame,
    media::SkCanvasVideoRenderer* video_renderer) {
  DCHECK(frame->format() == media::VideoFrame::YV12 ||
         frame->format() == media::VideoFrame::I420 ||
         frame->format() == media::VideoFrame::NATIVE_TEXTURE);
  scoped_refptr<media::VideoFrame> new_frame =
      media::VideoFrame::CreateFrame(media::VideoFrame::YV12,
                                     frame->coded_size(),
                                     frame->visible_rect(),
                                     frame->natural_size(),
                                     frame->timestamp());

  if (frame->format() == media::VideoFrame::NATIVE_TEXTURE) {
    SkBitmap bitmap;
    bitmap.allocN32Pixels(frame->visible_rect().width(),
                          frame->visible_rect().height());
    SkCanvas canvas(bitmap);

    cc::ContextProvider* provider =
        RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
    if (provider) {
      media::Context3D context_3d =
          media::Context3D(provider->ContextGL(), provider->GrContext());
      DCHECK(context_3d.gl);
      video_renderer->Copy(frame.get(), &canvas, context_3d);
    } else {
      // GPU Process crashed.
      bitmap.eraseColor(SK_ColorTRANSPARENT);
    }
    media::CopyRGBToVideoFrame(
        reinterpret_cast<uint8*>(bitmap.getPixels()),
        bitmap.rowBytes(),
        frame->visible_rect(),
        new_frame.get());
  } else {
    size_t number_of_planes =
        media::VideoFrame::NumPlanes(frame->format());
    for (size_t i = 0; i < number_of_planes; ++i) {
      media::CopyPlane(i, frame->data(i), frame->stride(i),
                       frame->rows(i), new_frame.get());
    }
  }
  return new_frame;
}

}  // anonymous namespace

WebMediaPlayerMS::WebMediaPlayerMS(
    blink::WebFrame* frame,
    blink::WebMediaPlayerClient* client,
    base::WeakPtr<media::WebMediaPlayerDelegate> delegate,
    media::MediaLog* media_log,
    scoped_ptr<MediaStreamRendererFactory> factory)
    : frame_(frame),
      network_state_(WebMediaPlayer::NetworkStateEmpty),
      ready_state_(WebMediaPlayer::ReadyStateHaveNothing),
      buffered_(static_cast<size_t>(0)),
      volume_(1.0f),
      client_(client),
      delegate_(delegate),
      paused_(true),
      current_frame_used_(false),
      pending_repaint_(false),
      video_frame_provider_client_(NULL),
      received_first_frame_(false),
      total_frame_count_(0),
      dropped_frame_count_(0),
      media_log_(media_log),
      renderer_factory_(factory.Pass()) {
  DVLOG(1) << "WebMediaPlayerMS::ctor";
  media_log_->AddEvent(
      media_log_->CreateEvent(media::MediaLogEvent::WEBMEDIAPLAYER_CREATED));
}

WebMediaPlayerMS::~WebMediaPlayerMS() {
  DVLOG(1) << "WebMediaPlayerMS::dtor";
  DCHECK(thread_checker_.CalledOnValidThread());

  SetVideoFrameProviderClient(NULL);
  GetClient()->setWebLayer(NULL);

  if (video_frame_provider_.get())
    video_frame_provider_->Stop();

  if (audio_renderer_.get())
    audio_renderer_->Stop();

  media_log_->AddEvent(
      media_log_->CreateEvent(media::MediaLogEvent::WEBMEDIAPLAYER_DESTROYED));

  if (delegate_.get())
    delegate_->PlayerGone(this);
}

void WebMediaPlayerMS::load(LoadType load_type,
                            const blink::WebURL& url,
                            CORSMode cors_mode) {
  DVLOG(1) << "WebMediaPlayerMS::load";
  DCHECK(thread_checker_.CalledOnValidThread());

  // TODO(acolwell): Change this to DCHECK_EQ(load_type,
  // LoadTypeMediaStream) once Blink-side changes land.
  DCHECK_NE(load_type, LoadTypeMediaSource);

  GURL gurl(url);

  SetNetworkState(WebMediaPlayer::NetworkStateLoading);
  SetReadyState(WebMediaPlayer::ReadyStateHaveNothing);
  media_log_->AddEvent(media_log_->CreateLoadEvent(url.spec()));

  video_frame_provider_ = renderer_factory_->GetVideoFrameProvider(
      url,
      base::Bind(&WebMediaPlayerMS::OnSourceError, AsWeakPtr()),
      base::Bind(&WebMediaPlayerMS::OnFrameAvailable, AsWeakPtr()));

  RenderFrame* frame = RenderFrame::FromWebFrame(frame_);
  audio_renderer_ = renderer_factory_->GetAudioRenderer(
    url,
    frame->GetRenderView()->GetRoutingID(),
    frame->GetRoutingID());

  if (video_frame_provider_.get() || audio_renderer_.get()) {
    if (audio_renderer_.get()) {
      audio_renderer_->SetVolume(volume_);
      audio_renderer_->Start();
    }

    if (video_frame_provider_.get()) {
      video_frame_provider_->Start();
    } else {
      // This is audio-only mode.
      DCHECK(audio_renderer_.get());
      SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata);
      SetReadyState(WebMediaPlayer::ReadyStateHaveEnoughData);
    }
  } else {
    SetNetworkState(WebMediaPlayer::NetworkStateNetworkError);
  }
}

void WebMediaPlayerMS::play() {
  DVLOG(1) << "WebMediaPlayerMS::play";
  DCHECK(thread_checker_.CalledOnValidThread());

  if (paused_) {
    if (video_frame_provider_.get())
      video_frame_provider_->Play();

    if (audio_renderer_.get())
      audio_renderer_->Play();

    if (delegate_.get())
      delegate_->DidPlay(this);
  }

  paused_ = false;

  media_log_->AddEvent(media_log_->CreateEvent(media::MediaLogEvent::PLAY));
}

void WebMediaPlayerMS::pause() {
  DVLOG(1) << "WebMediaPlayerMS::pause";
  DCHECK(thread_checker_.CalledOnValidThread());

  if (video_frame_provider_.get())
    video_frame_provider_->Pause();

  if (!paused_) {
    if (audio_renderer_.get())
      audio_renderer_->Pause();

    if (delegate_.get())
      delegate_->DidPause(this);
  }

  paused_ = true;

  media_log_->AddEvent(media_log_->CreateEvent(media::MediaLogEvent::PAUSE));

  if (!current_frame_.get())
    return;

  // Copy the frame so that rendering can show the last received frame.
  // The original frame must not be referenced when the player is paused since
  // there might be a finite number of available buffers. E.g, video that
  // originates from a video camera.
  scoped_refptr<media::VideoFrame> new_frame =
      CopyFrameToYV12(current_frame_, &video_renderer_);

  base::AutoLock auto_lock(current_frame_lock_);
  current_frame_ = new_frame;
}

bool WebMediaPlayerMS::supportsSave() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  return false;
}

void WebMediaPlayerMS::seek(double seconds) {
  DCHECK(thread_checker_.CalledOnValidThread());
}

void WebMediaPlayerMS::setRate(double rate) {
  DCHECK(thread_checker_.CalledOnValidThread());
}

void WebMediaPlayerMS::setVolume(double volume) {
  DCHECK(thread_checker_.CalledOnValidThread());
  DVLOG(1) << "WebMediaPlayerMS::setVolume(volume=" << volume << ")";
  volume_ = volume;
  if (audio_renderer_.get())
    audio_renderer_->SetVolume(volume_);
}

void WebMediaPlayerMS::setPreload(WebMediaPlayer::Preload preload) {
  DCHECK(thread_checker_.CalledOnValidThread());
}

bool WebMediaPlayerMS::hasVideo() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  return (video_frame_provider_.get() != NULL);
}

bool WebMediaPlayerMS::hasAudio() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  return (audio_renderer_.get() != NULL);
}

blink::WebSize WebMediaPlayerMS::naturalSize() const {
  DCHECK(thread_checker_.CalledOnValidThread());

  gfx::Size size;
  if (current_frame_.get())
    size = current_frame_->natural_size();
  DVLOG(3) << "WebMediaPlayerMS::naturalSize, " << size.ToString();
  return blink::WebSize(size);
}

bool WebMediaPlayerMS::paused() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  return paused_;
}

bool WebMediaPlayerMS::seeking() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  return false;
}

double WebMediaPlayerMS::duration() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  return std::numeric_limits<double>::infinity();
}

double WebMediaPlayerMS::currentTime() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  if (current_time_.ToInternalValue() != 0) {
    return current_time_.InSecondsF();
  } else if (audio_renderer_.get()) {
    return audio_renderer_->GetCurrentRenderTime().InSecondsF();
  }
  return 0.0;
}

WebMediaPlayer::NetworkState WebMediaPlayerMS::networkState() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  DVLOG(1) << "WebMediaPlayerMS::networkState, state:" << network_state_;
  return network_state_;
}

WebMediaPlayer::ReadyState WebMediaPlayerMS::readyState() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  DVLOG(1) << "WebMediaPlayerMS::readyState, state:" << ready_state_;
  return ready_state_;
}

blink::WebTimeRanges WebMediaPlayerMS::buffered() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  return buffered_;
}

blink::WebTimeRanges WebMediaPlayerMS::seekable() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  return blink::WebTimeRanges();
}

bool WebMediaPlayerMS::didLoadingProgress() {
  DCHECK(thread_checker_.CalledOnValidThread());
  return true;
}

void WebMediaPlayerMS::paint(blink::WebCanvas* canvas,
                             const blink::WebRect& rect,
                             unsigned char alpha,
                             SkXfermode::Mode mode) {
  DVLOG(3) << "WebMediaPlayerMS::paint";
  DCHECK(thread_checker_.CalledOnValidThread());

  media::Context3D context_3d;
  if (current_frame_.get() &&
      current_frame_->format() == media::VideoFrame::NATIVE_TEXTURE) {
    cc::ContextProvider* provider =
        RenderThreadImpl::current()->SharedMainThreadContextProvider().get();
    // GPU Process crashed.
    if (!provider)
      return;
    context_3d = media::Context3D(provider->ContextGL(), provider->GrContext());
    DCHECK(context_3d.gl);
  }
  gfx::RectF dest_rect(rect.x, rect.y, rect.width, rect.height);
  video_renderer_.Paint(current_frame_, canvas, dest_rect, alpha, mode,
                        media::VIDEO_ROTATION_0, context_3d);

  {
    base::AutoLock auto_lock(current_frame_lock_);
    if (current_frame_.get())
      current_frame_used_ = true;
  }
}

bool WebMediaPlayerMS::hasSingleSecurityOrigin() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  return true;
}

bool WebMediaPlayerMS::didPassCORSAccessCheck() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  return true;
}

double WebMediaPlayerMS::mediaTimeForTimeValue(double timeValue) const {
  return media::ConvertSecondsToTimestamp(timeValue).InSecondsF();
}

unsigned WebMediaPlayerMS::decodedFrameCount() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  DVLOG(1) << "WebMediaPlayerMS::decodedFrameCount, " << total_frame_count_;
  return total_frame_count_;
}

unsigned WebMediaPlayerMS::droppedFrameCount() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  DVLOG(1) << "WebMediaPlayerMS::droppedFrameCount, " << dropped_frame_count_;
  return dropped_frame_count_;
}

unsigned WebMediaPlayerMS::audioDecodedByteCount() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  NOTIMPLEMENTED();
  return 0;
}

unsigned WebMediaPlayerMS::videoDecodedByteCount() const {
  DCHECK(thread_checker_.CalledOnValidThread());
  NOTIMPLEMENTED();
  return 0;
}

bool WebMediaPlayerMS::copyVideoTextureToPlatformTexture(
    blink::WebGraphicsContext3D* web_graphics_context,
    unsigned int texture,
    unsigned int level,
    unsigned int internal_format,
    unsigned int type,
    bool premultiply_alpha,
    bool flip_y) {
  TRACE_EVENT0("media", "WebMediaPlayerMS:copyVideoTextureToPlatformTexture");
  DCHECK(thread_checker_.CalledOnValidThread());

  scoped_refptr<media::VideoFrame> video_frame;
  {
    base::AutoLock auto_lock(current_frame_lock_);
    video_frame = current_frame_;
  }

  if (!video_frame.get() ||
      video_frame->format() != media::VideoFrame::NATIVE_TEXTURE) {
    return false;
  }

  // TODO(dshwang): need more elegant way to convert WebGraphicsContext3D to
  // GLES2Interface.
  gpu::gles2::GLES2Interface* gl =
      static_cast<gpu_blink::WebGraphicsContext3DImpl*>(web_graphics_context)
          ->GetGLInterface();
  media::SkCanvasVideoRenderer::CopyVideoFrameTextureToGLTexture(
      gl, video_frame.get(), texture, level, internal_format, type,
      premultiply_alpha, flip_y);
  return true;
}

void WebMediaPlayerMS::SetVideoFrameProviderClient(
    cc::VideoFrameProvider::Client* client) {
  // This is called from both the main renderer thread and the compositor
  // thread (when the main thread is blocked).
  if (video_frame_provider_client_)
    video_frame_provider_client_->StopUsingProvider();
  video_frame_provider_client_ = client;
}

scoped_refptr<media::VideoFrame> WebMediaPlayerMS::GetCurrentFrame() {
  DVLOG(3) << "WebMediaPlayerMS::GetCurrentFrame";
  base::AutoLock auto_lock(current_frame_lock_);
  DCHECK(!pending_repaint_);
  if (!current_frame_.get())
    return NULL;
  pending_repaint_ = true;
  current_frame_used_ = true;
  return current_frame_;
}

void WebMediaPlayerMS::PutCurrentFrame(
    const scoped_refptr<media::VideoFrame>& frame) {
  DVLOG(3) << "WebMediaPlayerMS::PutCurrentFrame";
  DCHECK(pending_repaint_);
  pending_repaint_ = false;
}

void WebMediaPlayerMS::OnFrameAvailable(
    const scoped_refptr<media::VideoFrame>& frame) {
  DVLOG(3) << "WebMediaPlayerMS::OnFrameAvailable";
  DCHECK(thread_checker_.CalledOnValidThread());
  ++total_frame_count_;
  if (!received_first_frame_) {
    received_first_frame_ = true;
    {
      base::AutoLock auto_lock(current_frame_lock_);
      DCHECK(!current_frame_used_);
      current_frame_ = frame;
    }
    SetReadyState(WebMediaPlayer::ReadyStateHaveMetadata);
    SetReadyState(WebMediaPlayer::ReadyStateHaveEnoughData);
    GetClient()->sizeChanged();

    if (video_frame_provider_.get()) {
      video_weblayer_.reset(new cc_blink::WebLayerImpl(
          cc::VideoLayer::Create(this, media::VIDEO_ROTATION_0)));
      video_weblayer_->setOpaque(true);
      GetClient()->setWebLayer(video_weblayer_.get());
    }
  }

  // Do not update |current_frame_| when paused.
  if (paused_)
    return;

  bool size_changed = !current_frame_.get() ||
                      current_frame_->natural_size() != frame->natural_size();

  {
    base::AutoLock auto_lock(current_frame_lock_);
    if (!current_frame_used_ && current_frame_.get())
      ++dropped_frame_count_;
    current_frame_ = frame;
    current_time_ = frame->timestamp();
    current_frame_used_ = false;
  }

  if (size_changed)
    GetClient()->sizeChanged();

  GetClient()->repaint();
}

void WebMediaPlayerMS::RepaintInternal() {
  DVLOG(1) << "WebMediaPlayerMS::RepaintInternal";
  DCHECK(thread_checker_.CalledOnValidThread());
  GetClient()->repaint();
}

void WebMediaPlayerMS::OnSourceError() {
  DVLOG(1) << "WebMediaPlayerMS::OnSourceError";
  DCHECK(thread_checker_.CalledOnValidThread());
  SetNetworkState(WebMediaPlayer::NetworkStateFormatError);
  RepaintInternal();
}

void WebMediaPlayerMS::SetNetworkState(WebMediaPlayer::NetworkState state) {
  DCHECK(thread_checker_.CalledOnValidThread());
  network_state_ = state;
  // Always notify to ensure client has the latest value.
  GetClient()->networkStateChanged();
}

void WebMediaPlayerMS::SetReadyState(WebMediaPlayer::ReadyState state) {
  DCHECK(thread_checker_.CalledOnValidThread());
  ready_state_ = state;
  // Always notify to ensure client has the latest value.
  GetClient()->readyStateChanged();
}

blink::WebMediaPlayerClient* WebMediaPlayerMS::GetClient() {
  DCHECK(thread_checker_.CalledOnValidThread());
  DCHECK(client_);
  return client_;
}

}  // namespace content


text:
layout: post
title: "Purple Worm"
date: 2017-09-10
tags: [gargantuan, monstrosity, cr15, monster-manual]
---

**Gargantuan monstrosity, unaligned**

**Armor Class** 18 (natural armor)

**Hit Points** 247 (15d20+90)

**Speed** 50 ft., burrow 30 ft.

|   STR   |   DEX   |   CON   |   INT   |   WIS   |   CHA   |
|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|
| 28 (+9) | 7 (-2) | 22 (+6) | 1 (-5) | 8 (-1) | 4 (-3) |

**Saving Throws** Con +11, Wis +4

**Senses** blindsight 30 ft., tremorsense 60 ft.

**Challenge** 15 (13,000 XP)

***Tunneler.*** The worm can burrow through solid rock at half its burrow speed and leaves a 10-foot-diameter tunnel in its wake.

**Actions**

***Multiattack.*** The worm makes two attacks: one with its bite and one with its stinger.

***Bite.*** Melee Weapon Attack: +9 to hit, reach 10 ft., one target. Hit: 22 (3d8 + 9) piercing damage. If the target is a Large or smaller creature, it must succeed on a DC 19 Dexterity saving throw or be swallowed by the worm. A swallowed creature is blinded and restrained, it has total cover against attacks and other effects outside the worm, and it takes 21 (6d6) acid damage at the start of each of the worm's turns.

If the worm takes 30 damage or more on a single turn from a creature inside it, the worm must succeed on a DC 21 Constitution saving throw at the end of that turn or regurgitate all swallowed creatures, which fall prone in a space within 10 feet of the worm. If the worm dies, a swallowed creature is no longer restrained by it and can escape from the corpse by using 20 feet of movement, exiting prone.

***Tail Stinger.*** Melee Weapon Attack: +9 to hit, reach 10 ft., one creature. Hit: 19 (3d6 + 9) piercing damage, and the target must make a DC 19 Constitution saving throw, taking 42 (12d6) poison damage on a failed save, or half as much damage on a successful one.


text:
import * as bodyParser from 'body-parser';
import * as cookieParser from 'cookie-parser';
import * as express from 'express';
import 'isomorphic-fetch';
import * as next from 'next';
import { resolve } from 'path';
import * as logger from 'winston';
import { apiSyncUserRepositories, apiRssFeed } from './api';
import cron from './cron';

// TODO add sentry to catch errors (client + server)

const dev = process.env.NODE_ENV !== 'production';
const dir = resolve(__dirname, '..', 'client');
const app = next({ dev, dir });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();
  server.use(cookieParser());
  server.use(bodyParser.json());

  server.post('/api/sync-stars', apiSyncUserRepositories);

  server.get('/users/:userId/rss', apiRssFeed);

  server.get(
    '/release/:repositoryType/:repositoryName1/:repositoryName2/:releaseTagName',
    (req, res) => {
      const actualPage = '/release';
      const queryParams = {
        repositoryType: req.params.repositoryType,
        repositoryName: `${req.params.repositoryName1}/${req.params
          .repositoryName2}`,
        releaseTagName: req.params.releaseTagName,
      };
      app.render(req, res, actualPage, queryParams);
    }
  );

  server.get('*', (req, res) => {
    handle(req, res);
  });

  server.listen(3000, () => {
    logger.log('info', 'App listening on port 3000!');

    // Start cron tasks
    cron();
  });
});


text:
set(CMAKE_DEPENDS_LANGUAGES
  "CXX"
  )
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_CXX
  "/cygdrive/c/Users/Owner/Desktop/Github-Code/CppLibraries/Date/main.cpp" "/cygdrive/c/Users/Owner/Desktop/Github-Code/CppLibraries/Date/cmake-build-debug/CMakeFiles/Date.dir/main.cpp.o"
  "/cygdrive/c/Users/Owner/Desktop/Github-Code/CppLibraries/Date/sources/date.cpp" "/cygdrive/c/Users/Owner/Desktop/Github-Code/CppLibraries/Date/cmake-build-debug/CMakeFiles/Date.dir/sources/date.cpp.o"
  "/cygdrive/c/Users/Owner/Desktop/Github-Code/CppLibraries/Date/sources/date_operators.cpp" "/cygdrive/c/Users/Owner/Desktop/Github-Code/CppLibraries/Date/cmake-build-debug/CMakeFiles/Date.dir/sources/date_operators.cpp.o"
  )
set(CMAKE_CXX_COMPILER_ID "GNU")

# The include file search paths:
set(CMAKE_CXX_TARGET_INCLUDE_PATH
  )

# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
  )

# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")


text:
/**
 * This file is part of the CernVM File System.
 */

#include "cvmfs_config.h"
#include "quota.h"

#include <errno.h>
#include <unistd.h>

#include <cstdlib>

#include "logging.h"
#include "smalloc.h"
#include "util_concurrency.h"

using namespace std;  // NOLINT

const uint32_t QuotaManager::kProtocolRevision = 2;

void QuotaManager::BroadcastBackchannels(const string &message) {
  assert(message.length() > 0);
  MutexLockGuard lock_guard(*lock_back_channels_);

  for (map<shash::Md5, int>::iterator i = back_channels_.begin(),
       iend = back_channels_.end(); i != iend; )
  {
    LogCvmfs(kLogQuota, kLogDebug, "broadcasting %s to %s",
             message.c_str(), i->first.ToString().c_str());
    int written = write(i->second, message.data(), message.length());
    if (written < 0) written = 0;
    if (static_cast<unsigned>(written) != message.length()) {
      bool remove_backchannel = errno != EAGAIN;
      LogCvmfs(kLogQuota, kLogDebug | kLogSyslogWarn,
               "failed to broadcast '%s' to %s (written %d, error %d)",
               message.c_str(), i->first.ToString().c_str(), written, errno);
      if (remove_backchannel) {
        LogCvmfs(kLogQuota, kLogDebug | kLogSyslogWarn,
                 "removing back channel %s", i->first.ToString().c_str());
        map<shash::Md5, int>::iterator remove_me = i;
        ++i;
        close(remove_me->second);
        back_channels_.erase(remove_me);
      } else {
        ++i;
      }
    } else {
      ++i;
    }
  }
}

QuotaManager::QuotaManager() : protocol_revision_(0) {
  lock_back_channels_ =
    reinterpret_cast<pthread_mutex_t *>(smalloc(sizeof(pthread_mutex_t)));
  int retval = pthread_mutex_init(lock_back_channels_, NULL);
  assert(retval == 0);
}

QuotaManager::~QuotaManager() {
  for (map<shash::Md5, int>::iterator i = back_channels_.begin(),
       iend = back_channels_.end(); i != iend; ++i)
  {
    close(i->second);
  }
  pthread_mutex_destroy(lock_back_channels_);
  free(lock_back_channels_);
}


text:
Spree::Sample.load_sample("variants")

location = Spree::StockLocation.first_or_create! name: 'default'
location.active = true
location.country =  Spree::Country.where(iso: 'US').first
location.save!

Spree::Variant.all.each do |variant|
  variant.stock_items.each do |stock_item|
    Spree::StockMovement.create(:quantity => 10, :stock_item => stock_item)
  end
end


text:
package mesosphere.marathon.api

import mesosphere.marathon.Protos.MarathonTask
import mesosphere.marathon.state.{ AppDefinition, Group, GroupManager, PathId, Timestamp }
import mesosphere.marathon.tasks.{ MarathonTasks, TaskTracker }
import mesosphere.marathon.upgrade.DeploymentPlan
import mesosphere.marathon.{ AppLockedException, MarathonSchedulerService, MarathonSpec, UnknownAppException }
import mesosphere.mesos.protos.Implicits.slaveIDToProto
import mesosphere.mesos.protos.SlaveID
import org.mockito.ArgumentCaptor
import org.mockito.Matchers.any
import org.mockito.Mockito._
import org.scalatest.concurrent.ScalaFutures
import org.scalatest.mock.MockitoSugar
import org.scalatest.{ BeforeAndAfterAll, Matchers }

import scala.concurrent.Future

class TaskKillerTest extends MarathonSpec
    with Matchers
    with BeforeAndAfterAll
    with MockitoSugar
    with ScalaFutures {

  var tracker: TaskTracker = _
  var service: MarathonSchedulerService = _
  var groupManager: GroupManager = _
  var taskKiller: TaskKiller = _

  before {
    service = mock[MarathonSchedulerService]
    tracker = mock[TaskTracker]
    groupManager = mock[GroupManager]
    taskKiller = new TaskKiller(tracker, groupManager, service)
  }

  test("AppNotFound") {
    val appId = PathId("invalid")
    when(tracker.contains(appId)).thenReturn(false)

    val result = taskKiller.kill(appId, (tasks) => Set.empty[MarathonTask], force = true)
    result.failed.futureValue shouldEqual UnknownAppException(appId)
  }

  test("AppNotFound with scaling") {
    val appId = PathId("invalid")
    when(tracker.contains(appId)).thenReturn(false)

    val result = taskKiller.killAndScale(appId, (tasks) => Set.empty[MarathonTask], force = true)
    result.failed.futureValue shouldEqual UnknownAppException(appId)
  }

  test("KillRequested with scaling") {
    val appId = PathId(List("my", "app"))
    val now = Timestamp.now()
    val task1 = MarathonTasks.makeTask(
      "task-1", "host", ports = Nil, attributes = Nil, version = now, now = now,
      slaveId = SlaveID("1")
    )
    val task2 = MarathonTasks.makeTask(
      "task-2", "host", ports = Nil, attributes = Nil, version = Timestamp.now(), now = now,
      slaveId = SlaveID("1")
    )
    val tasksToKill = Set(task1, task2)
    val originalAppDefinition = AppDefinition(appId, instances = 23)

    when(tracker.contains(appId)).thenReturn(true)
    when(groupManager.group(appId.parent)).thenReturn(Future.successful(Some(Group.emptyWithId(appId.parent))))

    val appIdCaptor = ArgumentCaptor.forClass(classOf[PathId])
    val appUpdateCaptor = ArgumentCaptor.forClass(classOf[(Option[AppDefinition]) => AppDefinition])
    val forceCaptor = ArgumentCaptor.forClass(classOf[Boolean])
    val toKillCaptor = ArgumentCaptor.forClass(classOf[Set[MarathonTask]])
    val expectedDeploymentPlan = DeploymentPlan.empty
    when(groupManager.updateApp(
      appId = appIdCaptor.capture(),
      fn = appUpdateCaptor.capture(),
      version = any[Timestamp](),
      force = forceCaptor.capture(),
      toKill = toKillCaptor.capture())
    ).thenReturn(Future.successful(expectedDeploymentPlan))

    val result = taskKiller.killAndScale(appId, (tasks) => tasksToKill, force = true)
    result.futureValue shouldEqual expectedDeploymentPlan
    appIdCaptor.getValue shouldEqual appId
    appUpdateCaptor.getValue.apply(Some(originalAppDefinition)) shouldEqual originalAppDefinition.copy(instances = 21)
    forceCaptor.getValue shouldEqual true
    toKillCaptor.getValue shouldEqual tasksToKill
  }

  test("KillRequested without scaling") {
    val appId = PathId(List("my", "app"))
    val tasksToKill = Set(MarathonTask.getDefaultInstance)
    when(tracker.contains(appId)).thenReturn(true)

    val result = taskKiller.kill(appId, (tasks) => tasksToKill, force = true)
    result.futureValue shouldEqual tasksToKill
    verify(service, times(1)).killTasks(appId, tasksToKill)
    verifyNoMoreInteractions(groupManager)
  }

  test("Kill and scale w/o force should fail if there is a deployment") {
    val appId = PathId(List("my", "app"))
    val now = Timestamp.now()
    val task1 = MarathonTasks.makeTask(
      "task-1", "host", ports = Nil, attributes = Nil, version = Timestamp.now(), now = now,
      slaveId = SlaveID("1")
    )
    val task2 = MarathonTasks.makeTask(
      "task-2", "host", ports = Nil, attributes = Nil, version = Timestamp.now(), now = now,
      slaveId = SlaveID("1")
    )
    val tasksToKill = Set(task1, task2)

    when(tracker.contains(appId)).thenReturn(true)
    when(groupManager.group(appId.parent)).thenReturn(Future.successful(Some(Group.emptyWithId(appId.parent))))
    val forceCaptor = ArgumentCaptor.forClass(classOf[Boolean])
    when(groupManager.updateApp(any(), any(), any(), forceCaptor.capture(), any())
    ).thenReturn(Future.failed(AppLockedException()))

    val result = taskKiller.killAndScale(appId, (tasks) => tasksToKill, force = false)
    forceCaptor.getValue shouldEqual false
    result.failed.futureValue shouldEqual AppLockedException()
  }

}


text:
title: Oliver Smith
gender: male
submitted: false
headshot: xK6sX2f
---


text:
/**
 * @file
 **/

#include "modules/planning/tasks/deciders/st_bounds_decider/st_guide_line.h"

namespace apollo {
namespace planning {

constexpr double kSpeedGuideLineResolution = 0.1;

void STGuideLine::Init(double desired_v) {
  s0_ = 0.0;
  t0_ = 0.0;
  v0_ = desired_v;
}

void STGuideLine::Init(
    double desired_v,
    const std::vector<common::TrajectoryPoint> &speed_reference) {
  s0_ = 0.0;
  t0_ = 0.0;
  v0_ = desired_v;
  DiscretizedTrajectory discrete_speed_reference(speed_reference);
  double total_time = discrete_speed_reference.GetTemporalLength();
  guideline_speed_data_.clear();
  for (double t = 0; t <= total_time; t += kSpeedGuideLineResolution) {
    const common::TrajectoryPoint trajectory_point =
        discrete_speed_reference.Evaluate(t);
    guideline_speed_data_.AppendSpeedPoint(
        trajectory_point.path_point().s(), trajectory_point.relative_time(),
        trajectory_point.v(), trajectory_point.a(), trajectory_point.da());
  }
}

double STGuideLine::GetGuideSFromT(double t) {
  common::SpeedPoint speed_point;
  if (t < guideline_speed_data_.TotalTime() &&
      guideline_speed_data_.EvaluateByTime(t, &speed_point)) {
    s0_ = speed_point.s();
    t0_ = t;
    return speed_point.s();
  }
  return s0_ + (t - t0_) * v0_;
}

void STGuideLine::UpdateBlockingInfo(const double t, const double s_block,
                                     const bool is_lower_block) {
  if (is_lower_block) {
    if (GetGuideSFromT(t) < s_block) {
      s0_ = s_block;
      t0_ = t;
    }
  } else {
    if (GetGuideSFromT(t) > s_block) {
      s0_ = s_block;
      t0_ = t;
    }
  }
}

}  // namespace planning
}  // namespace apollo


text: Portfolio/Resume Website


text:
package com.spotify.heroic.aggregation.cardinality;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.spotify.heroic.aggregation.BucketAggregationInstance;
import com.spotify.heroic.metric.Payload;
import com.spotify.heroic.metric.MetricType;

public class DistributedCardinalityInstance extends BucketAggregationInstance<CardinalityBucket> {
    private final CardinalityMethod method;

    @JsonCreator
    public DistributedCardinalityInstance(
        @JsonProperty("size") final long size, @JsonProperty("extent") final long extent,
        @JsonProperty("method") CardinalityMethod method
    ) {
        super(size, extent, ALL_TYPES, MetricType.CARDINALITY);
        this.method = method;
    }

    @Override
    protected CardinalityBucket buildBucket(long timestamp) {
        return method.build(timestamp);
    }

    @Override
    protected Payload build(CardinalityBucket bucket) {
        return new Payload(bucket.timestamp(), bucket.state());
    }
}


text:
<?php

/**
 * DmMailTemplateTranslation form base class.
 *
 * @method DmMailTemplateTranslation getObject() Returns the current form's model object
 *
 * @package    retest
 * @subpackage form
 * @author     Your name here
 * @version    SVN: $Id: sfDoctrineFormGeneratedTemplate.php 24171 2009-11-19 16:37:50Z Kris.Wallsmith $
 */
abstract class BaseDmMailTemplateTranslationForm extends BaseFormDoctrine
{
  public function setup()
  {
    $this->setWidgets(array(
      'id'              => new sfWidgetFormInputHidden(),
      'description'     => new sfWidgetFormTextarea(),
      'subject'         => new sfWidgetFormTextarea(),
      'body'            => new sfWidgetFormTextarea(),
      'from_email'      => new sfWidgetFormTextarea(),
      'to_email'        => new sfWidgetFormTextarea(),
      'cc_email'        => new sfWidgetFormTextarea(),
      'bcc_email'       => new sfWidgetFormTextarea(),
      'reply_to_email'  => new sfWidgetFormTextarea(),
      'sender_email'    => new sfWidgetFormTextarea(),
      'list_unsuscribe' => new sfWidgetFormTextarea(),
      'is_html'         => new sfWidgetFormInputCheckbox(),
      'is_active'       => new sfWidgetFormInputCheckbox(),
      'lang'            => new sfWidgetFormInputHidden(),
    ));

    $this->setValidators(array(
      'id'              => new sfValidatorDoctrineChoice(array('model' => $this->getModelName(), 'column' => 'id', 'required' => false)),
      'description'     => new sfValidatorString(array('max_length' => 5000, 'required' => false)),
      'subject'         => new sfValidatorString(array('max_length' => 5000)),
      'body'            => new sfValidatorString(),
      'from_email'      => new sfValidatorString(array('max_length' => 5000)),
      'to_email'        => new sfValidatorString(array('max_length' => 5000, 'required' => false)),
      'cc_email'        => new sfValidatorString(array('max_length' => 5000, 'required' => false)),
      'bcc_email'       => new sfValidatorString(array('max_length' => 5000, 'required' => false)),
      'reply_to_email'  => new sfValidatorString(array('max_length' => 5000, 'required' => false)),
      'sender_email'    => new sfValidatorString(array('max_length' => 5000, 'required' => false)),
      'list_unsuscribe' => new sfValidatorString(array('max_length' => 5000, 'required' => false)),
      'is_html'         => new sfValidatorBoolean(array('required' => false)),
      'is_active'       => new sfValidatorBoolean(array('required' => false)),
      'lang'            => new sfValidatorDoctrineChoice(array('model' => $this->getModelName(), 'column' => 'lang', 'required' => false)),
    ));

    $this->widgetSchema->setNameFormat('dm_mail_template_translation[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    $this->setupInheritance();

    parent::setup();
  }

  public function getModelName()
  {
    return 'DmMailTemplateTranslation';
  }

}


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>PsycleContainer | psyborg</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					psyborg

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"psyborg/Psycle/PsycleContainer"

					psyborg

					PsycleContainer

Class PsycleContainer

スライドショーコンテナ要素

class

PsycleContainer

since

0.1.0

extends

PsyborgElement

constructor

Hierarchy

						PsyborgElement

								PsycleContainer

Index

Constructors

constructor

Properties

$el

el

Methods

get<wbr>Height

get<wbr>Max<wbr>Height

get<wbr>Min<wbr>Height

get<wbr>Width

off

on

set<wbr>Height

set<wbr>Width

trigger

Constructors

constructor

new <wbr>Psycle<wbr>Container($el: JQuery): PsycleContainer

Inherited from PsyborgElement.constructor

Overrides PsyborgEventDispacther.constructor

Defined in psyborg/PsyborgElement.ts:9

Parameters

$el: JQuery

Returns PsycleContainer

Properties

$el

$el: JQuery

Inherited from PsyborgElement.$el

Defined in psyborg/PsyborgElement.ts:25

内包するjQuery要素

since

0.1.0

el

el: Element

Inherited from PsyborgElement.el

Defined in psyborg/PsyborgElement.ts:32

内包するDOM要素

since

0.9.0

Methods

get<wbr>Height

get<wbr>Height(): number

Inherited from PsyborgElement.getHeight

Defined in psyborg/PsyborgElement.ts:68

要素の高さを取得

since

0.4.3

Returns number

要素の高さ

get<wbr>Max<wbr>Height

get<wbr>Max<wbr>Height(): number

Inherited from PsyborgElement.getMaxHeight

Defined in psyborg/PsyborgElement.ts:78

要素から最大の高さを取得

since

0.9.1

Returns number

要素の高さ

get<wbr>Min<wbr>Height

get<wbr>Min<wbr>Height(): number

Inherited from PsyborgElement.getMinHeight

Defined in psyborg/PsyborgElement.ts:92

要素から最小の高さを取得

since

0.9.1

Returns number

要素の高さ

get<wbr>Width

get<wbr>Width(): number

Inherited from PsyborgElement.getWidth

Defined in psyborg/PsyborgElement.ts:58

要素の幅を取得

since

0.4.3

Returns number

要素の幅

off

off(types: string, listener?: Function): void

Inherited from PsyborgEventDispacther.off

Defined in psyborg/PsyborgEventDispacther.ts:50

イベントを削除する

since

0.1.0

Parameters

types: string

イベントの種類(スペース区切りで複数可)

Optional listener: Function

リスナー関数

Returns void

on

on(types: string | string[], listener: function): void

Inherited from PsyborgEventDispacther.on

Defined in psyborg/PsyborgEventDispacther.ts:28

イベントを登録する

since

0.8.1

since

0.1.0

Parameters

types: string | string[]

イベントの種類(スペース区切りで複数可)

listener: function

リスナー関数

(e: PsyborgEvent): any

Parameters

e: PsyborgEvent

Returns any

Returns void

set<wbr>Height

set<wbr>Height(value: number): PsyborgElement

Inherited from PsyborgElement.setHeight

Defined in psyborg/PsyborgElement.ts:122

要素の高さを設定

since

0.4.3

Parameters

value: number

指定の値

Returns PsyborgElement

自身

set<wbr>Width

set<wbr>Width(value: number): PsyborgElement

Inherited from PsyborgElement.setWidth

Defined in psyborg/PsyborgElement.ts:110

要素の幅を設定

since

0.4.3

Parameters

value: number

指定の値

Returns PsyborgElement

自身

trigger

trigger(type: string, data?: any, context?: any): boolean

Inherited from PsyborgElement.trigger

Overrides PsyborgEventDispacther.trigger

Defined in psyborg/PsyborgElement.ts:44

イベントを任意に発火させる 要素にバインドされているイベントも同時に発火する

since

0.3.0

override

Parameters

type: string

イベントの種類

Default value data: any = {}

発火と同時にリスナー関数に渡すハッシュデータ

Default value context: any = this

リスナー関数のthisコンテクスト

Returns boolean

デフォルトのイベントの抑制がされていないかどうか

						Globals

						"psyborg/<wbr>Psycle/<wbr>Psycle<wbr>Container"

								psyborg

						Psycle<wbr>Container

								constructor

								$el

								el

								get<wbr>Height

								get<wbr>Max<wbr>Height

								get<wbr>Min<wbr>Height

								get<wbr>Width

								off

								on

								set<wbr>Height

								set<wbr>Width

								trigger

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
package models;

import com.avaje.ebean.validation.Email;
import org.codehaus.jackson.annotate.JsonIgnore;
import org.mindrot.jbcrypt.BCrypt;
import play.data.validation.Constraints;
import play.db.ebean.Model;

import javax.persistence.*;
import java.util.Set;

@Entity
@Table(name = "users")
public class User extends Model {

    @Id
    private Long id;

    @Constraints.Required
    @Column(unique = true, length = 120)
    @Email
    private String email;

    @Constraints.Required
    @JsonIgnore
    private String password;

    @Constraints.Required
    @OneToOne(cascade = {CascadeType.ALL})
    @JsonIgnore
    private AuthToken authToken;

    @OneToOne(cascade = {CascadeType.ALL})
    private Settings settings = new Settings();

    @ManyToMany(cascade = {CascadeType.ALL})
    private Set<Show> shows;

    public Long getId() {
        return id;
    }

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

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = BCrypt.hashpw(password, BCrypt.gensalt());
    }

    public Set<Show> getShows() {
        return shows;
    }

    public void setShows(Set<Show> shows) {
        this.shows = shows;
    }

    public AuthToken getAuthToken() {
        return authToken;
    }

    public void setAuthToken(AuthToken authToken) {
        this.authToken = authToken;
    }

    public Settings getSettings() {
        return settings;
    }

    public void setSettings(Settings settings) {
        this.settings = settings;
    }

    public static Finder<Long, User> find = new Finder<>(Long.class, User.class);

}


text:
<?php

declare(strict_types=1);

/*
 * This file is part of the RollerworksSearch package.
 *
 * (c) Sebastiaan Stok <s.stok@rollerscapes.net>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Rollerworks\Component\Search\Extension\Core\ValueComparator;

use Rollerworks\Component\Search\ValueComparator;

/**
 * @author Sebastiaan Stok <s.stok@rollerscapes.net>
 */
class DateValueComparator implements ValueComparator
{
    /**
     * @param \DateTimeImmutable $higher
     * @param \DateTimeImmutable $lower
     */
    public function isHigher($higher, $lower, array $options): bool
    {
        return $higher > $lower;
    }

    /**
     * @param \DateTimeImmutable $lower
     * @param \DateTimeImmutable $higher
     */
    public function isLower($lower, $higher, array $options): bool
    {
        return $lower < $higher;
    }

    /**
     * @param \DateTimeImmutable $value
     * @param \DateTimeImmutable $nextValue
     */
    public function isEqual($value, $nextValue, array $options): bool
    {
        return $value->getTimestamp() === $nextValue->getTimestamp();
    }
}


text:
'use strict';

module.exports = {
  path: __dirname
};


text:
A small utility to display two randomly selected pokemon. Then the intent is an artist can take the two and combine them into a fusion. Eventually I plan on displaying submitted artworks of the fusion.

## Inspiration
Initially a friend of mine just wanted ideas to draw, and she likes pokemon. I was probably inspired by the Pokemon Fusion site since I've seen that before as well (http://pokemon.alexonsager.net/). Otherwise just browsing tumblr and seeing posts about Steven Universe.

## Notes
This is still very new if you find this now, nothing here yet.


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.prestosql.sql.planner.iterative.rule;

import com.google.common.collect.ImmutableList;
import io.prestosql.matching.Capture;
import io.prestosql.matching.Captures;
import io.prestosql.matching.Pattern;
import io.prestosql.sql.planner.Symbol;
import io.prestosql.sql.planner.iterative.Rule;
import io.prestosql.sql.planner.optimizations.SymbolMapper;
import io.prestosql.sql.planner.plan.LimitNode;
import io.prestosql.sql.planner.plan.ProjectNode;
import io.prestosql.sql.tree.Expression;
import io.prestosql.sql.tree.SymbolReference;

import static io.prestosql.matching.Capture.newCapture;
import static io.prestosql.sql.planner.iterative.rule.Util.transpose;
import static io.prestosql.sql.planner.plan.Patterns.limit;
import static io.prestosql.sql.planner.plan.Patterns.project;
import static io.prestosql.sql.planner.plan.Patterns.source;

public class PushLimitThroughProject
        implements Rule<LimitNode>
{
    private static final Capture<ProjectNode> CHILD = newCapture();

    private static final Pattern<LimitNode> PATTERN = limit()
            .with(source().matching(
                    project()
                            // do not push limit through identity projection which could be there for column pruning purposes
                            .matching(projectNode -> !projectNode.isIdentity())
                            .capturedAs(CHILD)));

    @Override
    public Pattern<LimitNode> getPattern()
    {
        return PATTERN;
    }

    @Override
    public Result apply(LimitNode parent, Captures captures, Context context)
    {
        ProjectNode projectNode = captures.get(CHILD);

        // for a LimitNode without ties, simply reorder the nodes
        if (!parent.isWithTies()) {
            return Result.ofPlanNode(transpose(parent, projectNode));
        }

        // for a LimitNode with ties, the tiesResolvingScheme must be rewritten in terms of symbols before projection
        SymbolMapper.Builder symbolMapper = SymbolMapper.builder();
        for (Symbol symbol : parent.getTiesResolvingScheme().get().getOrderBy()) {
            Expression expression = projectNode.getAssignments().get(symbol);
            // if a symbol results from some computation, the translation fails
            if (!(expression instanceof SymbolReference)) {
                return Result.empty();
            }
            symbolMapper.put(symbol, Symbol.from(expression));
        }

        LimitNode mappedLimitNode = symbolMapper.build().map(parent, projectNode.getSource());
        return Result.ofPlanNode(projectNode.replaceChildren(ImmutableList.of(mappedLimitNode)));
    }
}


text:
class Model2 < ActiveRecord::Base

  def another_method
    puts "some bad copy paste here"
    puts "some bad copy paste here"
    puts "some bad copy paste here"
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JsUnit Test Container Controller</title>
    <script language="javascript" type="text/javascript">
        var containerReady = false;

        function init() {
            containerReady = true;
        }

        function isPageLoaded() {
            if (!containerReady)
                return false;

            var isTestPageLoaded = false;

            try {
                // attempt to access the var isTestPageLoaded in the testFrame
                if (typeof(top.testManager.testFrame.isTestPageLoaded) != 'undefined') {
                    isTestPageLoaded = top.testManager.testFrame.isTestPageLoaded;
                }

                // ok, if the above did not throw an exception, then the
                // variable is defined. If the onload has not fired in the
                // testFrame then isTestPageLoaded is still false. Otherwise
                // the testFrame has set it to true
            }
            catch (e) {
                // an error occured while attempting to access the isTestPageLoaded
                // in the testFrame, therefore the testFrame has not loaded yet
                isTestPageLoaded = false;
            }
            return isTestPageLoaded;
        }

        function isContainerReady() {
            return containerReady;
        }

        function setNotReady() {
            try {
                // attempt to set the isTestPageLoaded variable
                // in the test frame to false.
                top.testManager.testFrame.isTestPageLoaded = false;
            }
            catch (e) {
                // testFrame.isTestPageLoaded not available... ignore
            }
        }
        function setTestPage(testPageURI) {
            setNotReady();
            testPageURI = appendCacheBusterParameterTo(testPageURI);
            try {
                top.testManager.testFrame.location.href = testPageURI;
            } catch (e) {
            }
        }

        function appendCacheBusterParameterTo(testPageURI) {
            if (testPageURI.indexOf("?") == -1)
                testPageURI += "?";
            else
                testPageURI += "&";
            testPageURI += "cacheBuster=";
            testPageURI += new Date().getTime();
            return testPageURI;
        }
    </script>
</head>

<body onload="init()">
Test Container Controller
</body>
</html>