text:
public class A {
	public String x() { return "3"; }
}

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.content.browser.input;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;

/**
 * CursorController for inserting text at the cursor position.
 */
public abstract class InsertionHandleController implements CursorController {

    /** The handle view, lazily created when first shown */
    private HandleView mHandle;

    /** The view over which the insertion handle should be shown */
    private View mParent;

    /** True iff the insertion handle is currently showing */
    private boolean mIsShowing;

    /** True iff the insertion handle can be shown automatically when selection changes */
    private boolean mAllowAutomaticShowing;

    private Context mContext;

    public InsertionHandleController(View parent) {
        mParent = parent;
        mContext = parent.getContext();
    }

    /** Allows the handle to be shown automatically when cursor position changes */
    public void allowAutomaticShowing() {
        mAllowAutomaticShowing = true;
    }

    /** Disallows the handle from being shown automatically when cursor position changes */
    public void hideAndDisallowAutomaticShowing() {
        hide();
        mAllowAutomaticShowing = false;
    }

    /**
     * Shows the handle.
     */
    public void showHandle() {
        createHandleIfNeeded();
        showHandleIfNeeded();
    }

    void showPastePopup() {
        if (mIsShowing) {
            mHandle.showPastePopupWindow();
        }
    }

    public void showHandleWithPastePopup() {
        showHandle();
        showPastePopup();
    }

    /** Shows the handle at the given coordinates, as long as automatic showing is allowed */
    public void onCursorPositionChanged() {
        if (mAllowAutomaticShowing) {
            showHandle();
        }
    }

    /**
     * Moves the handle so that it points at the given coordinates.
     * @param x Handle x in physical pixels.
     * @param y Handle y in physical pixels.
     */
    public void setHandlePosition(float x, float y) {
        mHandle.positionAt((int) x, (int) y);
    }

    /**
     * If the handle is not visible, sets its visibility to View.VISIBLE and begins fading it in.
     */
    public void beginHandleFadeIn() {
        mHandle.beginFadeIn();
    }

    /**
     * Sets the handle to the given visibility.
     */
    public void setHandleVisibility(int visibility) {
        mHandle.setVisibility(visibility);
    }

    int getHandleX() {
        return mHandle.getAdjustedPositionX();
    }

    int getHandleY() {
        return mHandle.getAdjustedPositionY();
    }

    public HandleView getHandleViewForTest() {
        return mHandle;
    }

    @Override
    public void onTouchModeChanged(boolean isInTouchMode) {
        if (!isInTouchMode) {
            hide();
        }
    }

    @Override
    public void hide() {
        if (mIsShowing) {
            if (mHandle != null) mHandle.hide();
            mIsShowing = false;
        }
    }

    @Override
    public boolean isShowing() {
        return mIsShowing;
    }

    /**
     * @return Pixel width of insertion handle.
     */
    public int getHandleWidth() {
        return mHandle.getDrawable().getIntrinsicWidth();
    }

    /**
     * @return Pixel height of insertion handle.
     */
    public int getHandleHeight() {
        return mHandle.getDrawable().getIntrinsicHeight();
    }

    @Override
    public void beforeStartUpdatingPosition(HandleView handle) {}

    @Override
    public void updatePosition(HandleView handle, int x, int y) {
        setCursorPosition(x, y);
    }

    /**
     * The concrete implementation must cause the cursor position to move to the given
     * coordinates and (possibly asynchronously) set the insertion handle position
     * after the cursor position change is made via setHandlePosition.
     * @param x
     * @param y
     */
    protected abstract void setCursorPosition(int x, int y);

    /** Pastes the contents of clipboard at the current insertion point */
    protected abstract void paste();

    /** Returns the current line height in pixels */
    protected abstract int getLineHeight();

    @Override
    public void onDetached() {}

    boolean canPaste() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            return HoneyCombCompatLayer.canPaste(mContext);
        } else {
            return GenericCompatLayer.canPaste(mContext);
        }
    }

    private void createHandleIfNeeded() {
        if (mHandle == null) mHandle = new HandleView(this, HandleView.CENTER, mParent);
    }

    /**
     * Set window offset in pixels.
     *
     * @param padding The pixel offset for the parent view.
     */
    public void setWindowPadding(int padding) {
        if (mHandle != null) mHandle.setWindowPadding(padding);
    }

    private void showHandleIfNeeded() {
        if (!mIsShowing) {
            mIsShowing = true;
            mHandle.show();
            setHandleVisibility(HandleView.VISIBLE);
        }
    }

    /*
     * This class is based on TextView.PastePopupMenu.
     */
    class PastePopupMenu implements OnClickListener {
        private final PopupWindow mContainer;
        private int mPositionX;
        private int mPositionY;
        private View[] mPasteViews;
        private int[] mPasteViewLayouts;

        public PastePopupMenu() {
            mContainer = new PopupWindow(mContext, null,
                    android.R.attr.textSelectHandleWindowStyle);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                HoneyCombCompatLayer.setSplitTouchEnabled(mContainer, true);
            }
            mContainer.setClippingEnabled(false);

            mContainer.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
            mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

            final int[] POPUP_LAYOUT_ATTRS = {
                android.R.attr.textEditPasteWindowLayout,
                android.R.attr.textEditNoPasteWindowLayout,
                android.R.attr.textEditSidePasteWindowLayout,
                android.R.attr.textEditSideNoPasteWindowLayout,
            };

            mPasteViews = new View[POPUP_LAYOUT_ATTRS.length];
            mPasteViewLayouts = new int[POPUP_LAYOUT_ATTRS.length];

            TypedArray attrs = mContext.obtainStyledAttributes(POPUP_LAYOUT_ATTRS);
            for (int i = 0; i < attrs.length(); ++i) {
                mPasteViewLayouts[i] = attrs.getResourceId(attrs.getIndex(i), 0);
            }
            attrs.recycle();
        }

        private int viewIndex(boolean onTop) {
            return (onTop ? 0 : 1<<1) + (canPaste() ? 0 : 1 << 0);
        }

        private void updateContent(boolean onTop) {
            final int viewIndex = viewIndex(onTop);
            View view = mPasteViews[viewIndex];

            if (view == null) {
                final int layout = mPasteViewLayouts[viewIndex];
                LayoutInflater inflater = (LayoutInflater)mContext.
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                if (inflater != null) {
                    view = inflater.inflate(layout, null);
                }

                if (view == null) {
                    throw new IllegalArgumentException("Unable to inflate TextEdit paste window");
                }

                final int size = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
                view.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
                view.measure(size, size);

                view.setOnClickListener(this);

                mPasteViews[viewIndex] = view;
            }

            mContainer.setContentView(view);
        }

        void show() {
            updateContent(true);
            positionAtCursor();
        }

        void hide() {
            mContainer.dismiss();
        }

        boolean isShowing() {
            return mContainer.isShowing();
        }

        @Override
        public void onClick(View v) {
            if (canPaste()) {
                paste();
            }
            hide();
        }

        void positionAtCursor() {
            View contentView = mContainer.getContentView();
            int width = contentView.getMeasuredWidth();
            int height = contentView.getMeasuredHeight();

            int lineHeight = getLineHeight();

            mPositionX = (int) (mHandle.getAdjustedPositionX() - width / 2.0f);
            mPositionY = mHandle.getAdjustedPositionY() - height - lineHeight;

            final int[] coords = new int[2];
            mParent.getLocationInWindow(coords);
            coords[0] += mPositionX;
            coords[1] += mPositionY;

            final int screenWidth = mContext.getResources().getDisplayMetrics().widthPixels;
            if (coords[1] < 0) {
                updateContent(false);
                // Update dimensions from new view
                contentView = mContainer.getContentView();
                width = contentView.getMeasuredWidth();
                height = contentView.getMeasuredHeight();

                // Vertical clipping, move under edited line and to the side of insertion cursor
                // TODO bottom clipping in case there is no system bar
                coords[1] += height;
                coords[1] += lineHeight;

                // Move to right hand side of insertion cursor by default. TODO RTL text.
                final Drawable handle = mHandle.getDrawable();
                final int handleHalfWidth = handle.getIntrinsicWidth() / 2;

                if (mHandle.getAdjustedPositionX() + width < screenWidth) {
                    coords[0] += handleHalfWidth + width / 2;
                } else {
                    coords[0] -= handleHalfWidth + width / 2;
                }
            } else {
                // Horizontal clipping
                coords[0] = Math.max(0, coords[0]);
                coords[0] = Math.min(screenWidth - width, coords[0]);
            }

            mContainer.showAtLocation(mParent, Gravity.NO_GRAVITY, coords[0], coords[1]);
        }
    }

    private static class GenericCompatLayer {
        static boolean canPaste(Context context) {
            return false;
        }
    }

    private static class HoneyCombCompatLayer {
        static boolean canPaste(Context context) {
            return ((ClipboardManager)context.getSystemService(
                    Context.CLIPBOARD_SERVICE)).hasPrimaryClip();
        }
        static void setSplitTouchEnabled(PopupWindow win, boolean enabled) {
            win.setSplitTouchEnabled(enabled);
        }
    }
}


text:
package gov.nih.nci.nbia.beans.submissionreports;

/**
 * This object is basically a row in the patient details
 * table.  The decomposition of this object and PatientDetailGroupWrapper
 * may be somewhat dubious.  Just about all the code cares about
 * the "group" wrapper....
 */
public class PatientDetailWrapper  {

	public PatientDetailWrapper(String patient,
			                    String study,
			                    String series,
			                    String img) {
		super();
		this.patient = patient;
		this.study = study;
		this.series = series;
		this.img = img;
	}

	/**
	 * This is always a patient id
	 */
	public String getPatient() {
		return patient;
	}

	/**
	 * This is either a study id or a count of studies for the patient
	 */
	public String getStudy() {
		return study;
	}

	/**
	 * This is either a series id or a count of series for the patient
	 */
	public String getSeries() {
		return series;
	}

	/**
	 * This is a count of images or submissions (if annotation)
	 */
	public String getImg() {
		return img;
	}

	/////////////////////////////////PRIVATE////////////////////////////

	private String patient;
	private String study;
	private String series;
	private String img;

}


text:
from __future__ import print_function, division

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

from scipy.interpolate import UnivariateSpline as interpolate
from scipy.integrate import quad

from plotutils import setfig
from hashutils import hashcombine, hasharray

from .constraints import FunctionLowerLimit

class ContrastCurve(object):
    def __init__(self,rs,dmags,band,mag=None,name=None):
        """band is self-explanatory; 'mag' is mag of the primary in 'band' """
        #if band=='K' or band=="K'":
        #    band = 'Ks'

        rs = np.atleast_1d(rs)
        dmags = np.atleast_1d(dmags)
        self.rs = rs
        self.dmags = dmags
        self.band = band
        self.mag = mag
        self.contrastfn = interpolate(rs,dmags,s=0)
        self.rmax = rs.max()
        self.rmin = rs.min()
        if name is None:
            self.name = '%s band' % self.band
        else:
            self.name = name

    def plot(self,fig=None,**kwargs):
        setfig(fig)
        plt.plot(self.rs,self.dmags,**kwargs)
        plt.title('%s band contrast curve' % self.band)
        plt.gca().invert_yaxis()
        plt.xlabel('Separation [arcsec]')
        plt.ylabel('$\Delta %s$' % self.band)

    def __eq__(self,other):
        return hash(self)==hash(other)

    def __ne__(self,other):
        return not self.__eq__(other)

    def __hash__(self):
        return hashcombine(hasharray(self.rs),
                           hasharray(self.dmags),
                           self.band,
                           self.mag)
    def __call__(self,r):
        r = np.atleast_1d(r)
        dmags = np.atleast_1d(self.contrastfn(r))
        dmags[r >= self.rmax] = self.contrastfn(self.rmax)
        dmags[r < self.rmin] = 0
        #put something in here to "extend" beyond rmax?
        return dmags

    def __add__(self,other):
        if type(other) not in [type(1),type(1.),type(self)]:
            raise ValueError('Can only add a number or another ContrastCurve.')
        if type(other) in [type(1),type(1.)]:
            dmags = self.dmags + other
            return ContrastCurve(self.rs,dmags,self.band,self.mag)

    def __repr__(self):
        return '<%s: %s>' % (type(self),self.name)

    def power(self,floor=10,rmin=0.1,use_quad=False):
        if use_quad:
            return quad(self,rmin,self.rmax)[0]/((self.rmax-rmin)*floor)
        else:
            rs = np.linspace(rmin,self.rmax,100)
            return np.trapz(self(rs),rs)

class ContrastCurveConstraint(FunctionLowerLimit):
    def __init__(self,rs,dmags,cc,name='CC',**kwargs):
        self.rs = rs
        self.dmags = dmags
        self.cc = cc
        FunctionLowerLimit.__init__(self,rs,dmags,cc,name=name,**kwargs)

    def __str__(self):
        return '%s contrast curve' % self.name

    def update_rs(self,rs):
        self.rs = rs
        FunctionLowerLimit.__init__(self,rs,self.dmags,self.cc,name=self.name)
        logging.info('%s updated with new rsky values.' % self.name)

class ContrastCurveFromFile(ContrastCurve):
    def __init__(self,filename,band,mag=None):
        rs,dmags = np.loadtxt(filename,unpack=True)
        if rs[0] > 2:
            rs /= 1000.
        ContrastCurve.__init__(self,rs,dmags,band,mag)
        self.filename = filename

class VelocityContrastCurveConstraint(FunctionLowerLimit):
    def __init__(self,vels,dmags,vcc,name='VCC',**kwargs):
        self.vels = vels
        self.dmags = dmags
        self.vcc = vcc
        FunctionLowerLimit.__init__(self,vels,dmags,vcc,name=name,**kwargs)


text:
package org.rmatil.sync.test.base;

import org.rmatil.sync.core.messaging.StatusCode;

import java.util.UUID;

public class BaseMessageTest {

    protected static final UUID       EXCHANGE_ID = UUID.randomUUID();
    protected static final StatusCode STATUS_CODE = StatusCode.ACCEPTED;
}


text:
module AuthlogicRenrenConnect
  module ActsAsAuthentic
    def self.included(klass)
      klass.class_eval do
        extend Config
        add_acts_as_authentic_module(Methods, :prepend)
      end
    end

    module Config
    end

    module Methods
      def self.included(klass)
        klass.class_eval do
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/descriptionHeaderVerticalPadding"
    android:paddingBottom="@dimen/descriptionHeaderVerticalPadding"
    android:paddingLeft="@dimen/descriptionHeaderHorizontalPadding"
    android:paddingRight="@dimen/descriptionHeaderHorizontalPadding"
    android:gravity="center"/>


text:
// Trae todos los productos
exports.getRims = function(params,rim,errorCallback) {

 Ti.API.info("Get product");
var url = "http://msmotorsports.mx/ignoom/rines.php?id="+params;//?id="+params.id;

var xhr = Ti.Network.createHTTPClient({
    onload: function(e) {
    Ti.API.info("First: "+JSON.stringify(rim));
		//callback(this.responseText,rim);

		Ti.API.info(this.responseText);
		Ti.API.info(JSON.parse(this.responseText).imagen);

		Ti.API.info("Second: "+JSON.stringify(rim));
		var atts = JSON.parse(this.responseText);

		rim.nombre = atts.nombre;
		rim.id =  atts.id;
		rim.tipoRin = atts.tipo_rin;
		rim.imagen = atts.imagen;
		rim.modelo = atts.modelo;
		rim.dimension = atts.dimension;
		Ti.API.info("Third: "+JSON.stringify(rim));

		var logo = require('View/commonElements/rinLogo');
	 	Ti.API.info("Fifth: "+JSON.stringify(rim));
		rim.view = new logo((rim.id==1)?'Pickup':'Passenger', rim.imagen);

    },
    onerror: function(e) {
        Ti.API.debug(e.error);
        alert('No hay internet.');

        Ti.App.dispatcher.changeWindow(true,null,null);

    },
    timeout:10000  /* in milliseconds */
});
xhr.open("GET", url, true);
xhr.send();  // request is actually sent with this statement

};

exports.connect = function(url,callB) {

 Ti.API.info("Connecting to WS");

// var resp = null;
	function retrieveData(callback,callb) {

		var xhr = Ti.Network.createHTTPClient({
			onload : function() {

			//	Ti.API.info(this.responseText);
			//	Ti.API.info(JSON.parse(this.responseText).imagen);
				////data = this.responseText;
				callback(this.responseText,callb);

			},
			onerror : function(e) {
				//Ti.API.debug(e.error);
				alert('No hay internet.');
				//Ti.App.dispatcher.changeWindow(true,null,null);
			},
			timeout : 10000 /* in milliseconds */

		});

		xhr.open("GET", url,false);
		xhr.send();

	}

	retrieveData(function(returnVar,callb) {
		//If we get a null or undefined response, we'll just take an empty array
		var resp = JSON.parse(returnVar) || [];
		Ti.API.info("respuesta: "+resp);
		//Check there are some links
		//Ti.API.info(self.data);
		//Ti.API.info("Fifth: " + JSON.stringify(self.data));
		//var logo = require('View/commonElements/rinLogo');
		//self.view = new logo((self.data.id == 1) ? 'Pickup' : 'Passenger', self.data.imagen);
		if(callb){
			callb(resp);
		}

	}, callB);

	//return resp;

};


text:
package com.wjiec.tinder.springinaction.conditional.magic;

import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.MultiValueMap;

public class MagicCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        if (context.getEnvironment() != null) {
            MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(HasEnvironment.class.getName());
            if (attrs != null) {
                for (Object attr : attrs.get("value")) {
                    for (String env : (String[]) attr) {
                        if (context.getEnvironment().containsProperty(env)) {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }

}


text:
"""
A module for convolutions with cudnn.
"""

__author__ = "Nicolas Ballas"
__license__ = "3-clause BSD"
__credits__ = "Nicolas Ballas and Francesco Visin"
__maintainer__ = "Lisa Lab"

import functools
import numpy as np

from theano.sandbox.cuda.dnn import GpuDnnConv, GpuDnnConvDesc
from theano.sandbox.cuda.basic_ops import gpu_contiguous, gpu_alloc_empty

from pylearn2.packaged_dependencies.theano_linear.conv2d \
    import Conv2d as OrigConv2D

from pylearn2.linear.linear_transform import LinearTransform as P2LT
from pylearn2.utils import sharedX
from pylearn2.utils.rng import make_np_rng

default_seed = [2012, 11, 6, 9]
default_sparse_seed = [2012, 11, 6]

class Cudnn2D(OrigConv2D):
    """
    Wrapper on the Theano Cudnn op.

    Parameters
    ----------
    filters : Theano shared variable
        4D-tensor of shape (out channels, in channels, rows, cols)
    batch_size : int
        The size of the input batches
    input_space : Space
        The Space of the input data
    output_axes : tuple, optional
        The requested output axes. If not specified `bc01` will be used.
    subsample : tuple or list, optional
        Factor by which to subsample the output. Default (1, 1)
    border_mode : string, optional
        `valid` or `full`. See scipy.signal.convolve2d
    filters_shape : tuple of length 2 or 3, optional
        ([filter's number,] filter's height, filter's width)
    message : string, optional
        TODO
    """

    def __init__(self,
                 filters,
                 batch_size,
                 input_space,
                 output_axes=('b', 'c', 0, 1),
                 subsample=(1, 1),
                 border_mode='valid',
                 filters_shape=None,
                 message=''):

        assert batch_size is None or batch_size > 0
        self._input_space = input_space
        self._output_axes = output_axes
        self._subsample = tuple(subsample)
        self._border_mode = border_mode

        super(Cudnn2D, self).__init__(
            filters=filters,
            img_shape=(batch_size, input_space.num_channels,
                       input_space.shape[0], input_space.shape[1]),
            subsample=self._subsample,
            border_mode=border_mode,
            filters_shape=filters.get_value(borrow=True).shape,
            message=message
        )

        # conv_op has to be changed
        self._conv_op = GpuDnnConv()
        self._desc = GpuDnnConvDesc(border_mode=border_mode,
                                    subsample=self._subsample,
                                    conv_mode='conv')

    @functools.wraps(P2LT.get_params)
    def get_params(self):
        """ Return self._filters. """
        return [self._filters]

    @functools.wraps(P2LT.get_weights_topo)
    def get_weights_topo(self, borrow):
        """
        Parameters
        ----------
        borrow : TODO
            TODO
        """
        return np.transpose(self._filters.get_value(borrow=borrow),
                            (0, 2, 3, 1))

    def lmul(self, x):
        """
        .. todo::

            WRITEME properly

        dot(x, A)

        This method overrides the original Conv2D lmul to make it work
        with arbitrary axis orders

        Parameters
        ----------
        x : TODO
            TODO
        """
        # x must be formatted as batch index, channel, topo dim 0, topo dim 1
        # for use with conv2d, so check what the current input space format is
        assert x.ndim == 4
        axes = self._input_space.axes
        assert len(axes) == 4

        op_axes = ('b', 'c', 0, 1)

        if tuple(axes) != op_axes:
            x = x.dimshuffle(*[axes.index(ax) for ax in op_axes])

        # The calling format has to be changed
        img = gpu_contiguous(x)
        kerns = gpu_contiguous(self._filters)
        shape = GpuDnnConv.get_out_shape(
            img.shape, kerns.shape, self._border_mode, self._subsample)
        rval = gpu_alloc_empty(*shape)
        desc = self._desc(img.shape, kerns.shape)
        rval = self._conv_op(img, kerns, rval, desc)

        # Format the output based on the output space
        axes = self._output_axes
        assert len(axes) == 4

        if tuple(self._output_axes) != op_axes:
            rval = rval.dimshuffle(*[op_axes.index(ax) for ax in
                                     self._output_axes])

        return rval

    def set_batch_size(self, batch_size):
        """
        .. todo::

            WRITEME

        Parameters
        ----------
        batch_size : TODO
            TODO
        """
        self._img_shape = tuple([batch_size] + list(self._img_shape[1:]))

def make_random_conv2D(irange,
                       input_space,
                       output_space,
                       kernel_shape,
                       batch_size=None,
                       subsample=(1, 1),
                       border_mode = 'valid',
                       message = "",
                       rng = None):
    """
    .. todo::

        WRITEME properly

    Creates a CorrMM2D with random kernels

    Parameters
    ----------
    irange : TODO
    input_space : TODO
    output_space : TODO
    kernel_shape : 2D list or tuple
    batch_size : int, optional
    subsample : tuple, optional
    border_mode : string, optional
    message : string, optional
    rng : optional
    """

    rng = make_np_rng(rng, default_seed, which_method='uniform')

    W = sharedX(rng.uniform(-irange, irange, (output_space.num_channels,
                                              input_space.num_channels,
                                              kernel_shape[0],
                                              kernel_shape[1])))

    return Cudnn2D(
        filters=W,
        batch_size=batch_size,
        input_space=input_space,
        output_axes=output_space.axes,
        subsample=tuple(subsample),
        border_mode=border_mode,
        filters_shape=W.get_value(borrow=True).shape,
        message=message
    )

def make_sparse_random_conv2D(num_nonzero,
                              input_space,
                              output_space,
                              kernel_shape,
                              batch_size,
                              subsample=(1, 1),
                              border_mode='valid',
                              message="",
                              rng=None):

    """
    .. todo::

        WRITEME properly

    Creates a Cudnn2D with random kernels, where the randomly initialized
    values are sparse

    Parameters
    ----------
    num_nonzero : TODO
    input_space : TODO
    output_space : TODO
    kernel_shape : TODO
    batch_size : TODO
    subsample : TODO, optional
    border_mode : TODO, optional
    message : TODO, optional
    rng : TODO, optional

    """

    raise AssertionError(
        "TODO: I think this is a bug--num_nonzero "
        "determines the total number of nonzero elements in the "
        "whole kernel stack, not the number of non-zero elements per "
        "kernel. Investigate what it's meant to do."
    )

    rng = make_np_rng(rng, default_sparse_seed,
                      which_method=['randn', 'randint'])

    W = np.zeros((output_space.num_channels, input_space.num_channels,
                  kernel_shape[0], kernel_shape[1]))

    def random_coord():
        return [rng.randint(dim) for dim in W.shape]

    for i in range(num_nonzero):
        o, ch, r, c = random_coord()
        while W[o, ch, r, c] != 0:
            o, ch, r, c = random_coord()
        W[o, ch, r, c] = rng.randn()

    W = sharedX(W)

    return Cudnn2D(
        filters=W,
        batch_size=batch_size,
        input_space=input_space,
        output_axes=output_space.axes,
        subsample=subsample,
        border_mode=border_mode,
        filters_shape=W.get_value(borrow=True).shape,
        message=message
    )


text:
package com.hp.hpl.jena.rdf.model.test;

import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.util.CollectionFactory;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.graph.test.*;

import java.util.*;

/**
 	@author kers
*/
public abstract class AbstractTestReifiedStatements extends ModelTestBase
    {
    public AbstractTestReifiedStatements( String name )
        {
        super( name );
        }

    public abstract Model getModel();

    private Model model;
    private Resource S;
    private Property P;
    private RDFNode O;
    private Statement SPO;
    private Statement SPO2;

    private static final String aURI = "jena:test/reifying#someURI";
    private static final String anotherURI = "jena:test/reifying#anotherURI";
    private static final String anchor = "jena:test/Reifying#";

    @Override
    public void setUp()
        {
        model = getModel();
        Resource S2 = model.createResource( anchor + "subject2" );
        S = model.createResource( anchor + "subject" );
        P = model.createProperty( anchor + "predicate" );
        O = model.createLiteral( anchor + "object" );
        SPO = model.createStatement( S, P, O );
        SPO2 = model.createStatement( S2, P, O );
        }

    /**
        the simplest case: if we assert all the components of a reification quad,
        we can get a ReifiedStatement that represents the reified statement.
    */
    public void testBasicReification()
        {
        if (model.getReificationStyle() != ModelFactory.Minimal)
            { Resource R = model.createResource( aURI );
            model.add( R, RDF.type, RDF.Statement );
            model.add( R, RDF.subject, S );
            model.add( R, RDF.predicate, P );
            model.add( R, RDF.object, O );
            RDFNode rs = R.as( ReifiedStatement.class );
            assertEquals( "can recover statement", SPO, ((ReifiedStatement) rs).getStatement() ); }
        }

    /**
        check that, from a model with any combination of the statements given,
        we can convert R into a ReifiedStatement iff the four components of the
        quad are in the model.
    */
    public void testReificationCombinations()
        {
        Resource RR = model.createResource( aURI ), SS = model.createResource( anotherURI );
        Property PP = RR.as( Property.class );
        Object [][] statements =
            {
                { model.createStatement( RR, RDF.type, RDF.Statement ), new Integer(1) },
                { model.createStatement( RR, RDF.subject, SS ), new Integer(2) },
                { model.createStatement( RR, RDF.predicate, PP ), new Integer(4) },
                { model.createStatement( RR, RDF.object, O ), new Integer(8) },
                { model.createStatement( SS, PP, O ), new Integer(16) },
                { model.createStatement( RR, PP, O ), new Integer(32) },
                { model.createStatement( SS, RDF.subject, SS ), new Integer(64) },
                { model.createStatement( SS, RDF.predicate, PP ), new Integer(128) },
                { model.createStatement( SS, RDF.object, O ), new Integer(256) },
                { model.createStatement( SS, RDF.type, RDF.Statement ), new Integer(512) }
            };
        if (model.getReificationStyle() != ModelFactory.Minimal)
            testCombinations( model, RR, 0, statements, statements.length );
        }

    /**
        walk down the set of statements (represented as an array), recursing with and
        without each statement being present. The mask bits record those statements
        that are in the model. At the bottom of the recursion (n == 0), check that R
        can be reified exactly when all four quad components are present; the other
        statements don't matter.
    */
    private void testCombinations( Model m, Resource R, int mask, Object [][] statements, int n )
        {
        if (n == 0)
            {
            try
                {
                // System.err.println( "| hello. mask = " + mask );
                ReifiedStatement rs = R.as( ReifiedStatement.class );
                // System.err.println( "+  we constructed " + rs );
                assertTrue( "should not reify: not all components present [" + mask + "]: " + rs, (mask & 15) == 15 );
                // System.err.println( "+  and we passed the assertion." );
                }
            catch (DoesNotReifyException e)
                { // System.err.println( "+  we exploded" );
                    assertFalse( "should reify: all components present", mask == 15 ); }
            }
        else
            {
            int i = n - 1;
            Statement s = (Statement) statements[i][0];
            int bits = ((Integer) statements[i][1]).intValue();
            testCombinations( m, R, mask, statements, i );
            m.add( s );
            testCombinations( m, R, mask + bits, statements, i );
            m.remove( s );
            }
        }

    public void testThisWillBreak()
        {
        Resource R = model.createResource( aURI );
        SPO.createReifiedStatement( aURI );
        model.add(  R, RDF.subject, R );
        }

    /**
        "dirty" reifications - those with conflicting quadlets - should fail.
    */
    public void testDirtyReification()
        {
        Resource R = model.createResource( aURI );
        model.add( R, RDF.type, RDF.Statement );
        model.add( R, RDF.subject, S );
        model.add( R, RDF.subject, P );
        testDoesNotReify( "boo", R );
        }

    public void testDoesNotReify( String title, Resource r )
        {
        try { r.as( ReifiedStatement.class ); fail( title + " (" + r + ")" ); }
        catch (DoesNotReifyException e) { /* that's what we expect */ }
        }

    public void testConversion()
        {
        final String uri = "spoo:handle";
        model.createReifiedStatement( uri, SPO );
        ReifiedStatement rs2 = model.createResource( uri ).as( ReifiedStatement.class );
        assertEquals( "recover statement", SPO, rs2.getStatement() );
        }

    public void testDoesNotReifyUnknown()
        {
        testDoesNotReify( "model should not reify rubbish", model.createResource( "spoo:rubbish" ) );
        }

    public void testQuintetOfQuadlets()
        {
        Resource rs = model.createResource();
        rs.addProperty( RDF.type, RDF.Statement );
        model.createResource().addProperty( RDF.value, rs );
        rs.addProperty( RDF.subject, model.createResource() );
        rs.addProperty( RDF.predicate, model.createProperty( "http://example.org/foo" ) );
        rs.addProperty( RDF.object, model.createResource() );
        rs.addProperty( RDF.object, model.createResource() );
        StmtIterator it = model.listStatements();
        while (it.hasNext())
            {
            Statement s = it.nextStatement();
            assertFalse(s.getObject().equals(s.getSubject()));
            }
        }

    public void testConstructionByURI()
        {
        ReifiedStatement rs = model.createReifiedStatement( "spoo:handle", SPO );
        ReifiedStatement rs2 = SPO.createReifiedStatement( "spoo:gripper");
        assertEquals( "recover statement (URI)", SPO, rs.getStatement() );
        assertEquals( "recover URI", "spoo:handle", rs.getURI() );
        assertEquals( "recover URI", "spoo:gripper", rs2.getURI() );
        }

    public void testStatementAndModel( String title, ReifiedStatement rs, Model m, Statement st )
        {
        assertEquals( title + ": recover statement", st, rs.getStatement() );
        assertEquals( title + ": recover model", m, rs.getModel() );
        }

    public void testConstructionFromStatements()
        {
        testStatementAndModel( "fromStatement", SPO.createReifiedStatement(), model, SPO );
        }

    public void testConstructionFromModels()
        {
        testStatementAndModel( "fromModel", model.createReifiedStatement( SPO ) , model, SPO );
        }

    /**
        utility method: get a set of all the elements delivered by
        _m.listReifiedStatements_.
    */
    public Set<ReifiedStatement> getSetRS( Model m )
        { return m.listReifiedStatements().toSet(); }

    protected static Set<ReifiedStatement> noStatements = CollectionFactory.createHashedSet();

    /**
        test that listReifiedStatements produces an iterator that contains
        the right reified statements. We *don't* test that they're not
        duplicated, because they might be; disallowing duplicates
        could be expensive.
    */
    public void testListReifiedStatements()
        {
        assertEquals( "initially: no reified statements", noStatements, getSetRS( model ) );
        ReifiedStatement rs = model.createReifiedStatement( aURI, SPO );
        // assertEquals( "still: no reified statements", empty, getSetRS( m ) );
    /* */
        model.add( rs, P, O );
        Set<ReifiedStatement> justRS = arrayToSet( new ReifiedStatement [] {rs} );
        assertEquals( "post-add: one reified statement", justRS, getSetRS( model ) );
        model.add( S, P, rs );
        assertEquals( "post-add: still one reified statement", justRS, getSetRS( model ) );
    /* */
        ReifiedStatement rs2 = model.createReifiedStatement( anotherURI, SPO2 );
        Set<ReifiedStatement> bothRS = arrayToSet( new ReifiedStatement[] {rs, rs2} );
        model.add( rs2, P, O );
        assertEquals( "post-add: still one reified statement", bothRS, getSetRS( model ) );
        }

    /**
        this test appeared when TestStatementResources crashed using reified
        statements as a step-0 implementation for asSubject()/asObject(). Looks
        like there was a problem in modelReifier().getRS(), which we're fixing ...
    */
    public void testListDoesntCrash()
        {
        model.createReifiedStatement( SPO );
        model.createReifiedStatement( SPO2 );
        assertTrue( "should be non-empty", model.listReifiedStatements().hasNext() );
        }

    public Set<ReifiedStatement> getSetRS( Model m, Statement st )
        { return m.listReifiedStatements( st ).toSet(); }

    public void testListReifiedSpecificStatements()
        {
        assertEquals( "no statements should match st", noStatements, getSetRS( model, SPO ) );
    /* */
        ReifiedStatement rs = model.createReifiedStatement( aURI, SPO );
        ReifiedStatement rs2 = model.createReifiedStatement( anotherURI, SPO2 );
        model.add( rs, P, O );
        // assertEquals( "still no matching statement", empty, getSetRS( m, stOther ) );
    /* */
        Set<ReifiedStatement> justRS2 = arrayToSet( new ReifiedStatement [] {rs2} );
        model.add( rs2, P, O );
        assertEquals( "now one matching statement", justRS2, getSetRS( model, SPO2 ) );
        }

    public void testStatementListReifiedStatements()
        {
        Statement st = SPO;
        Model m = model;
        assertEquals( "it's not there yet", noStatements, GraphTestBase.iteratorToSet( st.listReifiedStatements() ) );
        ReifiedStatement rs = m.createReifiedStatement( aURI, st );
        Set<ReifiedStatement> justRS = arrayToSet( new ReifiedStatement [] {rs} );
        m.add( rs, P, O );
        assertEquals( "it's here now", justRS, GraphTestBase.iteratorToSet( st.listReifiedStatements() ) );
        }

    public void testIsReified()
        {
        ReifiedStatement rs = model.createReifiedStatement( aURI, SPO );
        Resource BS = model.createResource( anchor + "BS" );
        Property BP = model.createProperty( anchor + "BP" );
        RDFNode BO = model.createProperty( anchor + "BO" );
        model.add( rs, P, O );
        assertTrue( "st should be reified now", SPO.isReified() );
        assertTrue( "m should have st reified now", model.isReified( SPO ) );
        assertFalse( "this new statement should not be reified", model.createStatement( BS, BP, BO ).isReified() );
        }

    public void testGetAny()
        {
        Resource r = model.getAnyReifiedStatement( SPO );
        assertInstanceOf( ReifiedStatement.class, r );
        assertEquals( "should get me the statement", SPO, ((ReifiedStatement) r).getStatement() );
        }

    public void testRemoveReificationWorks()
        {
        Statement st = SPO;
        Model m = model;
        m.createReifiedStatement( aURI, st );
        assertTrue( "st is now reified", st.isReified() );
        m.removeAllReifications( st );
        assertFalse( "st is no longer reified", st.isReified() );
        }

    /**
        Leo Bard spotted a problem whereby removing a reified statement from a model
        with style Standard didn't leave the model empty. Here's a test for it.
    */
    public void testLeosBug()
        {
        Model A = getModel();
        Statement st = statement( A,  "pigs fly south" );
        ReifiedStatement rst = st.createReifiedStatement( "eh:pointer" );
        A.removeReification( rst );
        assertIsoModels( ModelFactory.createDefaultModel(), A );
        }

    public void testRR()
        {
        Statement st = SPO;
        Model m = model;
        ReifiedStatement rs1 = m.createReifiedStatement( aURI, st );
        ReifiedStatement rs2 = m.createReifiedStatement( anotherURI, st );
        m.removeReification( rs1 );
        testNotReifying( m, aURI );
        assertTrue( "st is still reified", st.isReified() );
        m.removeReification( rs2 );
        assertFalse( "st should no longer be reified", st.isReified() );
        }

    private void testNotReifying( Model m, String uri )
        {
        try
            {
            m.createResource( uri ).as( ReifiedStatement.class );
            fail( "there should be no reifiedStatement for " + uri );
            }
        catch (DoesNotReifyException e)
            { /* that's what we require */ }
        }

    public void testDoesNotReifyElsewhere()
        {
        final String uri = "spoo:rubbish";
        Model m2 = getModel();
        model.createReifiedStatement( uri, SPO );
        testDoesNotReify( "blue model should not reify rubbish", m2.createResource( uri ) );
        }
//    public void testXXX()
//        {
//        String root = "http://root/root#";
//        Model m = ModelFactory.createDefaultModel();
//        Model r = ModelFactory.createRDFSModel( m );
//        Resource S = r.createResource( root + "S" );
//        Property P = r.createProperty( root + "P" );
//        RDFNode O = r.createResource( root + "O" );
//        Statement st = r.createStatement( S, P, O );
//        ReifiedStatement rs = st.createReifiedStatement( root + "RS" );
//        }
    }


text:
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import Button from 'react-native-button';
import { connect } from 'react-redux';
import SliderWithLabel from './sliderWithLabel';
import ClickableLabel from './sectionClickableLabel';

import {makeServerCall, generateRequestBody} from '../shared/utils';
import {togglePlayer, togglePlay, setVolume, updatePlayerState} from '../state/actions/player';
import {showNotification, changeConnectionStatus} from '../state/actions/appState';

const mapStateToProps = (state) => ({
	player: state.player,
});

const mapDispatchToProps = (dispatch) => ({
	togglePlayer: () => {
		dispatch(togglePlayer());
	},
	togglePlay: () => {
		dispatch(togglePlay());
	},
	setVolume: (volume) => {
		dispatch(setVolume(volume));
	},
	updatePlayerState: (newState) => {
		dispatch(updatePlayerState(newState));
	},
	showNetworkStatus: (message) => {
		dispatch(changeConnectionStatus(message));
	},
	showNotification: (message) => {
		dispatch(showNotification(message));
	}
});

class Player extends Component {
	sendToServer(requestBody){
		this.props.showNetworkStatus('Fetching...');
		makeServerCall('player', requestBody)
		.then((data) => { this.props.updatePlayerState(data); 	this.props.showNetworkStatus('Fetched player data.'); })
		.catch((err) => { this.props.showNotification('Oops, it didn\'t work.'); 	this.props.showNetworkStatus('Fetching failed.'); });
	}

	changeSong(direction) {
		this.sendToServer(generateRequestBody('changeSong', [direction]));
	}

	playToggle() {
		const {player} = this.props;
		const nextState = !player.isPlaying;

		this.props.togglePlay();
		this.sendToServer(generateRequestBody('playToggle', nextState ? [player.volume] : [0]));
	}

	playerToggle() {
		const {player} = this.props;
		const nextState = !player.isOn;

		this.props.togglePlayer();
		this.sendToServer(generateRequestBody('playerToggle', nextState ? ['ton'] : ['toff']));
	}

	volumeChanged(vol) {
		this.props.setVolume(vol);
		this.sendToServer(generateRequestBody('volumeChanged', [vol]));
	}

	render() {
		const {player} = this.props;

		const playIcon = player.isPlaying ? 'md-pause' : 'md-play';
		const labelColor = player.isOn ? 'green' : 'red';

		return (
			<View {...this.props} >
        <ClickableLabel containerStyle={{flex: 3, justifyContent: 'center'}} iconName= 'md-musical-notes'
          iconSize= {32} color = {labelColor} backgroundColor = '#FFFCDD' onPress = {() => this.playerToggle()}>
          Player
        </ClickableLabel>
        <View style={{flex: 5, flexDirection: 'row', alignItems: 'center'}}>
          <Button containerStyle ={styles.changeSongButton} disabled = {!player.isOn} onPress= { () => this.changeSong('prev')}>
            <Icon name='md-skip-backward' color = 'black' size={textSizes.iconSize}></Icon>
          </Button>
          <Button containerStyle ={styles.playButton} disabled = {!player.isOn} onPress= {() => this.playToggle()}>
            <Icon name={playIcon} color = 'black' size={textSizes.iconSize}></Icon>
          </Button>
          <Button containerStyle = {styles.changeSongButton} disabled = {!player.isOn} onPress= {() => this.changeSong('next')}>
            <Icon name='md-skip-forward' color = 'black' size={textSizes.iconSize}></Icon>
          </Button>
        </View>
        <View style={{flex: 4, alignItems: 'center'}}>
          <SliderWithLabel minimumValue={1} maximumValue={9} step={1} disabled = {!player.isOn} value = {player.volume} onSlidingComplete={(val) => this.volumeChanged(val)}></SliderWithLabel>
        </View>
      </View>
		);
	}
}

const styles = StyleSheet.create({
	changeSongButton: {
		padding: 4,
		margin: 5,
		overflow: 'hidden',
		borderRadius: 3,
		backgroundColor: '#FFFCDD'
	},
	playButton: {
		padding: 6,
		margin: 5,
		marginLeft: 10,
		marginRight: 10,
		overflow: 'hidden',
		borderRadius: 3,
		backgroundColor: '#FFFCDD'
	},
});

const textSizes = {
	iconSize: 36,
};

export default connect(mapStateToProps, mapDispatchToProps)(Player);


text:
```html
${'<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>'}
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Login</title>
    <link rel="stylesheet" type="text/css" href="/css/bootstrap.css"/>
    <link rel="stylesheet" type="text/css" href="/css/jquery.growl.css"/>
    <script src="http://code.jquery.com/jquery.js"></script>
    <script src="${lock_url}"></script>
    <script src="/js/jquery.growl.js" type="text/javascript"></script>
</head>
<body>
  <div class="container">
    <script type="text/javascript">
      $(function () {
        var error = <%= "${error}" %>;
        if (error) {
          $.growl.error({message: "An error was detected. Please log in"});
        } else {
          $.growl({title: "Welcome!", message: "Please log in"});
        }
      });

      $(function () {
            var lock = new Auth0Lock('${account.clientId}', '${account.namespace}', {
                auth: {
                    redirectUrl: '<%= "${fn:replace(pageContext.request.requestURL, pageContext.request.requestURI, '')}" %><%= "${loginCallback}" %>',
                    responseType: 'code',
                    params: {
                        state: '<%= "${state}" %>',
                        scope: 'openid user_id name nickname email picture'
                    }
                }
            });
            setTimeout(function () {
                lock.show();
            }, 1500);
        });
    </script>
  </div>
</body>
</html>
```


text:
<?php

namespace api\components;

use Yii;
use yii\base\Model;
use yii\helpers\Url;
use yii\web\ServerErrorHttpException;
use yii\rest\Action;

/**
 * CreateAction implements the API endpoint for creating a new model from the given data.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class CreateActionNR extends Action
{
    /**
     * @var string the scenario to be assigned to the new model before it is validated and saved.
     */
    public $scenario = Model::SCENARIO_DEFAULT;
    /**
     * @var string the name of the view action. This property is need to create the URL when the model is successfully created.
     */
    public $viewAction = 'view';
    /**
     * Creates a new model.
     * @return \yii\db\ActiveRecordInterface the model newly created
     * @throws ServerErrorHttpException if there is any error when creating the model
     */
    public function run()
    {
        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id);
        }
        /* @var $model \yii\db\ActiveRecord */
        $model = new $this->modelClass([
            'scenario' => $this->scenario,
        ]);
        $model->load(Yii::$app->getRequest()->getBodyParams(), '');
        if ($model->save()) {
            $response = Yii::$app->getResponse();
            $response->setStatusCode(201);
        } elseif (!$model->hasErrors()) {
            throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
        }
        return $model;
    }
}


text:
   dontUseRefs

      void dontUseRefs()
      void dontUseRefs(

)

      Source

   Description

By default, a [occa::device](/api/device/) will automatically call [free](/api/device/free) through reference counting.
Turn off automatic garbage collection through this method.


text:
// **********************************************************************
//
// <copyright>
//
//  BBN Technologies
//  10 Moulton Street
//  Cambridge, MA 02138
//  (617) 873-8000
//
//  Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/gui/dock/DockPanel.java,v $
// $RCSfile: DockPanel.java,v $
// $Revision: 1.5 $
// $Date: 2004/10/14 18:05:49 $
// $Author: dietrick $
//
// **********************************************************************

package com.bbn.openmap.gui.dock;

import java.awt.BorderLayout;

import javax.swing.JComponent;

/**
 * An interface onto a component that has a background component and
 * docking children.
 *
 * @author Ben Lubin
 * @version $Revision: 1.5 $ on $Date: 2004/10/14 18:05:49 $
 * @since 12/5/02
 */
public interface DockPanel {

    /** Constraint for the background component */
    public static final String BACKGROUND = BorderLayout.CENTER;

    //Background Methods:
    /////////////////////

    /**
     * Get the background component.
     */
    public JComponent getBackgroundComponent();

    /**
     * Set the background component.
     */
    public void setBackgroundComponent(JComponent back);

    //Constraint Methods:
    /////////////////////

    /**
     * Set the constraint on the given child.
     */
    public void setConstraint(JComponent child, DockConstraint c);

    /**
     * Get the constraint on the given child.
     */
    public DockConstraint getConstraint(JComponent child);

    /**
     * Remove a constraint on a child.
     */
    public void removeConstraint(JComponent child);

    //Constraint Setup Functions:
    /////////////////////////////

    /**
     * Set the childs preferred height.
     */
    public void setPreferredHeight(JComponent child, int i);

    /**
     * Set the childs preferred width.
     */
    public void setPreferredWidth(JComponent child, int i);

    /**
     * Set that the given child can sit in front of the background
     * component, without forcing the background component to be
     * resized to make room.
     */
    public void setCanOcclude(JComponent child, boolean b);

    /**
     * Set the child component to have a transparent background.
     */
    public void setCanTransparent(JComponent child, boolean b);

    /**
     * Set that the child component can be user-resized.
     */
    public void setCanResize(JComponent child, boolean b);

    /**
     * Set that the child component can be tabbed up, if docked in the
     * same location as other tab-able components.
     */
    public void setCanTab(JComponent child, boolean b);

    /**
     * Set the name of the tab to use when the component is tabbed (if
     * it can tab). If unspecified, defaults to Component.getName()
     */
    public void setTabName(JComponent child, String tabName);

    /**
     * Set that the child can be become an external frame.
     */
    public void setCanExternalFrame(JComponent child, boolean b);

    /**
     * Set that the child can be become an internal frame.
     */
    public void setCanInternalFrame(JComponent child, boolean b);

    /**
     * Set that the child can be closed.
     */
    public void setCanClose(JComponent child, boolean b);

    /**
     * Set that the child can dock on the top-level north.
     */
    public void setCanDockNorth(JComponent child, boolean b);

    /**
     * Set that the child can dock on the top-level south.
     */
    public void setCanDockSouth(JComponent child, boolean b);

    /**
     * Set that the child can dock on the top-level east.
     */
    public void setCanDockEast(JComponent child, boolean b);

    /**
     * Set that the child can dock on the top-level west.
     */
    public void setCanDockWest(JComponent child, boolean b);

    //Docking Functions:
    ////////////////////

    //NORTH:

    /**
     * Dock child on the DockPanel.
     */
    public void dockNorth(JComponent child);

    /**
     * Dock the given child into the given position on the DockPanel
     */
    public void dockNorth(JComponent child, int idx);

    //SOUTH:

    /**
     * Dock child on the DockPanel.
     */
    public void dockSouth(JComponent child);

    /**
     * Dock the given child into the given position on the DockPanel
     */
    public void dockSouth(JComponent child, int idx);

    //EAST:

    /**
     * Dock child on the DockPanel.
     */
    public void dockEast(JComponent child);

    /**
     * Dock the given child into the given position on the DockPanel
     */
    public void dockEast(JComponent child, int idx);

    //WEST:

    /**
     * Dock child on the DockPanel.
     */
    public void dockWest(JComponent child);

    /**
     * Dock the given child into the given position on the DockPanel
     */
    public void dockWest(JComponent child, int idx);

    //ANYWHERE:

    /**
     * Dock the given child somewhere on the DockPanel.
     */
    public void dockSomewhere(JComponent child);

    //DOCK onto existing child:

    /**
     * Dock the given child onto the given parent, which is itself a
     * child.
     */
    public void dock(JComponent outter, JComponent inner);

    /**
     * Dock the given child onto the given parent, which is itself a
     * child.
     */
    public void dock(JComponent outter, JComponent inner, int idx);

    //FRAME Methods:

    /**
     * Set the component to an internal frame
     */
    public void internalFrame(JComponent child);

    /**
     * Set the component to an external frame
     */
    public void externalFrame(JComponent child);
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>OZYMANDIAS</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        {{content-for "head"}}

        <link rel="stylesheet" href="assets/vendor.css">
        <link rel="stylesheet" href="assets/ozymandias.css">

        {{content-for "head-footer"}}

Ozymandias

        {{content-for "body"}}

        {{content-for "body-footer"}}


text:
define(['dojo/_base/declare',
  'dojo/_base/lang',
  'dojo/dom-attr',
  'dojo/dom-style',
  'dojo/on',
  'dojo/json',
  'dojo/text!./SelectFeatureSetFromFile.html',
  'dijit/_TemplatedMixin',
  'dijit/_WidgetsInTemplateMixin',
  'esri/request',
  'esri/geometry/scaleUtils',
  'esri/InfoTemplate',
  'esri/layers/FeatureLayer',
  'esri/renderers/SimpleRenderer',
  'esri/tasks/FeatureSet',
  'jimu/dijit/Message',
  'jimu/portalUrlUtils',
  'jimu/symbolUtils',
  './BaseFeatureSetEditor',
  'dijit/form/Form',
  'dijit/form/Select'
],
function(declare, lang, domAttr, domStyle, on, JSON,
  template, _TemplatedMixin, _WidgetsInTemplateMixin, esriRequest,
  scaleUtils, InfoTemplate, FeatureLayer, SimpleRenderer, FeatureSet,
  Message, portalUrlUtils, symbolUtils, BaseFeatureSetEditor){
  return declare([BaseFeatureSetEditor, _TemplatedMixin, _WidgetsInTemplateMixin], {
    baseClass: 'jimu-gp-editor-base jimu-gp-editor-file',
    templateString: template,
    editorName: 'SelectFeatureSetFromFile',
    layer: undefined,

    constructor: function(){
      this.uniqueID = new Date().getTime();
    },

    postCreate: function(){
      this.inherited(arguments);
      domStyle.set(this.clearLink, 'display', 'none');
      domStyle.set(this.uploadStatus, 'display', 'none');
      this.uploadStatus.src = require.toUrl('jimu') + '/images/loading_circle.gif';
    },

    destroy: function(){
      this._clear();
    },

    getValue: function(){
      if(this.activeViewIndex === 0) {
        if(this.layer){
          var featureset = new FeatureSet();
          featureset.features = this.layer.graphics;
          return featureset;
        }else{
          return null;
        }
      } else {
        return this.getFeatureSet();
      }
    },

    _onUpload: function(){
      if(!domAttr.get(this.fileInput, 'value')){
        new Message({
          message:this.nls.noFileSelected
        });
        return;
      }

      var fileName = domAttr.get(this.fileInput, 'value');
      fileName = fileName.replace(/\\/g, '/');
      fileName = fileName.substr(fileName.lastIndexOf('/') + 1);
      this.fileInfo.innerHTML = fileName;
      domStyle.set(this.uploadStatus, 'display', '');
      //Define the input params for generate see the rest doc for details
      //http://www.arcgis.com/apidocs/rest/index.html?generate.html
      var params = {
        'name': fileName,
        'targetSR': this.map.spatialReference,
        'maxRecordCount': 1000,
        'enforceInputFileSizeLimit': true,
        'enforceOutputJsonSizeLimit': true
      };

      //generalize features for display. Here we generalize at 1:40,000 which is approx 10 meters
      //This should work well when using web mercator.
      var extent = scaleUtils.getExtentForScale(this.map, 40000);
      var resolution = extent.getWidth() / this.map.width;
      params.generalize = true;
      params.maxAllowableOffset = resolution;
      params.reducePrecision = true;
      params.numberOfDigitsAfterDecimal = 0;

      esriRequest({
        url: this._getPortalUrl() + '/sharing/rest/content/features/generate',
        content: {
          'filetype': 'shapefile',
          'publishParameters': JSON.stringify(params),
          'f': 'json'
        },
        form: this.fileForm.domNode,
        handleAs: 'json',
        load: lang.hitch(this, function(response){
          domStyle.set(this.uploadStatus, 'display', 'none');
          if (response.error) {
            new Message({
              message: response.error.message || response.error
            });
            return;
          }
          this.addToMap(response.featureCollection);
        }),
        error: lang.hitch(this, function(){
          domStyle.set(this.uploadStatus, 'display', 'none');
          var message = this.nls.generateShapefileError +
            this._getPortalUrl() + '/sharing/rest/content/features/generate';
          new Message({message: message});
        })
      });
    },

    addToMap: function(featureCollection){
      this._clear();

      var fsLayer = featureCollection.layers[0];
      var infoTemplate = new InfoTemplate('Details', '${*}');
      this.layer = new FeatureLayer(fsLayer, {
        infoTemplate: infoTemplate
      });
      //associate the feature with the popup on click to enable highlight and zoom to
      this.own(on(this.layer, 'click', lang.hitch(this, function (event) {
        this.map.infoWindow.setFeatures([event.graphic]);
      })));
      //change default symbol if desired. Comment this out and the layer will draw with the default symbology
      this.changeRenderer();
      var fullExtent = this.layer.fullExtent;

      this.map.addLayer(this.layer);
      this.map.setExtent(fullExtent.expand(1.25), true);

      domStyle.set(this.clearLink, 'display', '');
    },

    changeRenderer: function() {
      //change the default symbol for the feature collection for polygons and points
      var symbol = null;
      switch (this.layer.geometryType) {
      case 'esriGeometryPoint':
        symbol = symbolUtils.getDefaultMarkerSymbol();
        break;
      case 'esriGeometryPolyline':
        symbol = symbolUtils.getDefaultLineSymbol();
        break;
      case 'esriGeometryPolygon':
        symbol = symbolUtils.getDefaultFillSymbol();
        break;
      }
      if (symbol) {
        this.layer.setRenderer(new SimpleRenderer(symbol));
      }
    },

    _getPortalUrl: function(){
      return portalUrlUtils.getStandardPortalUrl(this.appConfig.portalUrl);
    },

    _clear: function(){
      if(this.layer){
        this.layer.clear();
        this.map.removeLayer(this.layer);
        this.fileInfo.innerHTML = '';
        domAttr.set(this.fileInput, 'value', '');
        domStyle.set(this.clearLink, 'display', 'none');
      }
    }
  });
});


text:
package com.lmax.disruptor.sequenced;

import com.lmax.disruptor.*;
import com.lmax.disruptor.dsl.ProducerType;
import com.lmax.disruptor.support.PerfTestUtil;
import com.lmax.disruptor.support.ValueAdditionEventHandler;
import com.lmax.disruptor.support.ValueEvent;
import com.lmax.disruptor.util.DaemonThreadFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.lmax.disruptor.RingBuffer.createMultiProducer;
import static com.lmax.disruptor.RingBuffer.createSingleProducer;
import static com.lmax.disruptor.support.PerfTestUtil.failIfNot;

/**
 * <pre>
 * UniCast a series of items between 1 publisher and 1 event processor.
 *
 * +----+    +-----+
 * | P1 |--->| EP1 |
 * +----+    +-----+
 *
 * Disruptor:
 * ==========
 *              track to prevent wrap
 *              +------------------+
 *              |                  |
 *              |                  v
 * +----+    +====+    +====+   +-----+
 * | P1 |--->| RB |<---| SB |   | EP1 |
 * +----+    +====+    +====+   +-----+
 *      claim      get    ^        |
 *                        |        |
 *                        +--------+
 *                          waitFor
 *
 * P1  - Publisher 1
 * RB  - RingBuffer
 * SB  - SequenceBarrier
 * EP1 - EventProcessor 1
 *
 * </pre>
 */
public final class OneToOneSequencedBatchThroughputTest extends AbstractPerfTestDisruptor {
    public static final int BATCH_SIZE = 10;
    private static final int BUFFER_SIZE = 1024 * 64;
    private static final long ITERATIONS = 1000L * 1000L * 100L;
    private final long expectedResult = PerfTestUtil.accumulatedAddition(ITERATIONS) * BATCH_SIZE;
    private final ExecutorService executor = Executors.newSingleThreadExecutor(DaemonThreadFactory.INSTANCE);
    private final SequenceBarrier sequenceBarrier;
    private final ValueAdditionEventHandler handler;
    private final BatchEventProcessor<ValueEvent> batchEventProcessor;
    private RingBuffer<ValueEvent> ringBuffer;

    public OneToOneSequencedBatchThroughputTest(ProducerType type, WaitStrategy strategy) {
        if (type.equals(ProducerType.SINGLE)) {
            this.ringBuffer = createSingleProducer(ValueEvent.EVENT_FACTORY, BUFFER_SIZE, strategy);
        }

        if (type.equals(ProducerType.MULTI)) {
            this.ringBuffer = createMultiProducer(ValueEvent.EVENT_FACTORY, BUFFER_SIZE, strategy);
        }

        sequenceBarrier = ringBuffer.newBarrier();
        handler = new ValueAdditionEventHandler();
        batchEventProcessor = new BatchEventProcessor<ValueEvent>(ringBuffer, sequenceBarrier, handler);
        ringBuffer.addGatingSequences(batchEventProcessor.getSequence());
    }

    public static void main(String[] args) throws Exception {
        System.out.println("ProducerType.SINGLE, use yield wait strategy");
        OneToOneSequencedBatchThroughputTest test1 = new OneToOneSequencedBatchThroughputTest(ProducerType.SINGLE, new YieldingWaitStrategy());
        test1.testImplementations();

        System.out.println("ProducerType.SINGLE, use sleep wait strategy");
        OneToOneSequencedBatchThroughputTest test2 = new OneToOneSequencedBatchThroughputTest(ProducerType.SINGLE, new SleepingWaitStrategy());
        test2.testImplementations();

        System.out.println("ProducerType.SINGLE, use block wait strategy");
        OneToOneSequencedBatchThroughputTest test3 = new OneToOneSequencedBatchThroughputTest(ProducerType.SINGLE, new BlockingWaitStrategy());
        test3.testImplementations();

        System.out.println("ProducerType.SINGLE, use busy spin wait strategy");
        OneToOneSequencedBatchThroughputTest test4 = new OneToOneSequencedBatchThroughputTest(ProducerType.SINGLE, new BusySpinWaitStrategy());
        test4.testImplementations();

        System.out.println("ProducerType.MULTI, use yield wait strategy");
        OneToOneSequencedBatchThroughputTest test5 = new OneToOneSequencedBatchThroughputTest(ProducerType.MULTI, new YieldingWaitStrategy());
        test5.testImplementations();

        System.out.println("ProducerType.MULTI, use sleep wait strategy");
        OneToOneSequencedBatchThroughputTest test6 = new OneToOneSequencedBatchThroughputTest(ProducerType.MULTI, new SleepingWaitStrategy());
        test6.testImplementations();

        System.out.println("ProducerType.MULTI, use block wait strategy");
        OneToOneSequencedBatchThroughputTest test7 = new OneToOneSequencedBatchThroughputTest(ProducerType.MULTI, new BlockingWaitStrategy());
        test7.testImplementations();

        System.out.println("ProducerType.MULTI, use busy spin wait strategy");
        OneToOneSequencedBatchThroughputTest test8 = new OneToOneSequencedBatchThroughputTest(ProducerType.MULTI, new BusySpinWaitStrategy());
        test8.testImplementations();
    }

    @Override
    protected int getRequiredProcessorCount() {
        return 2;
    }

    @Override
    protected long runDisruptorPass() throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(1);
        long expectedCount = batchEventProcessor.getSequence().get() + ITERATIONS * BATCH_SIZE;
        handler.reset(latch, expectedCount);
        executor.submit(batchEventProcessor);
        long start = System.currentTimeMillis();

        final RingBuffer<ValueEvent> rb = ringBuffer;

        for (long i = 0; i < ITERATIONS; i++) {
            long hi = rb.next(BATCH_SIZE);
            long lo = hi - (BATCH_SIZE - 1);
            for (long l = lo; l <= hi; l++) {
                rb.get(l).setValue(i);
            }
            rb.publish(lo, hi);
        }

        latch.await();
        long opsPerSecond = (BATCH_SIZE * ITERATIONS * 1000L) / (System.currentTimeMillis() - start);
        waitForEventProcessorSequence(expectedCount);
        batchEventProcessor.halt();

        failIfNot(expectedResult, handler.getValue());

        return opsPerSecond;
    }

    private void waitForEventProcessorSequence(long expectedCount) throws InterruptedException {
        while (batchEventProcessor.getSequence().get() != expectedCount) {
            Thread.sleep(1);
        }
    }
}


text:
package de.ifcore.hdv.converter.split;

import static org.junit.Assert.*;

import org.junit.Test;

import de.ifcore.hdv.converter.DataMocks;
import de.ifcore.hdv.converter.data.MergedData;

public class DataSplitterTest {

	@Test
	public void itShouldSplit() throws Exception {
		MergedData mergedData = DataMocks.mockMergedData();
		DataSplitter dataSplitter = new DataSplitter(mergedData);
		DataSplit dataSplit = dataSplitter.split();
		assertNotNull(dataSplit);
		assertEquals(mergedData, dataSplit.getMergedData());
		assertTrue(dataSplit.getProducts().containsKey(100));
	}
}


text:
class ProxyConfigDictionary;

namespace base {
class DictionaryValue;
class ListValue;
class Value;
}

namespace extensions {
namespace proxy_api_helpers {

// Conversion between PAC scripts and data-encoding URLs containing these
// PAC scripts. Data-encoding URLs consist of a data:// prefix, a mime-type and
// base64 encoded text. The functions return true in case of success.
// CreatePACScriptFromDataURL should only be called on data-encoding urls
// created with CreateDataURLFromPACScript.
bool CreateDataURLFromPACScript(const std::string& pac_script,
                                std::string* pac_script_url_base64_encoded);
bool CreatePACScriptFromDataURL(
    const std::string& pac_script_url_base64_encoded,
    std::string* pac_script);

// Helper functions for extension->browser pref transformation:

// The following functions extract one piece of data from the |proxy_config|
// each. |proxy_config| is a ProxyConfig dictionary as defined in the
// extension API. All output values conform to the format expected by a
// ProxyConfigDictionary.
//
// - If there are NO entries for the respective pieces of data, the functions
//   return true.
//   The GetPacMandatoryFromExtensionPref() function sets |out| to false in this
//   case.
// - If there ARE entries and they could be parsed, the functions set |out|
//   and return true.
// - If there are entries that could not be parsed, the functions set |error|
//   and return false.
//
// The parameter |bad_message| is passed to simulate the behavior of
// EXTENSION_FUNCTION_VALIDATE. It is never NULL.
bool GetProxyModeFromExtensionPref(const base::DictionaryValue* proxy_config,
                                   ProxyPrefs::ProxyMode* out,
                                   std::string* error,
                                   bool* bad_message);
bool GetPacMandatoryFromExtensionPref(const base::DictionaryValue* proxy_config,
                                      bool* out,
                                      std::string* error,
                                      bool* bad_message);
bool GetPacUrlFromExtensionPref(const base::DictionaryValue* proxy_config,
                                std::string* out,
                                std::string* error,
                                bool* bad_message);
bool GetPacDataFromExtensionPref(const base::DictionaryValue* proxy_config,
                                 std::string* out,
                                 std::string* error,
                                 bool* bad_message);
bool GetProxyRulesStringFromExtensionPref(
    const base::DictionaryValue* proxy_config,
    std::string* out,
    std::string* error,
    bool* bad_message);
bool GetBypassListFromExtensionPref(const base::DictionaryValue* proxy_config,
                                    std::string* out,
                                    std::string* error,
                                    bool* bad_message);

// Creates and returns a ProxyConfig dictionary (as defined in the extension
// API) from the given parameters. Ownership is passed to the caller.
// Depending on the value of |mode_enum|, several of the strings may be empty.
std::unique_ptr<base::Value> CreateProxyConfigDict(
    ProxyPrefs::ProxyMode mode_enum,
    bool pac_mandatory,
    const std::string& pac_url,
    const std::string& pac_data,
    const std::string& proxy_rules_string,
    const std::string& bypass_list,
    std::string* error);

// Converts a ProxyServer dictionary instance (as defined in the extension API)
// |proxy_server| to a net::ProxyServer.
// |default_scheme| is the default scheme that is filled in, in case the
// caller did not pass one.
// Returns true if successful and sets |error| otherwise.
bool GetProxyServer(const base::DictionaryValue* proxy_server,
                    net::ProxyServer::Scheme default_scheme,
                    net::ProxyServer* out,
                    std::string* error,
                    bool* bad_message);

// Joins a list of URLs (stored as StringValues) in |list| with |joiner|
// to |out|. Returns true if successful and sets |error| otherwise.
bool JoinUrlList(const base::ListValue* list,
                 const std::string& joiner,
                 std::string* out,
                 std::string* error,
                 bool* bad_message);

// Helper functions for browser->extension pref transformation:

// Creates and returns a ProxyRules dictionary as defined in the extension API
// with the values of a ProxyConfigDictionary configured for fixed proxy
// servers. Returns NULL in case of failures.
std::unique_ptr<base::DictionaryValue> CreateProxyRulesDict(
    const ProxyConfigDictionary& proxy_config);

// Creates and returns a ProxyServer dictionary as defined in the extension API
// with values from a net::ProxyServer object. Never returns NULL.
std::unique_ptr<base::DictionaryValue> CreateProxyServerDict(
    const net::ProxyServer& proxy);

// Creates and returns a PacScript dictionary as defined in the extension API
// with the values of a ProxyconfigDictionary configured for pac scripts.
// Returns NULL in case of failures.
std::unique_ptr<base::DictionaryValue> CreatePacScriptDict(
    const ProxyConfigDictionary& proxy_config);

// Tokenizes the |in| at delimiters |delims| and returns a new ListValue with
// StringValues created from the tokens.
std::unique_ptr<base::ListValue> TokenizeToStringList(
    const std::string& in,
    const std::string& delims);

}  // namespace proxy_api_helpers
}  // namespace extensions

#endif  // CHROME_BROWSER_EXTENSIONS_API_PROXY_PROXY_API_HELPERS_H_


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using StatsFetcher;
using System.IO;
using System.Reflection;

namespace StatsDisplay
{
	/// <summary>
	/// Interaction logic for Settings.xaml
	/// </summary>
	public partial class SettingsWindow : Window
	{
		public Properties.Settings Settings { get { return Properties.Settings.Default; } }
		private Window currentWindow;
		private HotKey hotKey;

		public SettingsWindow()
		{
			if (Settings.UpgradeRequired) {
				Settings.Upgrade();
				Settings.UpgradeRequired = false;
				Settings.Save();
			}

			InitializeComponent();
			var v = Assembly.GetExecutingAssembly().GetName().Version;
			Title = $"HotsStats v{v.Major}.{v.Minor}";
			if (Settings.SettingsWindowTop <= 0)
				WindowStartupLocation = WindowStartupLocation.CenterScreen;

			var mon = new FileMonitor();
			mon.BattleLobbyCreated += (o, e) => Dispatcher.BeginInvoke(new Action(() => { ProcessLobbyFile(e.Data); }));
			mon.RejoinFileCreated += (o,e) => Dispatcher.BeginInvoke(new Action(() => { ProcessRejoinFile(e.Data); }));
			mon.ReplayFileCreated += (o, e) => Dispatcher.BeginInvoke(new Action(() => { ProcessReplayFile(e.Data); }));
			mon.StartMonitoring();

			hotKey = new HotKey(Key.Tab, KeyModifier.Shift | KeyModifier.NoRepeat);
			hotKey.Pressed += (o, e) => {
				if (currentWindow != null)
					currentWindow.Visibility = currentWindow.IsVisible ? Visibility.Collapsed : Visibility.Visible;
			};

			Closing += (o, e) => {
				Settings.Save();
				Application.Current.Shutdown();
			};
		}

		private void ProcessLobbyFile(string path)
		{
			if (!Settings.Enabled)
				return;

			App.game = FileProcessor.ProcessLobbyFile(path);
			App.game.Me = App.game.Players.Where(p => p.BattleTag == Settings.BattleTag || p.Name == Settings.BattleTag).FirstOrDefault();

			currentWindow?.Close();
			currentWindow = new ShortStatsWindow();
			if (Settings.AutoShow)
				currentWindow.Show();
		}

		private void ProcessRejoinFile(string path)
		{
			FileProcessor.ProcessRejoin(path, App.game);
			currentWindow?.Close();
			currentWindow = new FullStatsWindow();
		}

		private void ProcessReplayFile(string path)
		{

		}

		private void Test1_Click(object sender, RoutedEventArgs e)
		{
			ProcessLobbyFile(@"replay.server.battlelobby");
		}

		private async void Test2_Click(object sender, RoutedEventArgs e)
		{
			ProcessRejoinFile(@"save.StormSave");
			currentWindow.Show();
		}
	}
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/**
 * @name: S10.2_A1.1_T1;
 * @section: 10.2;
 * @assertion: Every function call enters a new execution context;
 * @description: Sequence of function calls;
*/

var y;

function f(){
  var x;

  if(x === undefined) {
    x = 0;
  } else {
    x = 1;
  }

  return x;
}

y = f();
y = f();

if(!(y === 0)){
  $ERROR("#1: Sequenced function calls shares execution context");
}


text:
package com.akexorcist.mvpsimple.module.viewer.link;

import com.akexorcist.mvpsimple.bus.BusProvider;
import com.akexorcist.mvpsimple.network.model.PostList;

/**
 * Created by Akexorcist on 7/29/16 AD.
 */
public class FeedLinkPresenter implements FeedLinkContractor.Presenter {
    private FeedLinkContractor.View viewFeedLinkContractor;
    private PostList.Item postItem;

    public static FeedLinkPresenter createPresenter(FeedLinkContractor.View viewFeedLinkContractor) {
        return new FeedLinkPresenter(viewFeedLinkContractor);
    }

    public FeedLinkPresenter(FeedLinkContractor.View viewFeedLinkContractor) {
        this.viewFeedLinkContractor = viewFeedLinkContractor;
        viewFeedLinkContractor.setPresenter(this);
    }

    @Override
    public void setPostItem(PostList.Item postItem) {
        this.postItem = postItem;
        if (postItem != null) {
            viewFeedLinkContractor.setPostId(postItem.getId());
            viewFeedLinkContractor.setPostUrl(postItem.getUrl());
        }
    }

    @Override
    public PostList.Item getPostItem() {
        return postItem;
    }

    @Override
    public void start() {
        try {
            BusProvider.getProvider().getBus().register(this);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        BusProvider.getProvider().getBus().unregister(this);
    }
}


text:
import argparse
import logging
import sys

from .commands import COMMANDS, get_command_list

logger = logging.getLogger(__name__)

def main(args=None):
    if args is None:
        args = sys.argv[1:]

    parser = argparse.ArgumentParser(
        epilog=get_command_list(),
        formatter_class=argparse.RawDescriptionHelpFormatter
    )
    parser.add_argument(
        'command',
        type=str,
        nargs=1,
        choices=COMMANDS.keys()
    )
    parser.add_argument(
        '--loglevel',
        type=str,
        default='INFO'
    )
    args, extra = parser.parse_known_args()

    # Set up a simple console logger
    logging.basicConfig(level=args.loglevel)
    logging.addLevelName(
        logging.WARNING,
        "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.WARNING)
    )
    logging.addLevelName(
        logging.ERROR,
        "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR)
    )

    try:
        if args.command[0] in COMMANDS:
            COMMANDS[args.command[0]]['function'](args, *extra)
    except Exception as e:
        logger.exception(e)
        raise


text:
define(['./errors/bosherror',
        'xml',
        'ajax',
        'events',
        'class',
        'debug'],
function(BOSHError, xml, ajax, Emitter, clazz, debug) {
  debugrxd = debug('bosh:rx:data');
  debugtxd = debug('bosh:tx:data');

  function Request(url, body, fn) {
    Emitter.call(this);
    this.rid = body.attr('rid');
    this.payloadCount = body.children().length;
    this.fn = fn;
    this.statusType = undefined;
    this.statusCondition = undefined;
    this.response = undefined;

    this._url = url;
    this._data = body.toString();
    this._req = null;
  }
  clazz.inherits(Request, Emitter);

  Request.prototype.send = function() {
    var self = this
      , req = ajax.request(this._url, 'POST');

    this._req = req;

    req.on('response', function(res) {
      res.on('end', function() {
        debugrxd('status: ' + res.statusCode);
        debugrxd(res.responseText);

        if (res.statusCode == 200) {
          var body;
          try {
            body = self.response = xml(res.responseXML);
          } catch(err) {
            self.emit('error', err);
            return;
          }

          if (!body.is('body', 'http://jabber.org/protocol/httpbind')) {
            self.emit('error', new BOSHError('Bad protocol'));
            return;
          }

          self.statusType = body.attr('type') || 'ok';
          self.statusCondition = body.attr('condition') || 'ok';
          self.emit('end');
        } else {
          var cond = 'internal-server-error';
          switch (res.statusCode) {
            case 400:
              cond = 'bad-request';
              break;
            case 403:
              cond = 'policy-violation';
              break;
            case 404:
              cond = 'item-not-found';
              break;
          }

          self.statusType = 'terminate';
          self.statusCondition = cond;
          self.emit('end');
        }
      });
      res.on('error', function(err) {
        self.emit('error', err);
      });
    });
    req.on('error', function(err) {
      self.emit('error', err);
    });

    debugtxd(this._data);
    req.setHeader('Content-Type', 'text/xml; charset=utf-8');
    req.send(this._data);
  }

  Request.prototype.abort = function() {
    this._req.abort();
  }

  return Request;
});


text:
'use strict'

var express = require('express')

var qs = require('qs')

var config = require('../config')
var flows = {
  1: require('../flow/oauth1'),
  2: require('../flow/oauth2'),
  getpocket: require('../flow/getpocket')
}

function Grant (_config) {
  var app = express()
  app.config = config.init(_config)
  app._config = config

  app.all('/connect/:provider/:override?', function (req, res, next) {
    if (!req.session)
      throw new Error('Grant: mount session middleware first')
    if (req.method == 'POST' && !req.body)
      throw new Error('Grant: mount body parser middleware first')
    next()
  })

  app.get('/connect/:provider/:override?', function (req, res, next) {
    if (req.params.override == 'callback') return next()

    req.session.grant = {
      provider:req.params.provider
    }
    if (req.params.override) {
      req.session.grant.override = req.params.override
    }
    if (Object.keys(req.query||{}).length) {
      req.session.grant.dynamic = req.query
    }

    connect(req, res)
  })

  app.post('/connect/:provider/:override?', function (req, res) {
    req.session.grant = {
      provider:req.params.provider
    }
    if (req.params.override) {
      req.session.grant.override = req.params.override
    }
    if (Object.keys(req.body||{}).length) {
      req.session.grant.dynamic = req.body
    }

    connect(req, res)
  })

  function connect (req, res) {
    var grant = req.session.grant
    var provider = config.provider(app.config, grant)
    var flow = flows[provider.oauth]

    if (provider.oauth == 1) {
      flow.step1(provider, function (err, data) {
        if (err) return res.redirect(provider.callback + '?' + err)
        grant.step1 = data
        var url = flow.step2(provider, data)
        res.redirect(url)
      })
    }

    else if (provider.oauth == 2) {
      grant.state = provider.state
      var url = flow.step1(provider)
      res.redirect(url)
    }

    else if (flow) {
      flow.step1(provider, function (err, data) {
        if (err) return res.redirect(provider.callback + '?' + err)
        grant.step1 = data
        var url = flow.step2(provider, data)
        res.redirect(url)
      })
    }

    else {
      var err = {error:'Grant: missing or misconfigured provider'}
      if (provider.callback) {
        res.redirect(provider.callback + '?' + qs.stringify(err))
      } else {
        res.end(JSON.stringify(err))
      }
    }
  }

  app.get('/connect/:provider/callback', function (req, res) {
    var grant = req.session.grant || {}
    var provider = config.provider(app.config, grant)
    var flow = flows[provider.oauth]

    function callback (response) {
      if (!provider.transport || provider.transport == 'querystring') {
        res.redirect(provider.callback + '?' + response)
      }
      else if (provider.transport == 'session') {
        req.session.grant.response = qs.parse(response)
        res.redirect(provider.callback)
      }
    }

    if (provider.oauth == 1) {
      flow.step3(provider, grant.step1, req.query, function (err, response) {
        if (err) return res.redirect(provider.callback + '?' + err)
        callback(response)
      })
    }

    else if (provider.oauth == 2) {
      flow.step2(provider, req.query, grant, function (err, data) {
        if (err) return res.redirect(provider.callback + '?' + err)
        var response = flow.step3(provider, data)
        callback(response)
      })
    }

    else if (flow) {
      flow.step3(provider, grant.step1, function (err, response) {
        if (err) return res.redirect(provider.callback + '?' + err)
        callback(response)
      })
    }

    else {
      var err = {error:'Grant: missing session or misconfigured provider'}
      if (provider.callback) {
        res.redirect(provider.callback + '?' + qs.stringify(err))
      } else {
        res.end(JSON.stringify(err))
      }
    }
  })

  return app
}

exports = module.exports = Grant


text:
package org.springframework.context.annotation;

/**
 * A {@link Condition} that offers more fine-grained control when used with
 * {@code @Configuration}. Allows certain conditions to adapt when they match
 * based on the configuration phase. For example, a condition that checks if a bean
 * has already been registered might choose to only be evaluated during the
 * {@link ConfigurationPhase#REGISTER_BEAN REGISTER_BEAN} {@link ConfigurationPhase}.
 *
 * @author Phillip Webb
 * @since 4.0
 * @see Configuration
 */
public interface ConfigurationCondition extends Condition {

	/**
	 * Return the {@link ConfigurationPhase} in which the condition should be evaluated.
	 */
	ConfigurationPhase getConfigurationPhase();

	/**
	 * The various configuration phases where the condition could be evaluated.
	 */
	enum ConfigurationPhase {

		/**
		 * The {@link Condition} should be evaluated as a {@code @Configuration}
		 * class is being parsed.
		 *
If the condition does not match at this point, the {@code @Configuration}
		 * class will not be added.
		 */
		PARSE_CONFIGURATION,

		/**
		 * The {@link Condition} should be evaluated when adding a regular
		 * (non {@code @Configuration}) bean. The condition will not prevent
		 * {@code @Configuration} classes from being added.
		 *
At the time that the condition is evaluated, all {@code @Configuration}
		 * classes will have been parsed.
		 */
		REGISTER_BEAN
	}

}


text:
using Battleship.GameC.Model.Boards;
using Battleship.GameC.Model.Games;
using Battleship.GameC.Model.Players;
using FluentAssertions;
using Xunit;

namespace Battleship.GameC.Test.Unit
{
    public class BattleshipGameTests
    {
        [Fact]
        public void BattleshipGame_CanBeCreated()
        {
            // Arrange
            var playerA = new Player(
                    PlayerId.NewId(),
                    (PlayerName)"Player A",
                    BoardBuilder.GetEmpty(),
                    BoardBuilder.GetEmpty());
            var playerB = new Player(
                    PlayerId.NewId(),
                    (PlayerName)"Player B",
                    BoardBuilder.GetEmpty(),
                    BoardBuilder.GetEmpty());

            // Act
            var game = new BattleshipGame(
                    GameId.NewId(),
                    GameStatus.Ready,
                    playerA,
                    playerB);

            // Assert
            game.Should().NotBeNull();
            game.Status.Should().Be(GameStatus.Ready);
        }
    }
}


text:
//                           _       _
// __      _____  __ ___   ___  __ _| |_ ___
// \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
//  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
//   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
//
//  Copyright © 2016 - 2020 SeMI Holding B.V. (registered @ Dutch Chamber of Commerce no 75221632). All rights reserved.
//  LICENSE WEAVIATE OPEN SOURCE: https://www.semi.technology/playbook/playbook/contract-weaviate-OSS.html
//  LICENSE WEAVIATE ENTERPRISE: https://www.semi.technology/playbook/contract-weaviate-enterprise.html
//  CONCEPT: Bob van Luijt (@bobvanluijt)
//  CONTACT: hello@semi.technology
//

// Code generated by go-swagger; DO NOT EDIT.

package things

// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command

import (
	"context"
	"net/http"
	"time"

	"github.com/go-openapi/errors"
	"github.com/go-openapi/runtime"
	cr "github.com/go-openapi/runtime/client"

	strfmt "github.com/go-openapi/strfmt"

	models "github.com/semi-technologies/weaviate/entities/models"
)

// NewThingsValidateParams creates a new ThingsValidateParams object
// with the default values initialized.
func NewThingsValidateParams() *ThingsValidateParams {
	var ()
	return &ThingsValidateParams{

		timeout: cr.DefaultTimeout,
	}
}

// NewThingsValidateParamsWithTimeout creates a new ThingsValidateParams object
// with the default values initialized, and the ability to set a timeout on a request
func NewThingsValidateParamsWithTimeout(timeout time.Duration) *ThingsValidateParams {
	var ()
	return &ThingsValidateParams{

		timeout: timeout,
	}
}

// NewThingsValidateParamsWithContext creates a new ThingsValidateParams object
// with the default values initialized, and the ability to set a context for a request
func NewThingsValidateParamsWithContext(ctx context.Context) *ThingsValidateParams {
	var ()
	return &ThingsValidateParams{

		Context: ctx,
	}
}

// NewThingsValidateParamsWithHTTPClient creates a new ThingsValidateParams object
// with the default values initialized, and the ability to set a custom HTTPClient for a request
func NewThingsValidateParamsWithHTTPClient(client *http.Client) *ThingsValidateParams {
	var ()
	return &ThingsValidateParams{
		HTTPClient: client,
	}
}

/*ThingsValidateParams contains all the parameters to send to the API endpoint
for the things validate operation typically these are written to a http.Request
*/
type ThingsValidateParams struct {

	/*Body*/
	Body *models.Thing

	timeout    time.Duration
	Context    context.Context
	HTTPClient *http.Client
}

// WithTimeout adds the timeout to the things validate params
func (o *ThingsValidateParams) WithTimeout(timeout time.Duration) *ThingsValidateParams {
	o.SetTimeout(timeout)
	return o
}

// SetTimeout adds the timeout to the things validate params
func (o *ThingsValidateParams) SetTimeout(timeout time.Duration) {
	o.timeout = timeout
}

// WithContext adds the context to the things validate params
func (o *ThingsValidateParams) WithContext(ctx context.Context) *ThingsValidateParams {
	o.SetContext(ctx)
	return o
}

// SetContext adds the context to the things validate params
func (o *ThingsValidateParams) SetContext(ctx context.Context) {
	o.Context = ctx
}

// WithHTTPClient adds the HTTPClient to the things validate params
func (o *ThingsValidateParams) WithHTTPClient(client *http.Client) *ThingsValidateParams {
	o.SetHTTPClient(client)
	return o
}

// SetHTTPClient adds the HTTPClient to the things validate params
func (o *ThingsValidateParams) SetHTTPClient(client *http.Client) {
	o.HTTPClient = client
}

// WithBody adds the body to the things validate params
func (o *ThingsValidateParams) WithBody(body *models.Thing) *ThingsValidateParams {
	o.SetBody(body)
	return o
}

// SetBody adds the body to the things validate params
func (o *ThingsValidateParams) SetBody(body *models.Thing) {
	o.Body = body
}

// WriteToRequest writes these params to a swagger request
func (o *ThingsValidateParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {

	if err := r.SetTimeout(o.timeout); err != nil {
		return err
	}
	var res []error

	if o.Body != nil {
		if err := r.SetBodyParam(o.Body); err != nil {
			return err
		}
	}

	if len(res) > 0 {
		return errors.CompositeValidationError(res...)
	}
	return nil
}


text:
namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template <typename Geometry, typename Tag = typename tag<Geometry>::type>
struct is_simple
    : not_implemented<Geometry>
{};

} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_DISPATCH_IS_SIMPLE_HPP


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/toolbar_padding_top"
    android:background="@drawable/toolbar_color"
    android:minHeight="?attr/actionBarSize"
    android:gravity="center"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" >
    <TextView
        android:text="Persei"
        android:gravity="center"
        android:textColor="#202020"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    </android.support.v7.widget.Toolbar>


text:
function simulate_subspace_preservation(solver, solver_name, solver_params)
if nargin < 3
    solver_params = struct;
end

% We will carry out one experiment for each signal density level
rhos = round(5.^[1:.4:5]);
rhos = round(5.^[1:.4:3.5]);
% Number of experiments
R= numel(rhos);
estimated_num_subspaces = zeros(1, R);
estimated_coefficients = cell(1, R);
estimated_labels = cell(1, R);
true_labels = cell(1, R);
comparsion_results = cell(1, R);
connectivity = zeros(1, R);

% Create the directory for storing data
[status_code,message,message_id] = mkdir('bin');

for r=1:R
    rho = rhos(r);
    % Ambient space dimension
    M = 9;
    % Number of subspaces
    K = 5;
    % common dimension for each subspace
    D = 6;
    % dimensions of each subspace
    Ds = D * ones(1, K);
    bases = spx.data.synthetic.subspaces.random_subspaces(M, K, Ds);
    % Number of points on each subspace
    Sk = rho * D;
    Ss = Sk * ones(1, K);
    % total number of points
    S = sum(Ss);
    fprintf('Points per subspace: %d, Total points: %d\n', Sk, S);
    % Let us generate uniformly distributed points in each subspace
    points_result = spx.data.synthetic.subspaces.uniform_points_on_subspaces(bases, Ss);
    X = points_result.X;
    start_indices = points_result.start_indices;
    end_indices = points_result.end_indices;
    % Solve the sparse subspace clustering problem
    clustering_result = solver(X, D, K, solver_params);
    cluster_labels = clustering_result.labels;
    estimated_labels{r} = cluster_labels;
    % estimated_coefficients{r} = clustering_result.Z;
    estimated_num_subspaces(r) = clustering_result.num_clusters;
    cur_true_labels = spx.cluster.labels_from_cluster_sizes(Ss);
    true_labels{r} = cur_true_labels;
    % Time to compare the clustering
    comparer = spx.cluster.ClusterComparison(cur_true_labels, cluster_labels);
    comparsion_result = comparer.fMeasure();
    comparsion_results{r} = comparsion_result;
    connectivity(r) = spx.cluster.spectral.simple.connectivity(clustering_result.W, cur_true_labels);
    fprintf('\nPoint density: %0.2f: , fMeasure: %0.2f, connectivity: %0.2f  ', rho, comparsion_result.fMeasure, connectivity(r));
    if clustering_result.num_clusters == K
        fprintf('K: Success');
    else
        fprintf('K: Failure');
    end
    fprintf('\n\n');
end

filepath = sprintf('bin/subspace_preservation_test_%s.mat', solver_name);
save(filepath);

end


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace System.Windows.Forms
{
    public class RibbonOrbDropDownEventArgs
        : RibbonRenderEventArgs
    {
        #region Fields
        private RibbonOrbDropDown _dropDown;
        #endregion

        #region Ctor
        public RibbonOrbDropDownEventArgs(Ribbon ribbon, RibbonOrbDropDown dropDown, Graphics g, Rectangle clip)
            : base(ribbon, g, clip)
        {
            _dropDown = dropDown;
        }
        #endregion

        #region Props
        /// <summary>
        /// Gets the RibbonOrbDropDown related to the event
        /// </summary>
        public RibbonOrbDropDown RibbonOrbDropDown
        {
            get { return _dropDown; }
        }

        #endregion
    }
}