text:
<!doctype html>

  <meta charset="UTF-8">
  <title>Estimated Cost Analysis</title>

These metrics are not meant to be used as law but are a relative measure of the quality
  and cost of a program

Back to Overview

    Metric
    Value
    Description

    Maintainability
    80.50
    This is the relative maintainability of the file on a scale of 0-100. Higher is better.

    Difficulty
    8.63
    This is a measure of how difficult it is to understand the code. Lower is better.

    Cyclomatic Complexity
    1
    This is how complex the code is based on the number of paths through the code. Lower is better

    Cyclomatic Density
    4.00
    This is a re-expression of the above metric as a percentage based on the lines of code. Lower is better.

    Effort
    5232.79
    This is the amount of effort needed to write the code based on it's difficulty and length

    Time
    0.08 Hours
    This is the estimated amount of time needed to write the file based on the effort required.

    Cost
    $3.78
    This is the estimated cost to develop the file based on the time needed to develop it.

    Bugs
    0.20
    This is the estimated number of bugs in the file.

    Logical SLOC
    25
    This is the number of lines of software that are considered logic.

    Physical SLOC
    40
    This is the total lines of source code including up to 25% whitespace, but ignoring excessive formatting.

Dependencies:

    Name
    Line #
    Type

    gen
    3
    CommonJS

Functions:

    main

    Metric
    Value
    Description

    Line #
    6
    The line the function appears on.

    Parameters
    0
    The number of parameters the function takes.

    Difficulty
    2.00
    This is a measure of how difficult the method is to understand. Lower is better.

    Cyclomatic Complexity
    1
    This is how complex the method is based on the number of paths through the code. Lower is better.

    Cyclomatic Density
    33.33
    This is a re-expression of the above metric as a percentage based on the lines of code. Lower is better.

    Effort
    111.01
    This is the amount of effort needed to write the code based on it's difficulty and length.

    Time
    0.10 Minutes
    This is the estimated amount of time needed to write the method based on the effort required.

    Cost
    $0.80
    This is the estimated cost to develop the file based on the time needed to develop it.

    Bugs
    0.02
    This is the estimated number of bugs in the method.

    Logical SLOC
    3
    This is the number of lines of software that are considered logic.

    Physical SLOC
    22
    This is the total lines of source code including up to 25% whitespace, but ignoring excessive formatting.

    nested

    Metric
    Value
    Description

    Line #
    7
    The line the function appears on.

    Parameters
    0
    The number of parameters the function takes.

    Difficulty
    1.00
    This is a measure of how difficult the method is to understand. Lower is better.

    Cyclomatic Complexity
    1
    This is how complex the method is based on the number of paths through the code. Lower is better.

    Cyclomatic Density
    100.00
    This is a re-expression of the above metric as a percentage based on the lines of code. Lower is better.

    Effort
    11.61
    This is the amount of effort needed to write the code based on it's difficulty and length.

    Time
    0.01 Minutes
    This is the estimated amount of time needed to write the method based on the effort required.

    Cost
    $0.08
    This is the estimated cost to develop the file based on the time needed to develop it.

    Bugs
    0.00
    This is the estimated number of bugs in the method.

    Logical SLOC
    1
    This is the number of lines of software that are considered logic.

    Physical SLOC
    10
    This is the total lines of source code including up to 25% whitespace, but ignoring excessive formatting.

    delayed

    Metric
    Value
    Description

    Line #
    8
    The line the function appears on.

    Parameters
    1
    The number of parameters the function takes.

    Difficulty
    2.29
    This is a measure of how difficult the method is to understand. Lower is better.

    Cyclomatic Complexity
    1
    This is how complex the method is based on the number of paths through the code. Lower is better.

    Cyclomatic Density
    16.67
    This is a re-expression of the above metric as a percentage based on the lines of code. Lower is better.

    Effort
    188.38
    This is the amount of effort needed to write the code based on it's difficulty and length.

    Time
    0.17 Minutes
    This is the estimated amount of time needed to write the method based on the effort required.

    Cost
    $1.36
    This is the estimated cost to develop the file based on the time needed to develop it.

    Bugs
    0.03
    This is the estimated number of bugs in the method.

    Logical SLOC
    6
    This is the number of lines of software that are considered logic.

    Physical SLOC
    8
    This is the total lines of source code including up to 25% whitespace, but ignoring excessive formatting.

    innerBench

    Metric
    Value
    Description

    Line #
    20
    The line the function appears on.

    Parameters
    1
    The number of parameters the function takes.

    Difficulty
    2.29
    This is a measure of how difficult the method is to understand. Lower is better.

    Cyclomatic Complexity
    1
    This is how complex the method is based on the number of paths through the code. Lower is better.

    Cyclomatic Density
    20.00
    This is a re-expression of the above metric as a percentage based on the lines of code. Lower is better.

    Effort
    188.38
    This is the amount of effort needed to write the code based on it's difficulty and length.

    Time
    0.17 Minutes
    This is the estimated amount of time needed to write the method based on the effort required.

    Cost
    $1.36
    This is the estimated cost to develop the file based on the time needed to develop it.

    Bugs
    0.03
    This is the estimated number of bugs in the method.

    Logical SLOC
    5
    This is the number of lines of software that are considered logic.

    Physical SLOC
    7
    This is the total lines of source code including up to 25% whitespace, but ignoring excessive formatting.

    errorSuite

    Metric
    Value
    Description

    Line #
    32
    The line the function appears on.

    Parameters
    0
    The number of parameters the function takes.

    Difficulty
    2.00
    This is a measure of how difficult the method is to understand. Lower is better.

    Cyclomatic Complexity
    1
    This is how complex the method is based on the number of paths through the code. Lower is better.

    Cyclomatic Density
    50.00
    This is a re-expression of the above metric as a percentage based on the lines of code. Lower is better.

    Effort
    66.44
    This is the amount of effort needed to write the code based on it's difficulty and length.

    Time
    0.06 Minutes
    This is the estimated amount of time needed to write the method based on the effort required.

    Cost
    $0.48
    This is the estimated cost to develop the file based on the time needed to develop it.

    Bugs
    0.01
    This is the estimated number of bugs in the method.

    Logical SLOC
    2
    This is the number of lines of software that are considered logic.

    Physical SLOC
    7
    This is the total lines of source code including up to 25% whitespace, but ignoring excessive formatting.

    errorBench

    Metric
    Value
    Description

    Line #
    33
    The line the function appears on.

    Parameters
    0
    The number of parameters the function takes.

    Difficulty
    0.50
    This is a measure of how difficult the method is to understand. Lower is better.

    Cyclomatic Complexity
    1
    This is how complex the method is based on the number of paths through the code. Lower is better.

    Cyclomatic Density
    100.00
    This is a re-expression of the above metric as a percentage based on the lines of code. Lower is better.

    Effort
    1.00
    This is the amount of effort needed to write the code based on it's difficulty and length.

    Time
    0.00 Minutes
    This is the estimated amount of time needed to write the method based on the effort required.

    Cost
    $0.01
    This is the estimated cost to develop the file based on the time needed to develop it.

    Bugs
    0.00
    This is the estimated number of bugs in the method.

    Logical SLOC
    1
    This is the number of lines of software that are considered logic.

    Physical SLOC
    3
    This is the total lines of source code including up to 25% whitespace, but ignoring excessive formatting.


text:
package eu.qualimaster.common.shedding;

import java.io.Serializable;

/**
 * An instance containing the information for configuring a load shedder.
 *
 * @author Holger Eichelberger
 */
public interface ILoadShedderConfigurer {

    /**
     * Returns the value of an int parameter.
     *
     * @param name the name of the parameter
     * @param dflt the default value to be returned if the parameter is not specified / cannot be read
     * @return the value
     */
    public int getIntParameter(String name, int dflt);

    /**
     * Returns the value of an int parameter.
     *
     * @param param the parameter identifier
     * @param dflt the default value to be returned if the parameter is not specified / cannot be read
     * @return the value
     */
    public int getIntParameter(ILoadSheddingParameter param, int dflt);

    /**
     * Returns the value of a double parameter.
     *
     * @param name the name of the parameter
     * @param dflt the default value to be returned if the parameter is not specified / cannot be read
     * @return the value
     */
    public double getDoubleParameter(String name, double dflt);

    /**
     * Returns the value of a double parameter.
     *
     * @param param the parameter identifier
     * @param dflt the default value to be returned if the parameter is not specified / cannot be read
     * @return the value
     */
    public double getDoubleParameter(ILoadSheddingParameter param, double dflt);

    /**
     * Returns the value of a parameter.
     *
     * @param param the identifier of the parameter
     * @return the value or null if unknown
     */
    public Serializable getParameter(ILoadSheddingParameter param);

    /**
     * Returns the value of a parameter.
     *
     * @param name the name of the parameter
     * @return the value or null if unknown
     */
    public Serializable getParameter(String name);

}

redpajama_set_name: RedPajamaGithub


text:
package go_n1ql

import (
	"database/sql/driver"
	"io"
	"testing"
)

// This test assumes a Couchbase instance is accessible on the local machine,
// and that the standard bucket "beer-sample" is available on it.

func TestConnection(t *testing.T) {
	conn, err := OpenN1QLConnection("http://localhost:8093")
	if err != nil {
		t.Fatal(err)
	}

	results, err := conn.(*n1qlConn).Query("select * from `beer-sample` where city = 'San Francisco'", nil)
	if err != nil {
		t.Fatal(err)
	}

	result := make([]driver.Value, 1)
	totalRows := 0
	for results.Next(result) != io.EOF {
		totalRows++
	}

	if totalRows == 0 {
		t.Fatal("Query returned 0 rows")
	}

	results, err = conn.(*n1qlConn).Query("select * from `beer-sample` where city = \"London\"", nil)
	if err != nil {
		t.Fatal(err)
	}

	totalRows = 0
	for results.Next(result) != io.EOF {
		totalRows++
	}
	results.Close()

	if totalRows != 4 {
		t.Fatal("Expecting 4 rows got %d", totalRows)
	}

	stmt, err := conn.Prepare("select * from `beer-sample` where type = \"brewery\" limit 5")
	if err != nil {
		t.Fatal(err)
	}

	results, err = stmt.Query(nil)
	if err != nil {
		t.Fatal(err)
	}

	totalRows = 0
	for results.Next(result) != io.EOF {
		totalRows++
	}

	if totalRows != 5 {
		t.Fatal(" Got %d Rows instead of 5", totalRows)
	}

	res, err := conn.(*n1qlConn).Exec("upsert into `beer-sample` (key,value) values ('irish2', {'name': 'irish', 'type':'contact'})", nil)
	if err != nil {
		t.Fatal(err)
	}

	ra, _ := res.RowsAffected()
	if ra != 1 {
		t.Fatal("Insert failed.")
	}

	res, err = conn.(*n1qlConn).Exec("delete from `beer-sample` use keys \"irish2\"", nil)
	if err != nil {
		t.Fatal(err)
	}

}


text:
;(function () {
    "use strict";
    LaPa.HOOK.reg('initLib', false, function () {
        LaPa.COOKIE = {
            'get': function (name) {
                var matches = document.cookie.match(new RegExp(
                    "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
                ));
                return matches ? decodeURIComponent(matches[1]) : undefined;
            },
            'set': function (name, value, options) {
                options = options || {};

                var expires = options.expires;

                if (typeof expires == "number" && expires) {
                    var d = new Date();
                    d.setTime(d.getTime() + expires * 1000);
                    expires = options.expires = d;
                }
                if (expires && expires.toUTCString) {
                    options.expires = expires.toUTCString();
                }

                value = encodeURIComponent(value);

                var updatedCookie = name + "=" + value;

                for (var propName in options) {
                    updatedCookie += "; " + propName;
                    var propValue = options[propName];
                    if (propValue !== true) {
                        updatedCookie += "=" + propValue;
                    }
                }

                document.cookie = updatedCookie;
            },
            'del': function (name) {
                LaPa.COOKIE.set(name, "", {
                    expires: -1
                })
            }
        };
    }, '/lib/cookie.js');
    LaPa.importLib('/lib/cookie.js');
})();


text:
from __future__ import division, unicode_literals
import math
import numpy as np

from monty.dev import deprecated

"""
Utilities for generating nicer plots.
"""

__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "Mar 13, 2012"

def pretty_plot(width=8, height=None, plt=None, dpi=None,
                color_cycle=("qualitative", "Set1_9")):
    """
    Provides a publication quality plot, with nice defaults for font sizes etc.

    Args:
        width (float): Width of plot in inches. Defaults to 8in.
        height (float): Height of plot in inches. Defaults to width * golden
            ratio.
        plt (matplotlib.pyplot): If plt is supplied, changes will be made to an
            existing plot. Otherwise, a new plot will be created.
        dpi (int): Sets dot per inch for figure. Defaults to 300.
        color_cycle (tuple): Set the color cycle for new plots to one of the
            color sets in palettable. Defaults to a qualitative Set1_9.

    Returns:
        Matplotlib plot object with properly sized fonts.
    """
    ticksize = int(width * 2.5)

    golden_ratio = (math.sqrt(5) - 1) / 2

    if not height:
        height = int(width * golden_ratio)

    if plt is None:
        import matplotlib.pyplot as plt
        import importlib
        mod = importlib.import_module("palettable.colorbrewer.%s" %
                                      color_cycle[0])
        colors = getattr(mod, color_cycle[1]).mpl_colors
        from cycler import cycler

        plt.figure(figsize=(width, height), facecolor="w", dpi=dpi)
        ax = plt.gca()
        ax.set_prop_cycle(cycler('color', colors))
    else:
        fig = plt.gcf()
        fig.set_size_inches(width, height)
    plt.xticks(fontsize=ticksize)
    plt.yticks(fontsize=ticksize)

    ax = plt.gca()
    ax.set_title(ax.get_title(), size=width * 4)

    labelsize = int(width * 3)

    ax.set_xlabel(ax.get_xlabel(), size=labelsize)
    ax.set_ylabel(ax.get_ylabel(), size=labelsize)

    return plt

@deprecated(pretty_plot, "get_publication_quality_plot has been renamed "
                         "pretty_plot. This stub will be removed in pmg 2018.01.01.")
def get_publication_quality_plot(*args, **kwargs):
    return pretty_plot(*args, **kwargs)

def pretty_plot_two_axis(x, y1, y2, xlabel=None, y1label=None, y2label=None,
                         width=8, height=None, dpi=300):
    """
    Variant of pretty_plot that does a dual axis plot. Adapted from matplotlib
    examples. Makes it easier to create plots with different axes.

    Args:
        x (np.ndarray/list): Data for x-axis.
        y1 (dict/np.ndarray/list): Data for y1 axis (left). If a dict, it will
            be interpreted as a {label: sequence}.
        y2 (dict/np.ndarray/list): Data for y2 axis (right). If a dict, it will
            be interpreted as a {label: sequence}.
        xlabel (str): If not None, this will be the label for the x-axis.
        y1label (str): If not None, this will be the label for the y1-axis.
        y2label (str): If not None, this will be the label for the y2-axis.
        width (float): Width of plot in inches. Defaults to 8in.
        height (float): Height of plot in inches. Defaults to width * golden
            ratio.
        dpi (int): Sets dot per inch for figure. Defaults to 300.

    Returns:
        matplotlib.pyplot
    """

    import palettable.colorbrewer.diverging

    colors = palettable.colorbrewer.diverging.RdYlBu_4.mpl_colors
    c1 = colors[0]
    c2 = colors[-1]

    golden_ratio = (math.sqrt(5) - 1) / 2

    if not height:
        height = int(width * golden_ratio)

    import matplotlib.pyplot as plt
    width = 12
    labelsize = int(width * 3)
    ticksize = int(width * 2.5)
    styles = ["-", "--", "-.", "."]

    fig, ax1 = plt.subplots()
    fig.set_size_inches((width, height))
    if dpi:
        fig.set_dpi(dpi)
    if isinstance(y1, dict):
        for i, (k, v) in enumerate(y1.items()):
            ax1.plot(x, v, c=c1, marker='s', ls=styles[i % len(styles)],
                     label=k)
        ax1.legend(fontsize=labelsize)
    else:
        ax1.plot(x, y1, c=c1, marker='s', ls='-')

    if xlabel:
        ax1.set_xlabel(xlabel, fontsize=labelsize)

    if y1label:
        # Make the y-axis label, ticks and tick labels match the line color.
        ax1.set_ylabel(y1label, color=c1, fontsize=labelsize)

    ax1.tick_params('x', labelsize=ticksize)
    ax1.tick_params('y', colors=c1, labelsize=ticksize)

    ax2 = ax1.twinx()
    if isinstance(y2, dict):
        for i, (k, v) in enumerate(y2.items()):
            ax2.plot(x, v, c=c2, marker='o', ls=styles[i % len(styles)],
                     label=k)
        ax2.legend(fontsize=labelsize)
    else:
        ax2.plot(x, y2, c=c2, marker='o', ls='-')

    if y2label:
        # Make the y-axis label, ticks and tick labels match the line color.
        ax2.set_ylabel(y2label, color=c2, fontsize=labelsize)

    ax2.tick_params('y', colors=c2, labelsize=ticksize)
    return plt

def pretty_polyfit_plot(x, y, deg=1, xlabel=None, ylabel=None,
                        **kwargs):
    """
    Convenience method to plot data with trend lines based on polynomial fit.

    Args:
        x: Sequence of x data.
        y: Sequence of y data.
        deg (int): Degree of polynomial. Defaults to 1.
        xlabel (str): Label for x-axis.
        ylabel (str): Label for y-axis.
        \\*\\*kwargs: Keyword args passed to pretty_plot.

    Returns:
        matplotlib.pyplot object.
    """
    plt = pretty_plot(**kwargs)
    pp = np.polyfit(x, y, deg)
    xp = np.linspace(min(x), max(x), 200)
    plt.plot(xp, np.polyval(pp, xp), 'k--', x, y, 'o')
    if xlabel:
        plt.xlabel(xlabel)
    if ylabel:
        plt.ylabel(ylabel)
    return plt

def get_ax_fig_plt(ax=None):
    """
    Helper function used in plot functions supporting an optional Axes argument.
    If ax is None, we build the `matplotlib` figure and create the Axes else
    we return the current active figure.

    Returns:
        ax: :class:`Axes` object
        figure: matplotlib figure
        plt: matplotlib pyplot module.
    """
    import matplotlib.pyplot as plt
    if ax is None:
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
    else:
        fig = plt.gcf()

    return ax, fig, plt

def get_ax3d_fig_plt(ax=None):
    """
    Helper function used in plot functions supporting an optional Axes3D
    argument. If ax is None, we build the `matplotlib` figure and create the
    Axes3D else we return the current active figure.

    Returns:
        ax: :class:`Axes` object
        figure: matplotlib figure
        plt: matplotlib pyplot module.
    """
    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import axes3d
    if ax is None:
        fig = plt.figure()
        ax = axes3d.Axes3D(fig)
    else:
        fig = plt.gcf()

    return ax, fig, plt

def get_axarray_fig_plt(ax_array, nrows=1, ncols=1, sharex=False, sharey=False,
                        squeeze=True, subplot_kw=None, gridspec_kw=None,
                        **fig_kw):
    """
    Helper function used in plot functions that accept an optional array of Axes
    as argument. If ax_array is None, we build the `matplotlib` figure and
    create the array of Axes by calling plt.subplots else we return the
    current active figure.

    Returns:
        ax: Array of :class:`Axes` objects
        figure: matplotlib figure
        plt: matplotlib pyplot module.
    """
    import matplotlib.pyplot as plt

    if ax_array is None:
        fig, ax_array = plt.subplots(nrows=nrows, ncols=ncols, sharex=sharex,
                                     sharey=sharey, squeeze=squeeze,
                                     subplot_kw=subplot_kw,
                                     gridspec_kw=gridspec_kw, **fig_kw)
    else:
        fig = plt.gcf()
        if squeeze:
            ax_array = np.array(ax_array).ravel()
            if len(ax_array) == 1:
                ax_array = ax_array[1]

    return ax_array, fig, plt

def add_fig_kwargs(func):
    """
    Decorator that adds keyword arguments for functions returning matplotlib
    figures.

    The function should return either a matplotlib figure or None to signal
    some sort of error/unexpected event.
    See doc string below for the list of supported options.
    """
    from functools import wraps

    @wraps(func)
    def wrapper(*args, **kwargs):
        # pop the kwds used by the decorator.
        title = kwargs.pop("title", None)
        size_kwargs = kwargs.pop("size_kwargs", None)
        show = kwargs.pop("show", True)
        savefig = kwargs.pop("savefig", None)
        tight_layout = kwargs.pop("tight_layout", False)

        # Call func and return immediately if None is returned.
        fig = func(*args, **kwargs)
        if fig is None:
            return fig

        # Operate on matplotlib figure.
        if title is not None:
            fig.suptitle(title)

        if size_kwargs is not None:
            fig.set_size_inches(size_kwargs.pop("w"), size_kwargs.pop("h"),
                                **size_kwargs)

        if savefig:
            fig.savefig(savefig)
        if tight_layout:
            fig.tight_layout()
        if show:
            import matplotlib.pyplot as plt
            plt.show()

        return fig

    # Add docstring to the decorated method.
    s = "\n" + """\
    keyword arguments controlling the display of the figure:

    ================  ====================================================
    kwargs            Meaning
    ================  ====================================================
    title             Title of the plot (Default: None).
    show              True to show the figure (default: True).
    savefig           'abc.png' or 'abc.eps' to save the figure to a file.
    size_kwargs       Dictionary with options passed to fig.set_size_inches
                      example: size_kwargs=dict(w=3, h=4)
    tight_layout      True if to call fig.tight_layout (default: False)
    ================  ===================================================="""

    if wrapper.__doc__ is not None:
        # Add s at the end of the docstring.
        wrapper.__doc__ += "\n" + s
    else:
        # Use s
        wrapper.__doc__ = s

    return wrapper


text:
package idv.chatea.gldemo;

import android.app.Activity;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import idv.chatea.gldemo.gles10.PointList;

public class GLES1_DrawElements_Activity extends Activity {

    private final String[] mDrawMode = {
            "GL_POINTS",
            "GL_LINE_STRIP",
            "GL_LINE_LOOP",
            "GL_LINES",
            "GL_TRIANGLE_STRIP",
            "GL_TRIANGLE_FAN",
            "GL_TRIANGLES",
    };

    private final int[] mModeList = {
            GL10.GL_POINTS,
            GL10.GL_LINE_STRIP,
            GL10.GL_LINE_LOOP,
            GL10.GL_LINES,
            GL10.GL_TRIANGLE_STRIP,
            GL10.GL_TRIANGLE_FAN,
            GL10.GL_TRIANGLES,
    };

    private int mCurrentMode = mModeList[0];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gles1_drawelements);

        GLSurfaceView glSurfaceView = (GLSurfaceView) findViewById(R.id.glSurfaceView);
        glSurfaceView.setEGLContextClientVersion(1);
        glSurfaceView.setRenderer(new MyRenderer());
        glSurfaceView.setRenderMode(GLSurfaceView.RENDERMODE_CONTINUOUSLY);

        Spinner renderModeSpinner = (Spinner) findViewById(R.id.renderModeSpinner);
        renderModeSpinner.setAdapter(new ArrayAdapter(this, android.R.layout.simple_spinner_item, mDrawMode));
        renderModeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                mCurrentMode = mModeList[position];
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        renderModeSpinner.setSelection(0);
    }

    private class MyRenderer implements GLSurfaceView.Renderer {

        private PointList points;

        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {

            points = new PointList();

            gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

            gl.glPointSize(10.0f);
            gl.glLineWidth(5.0f);
        }

        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            gl.glViewport(0, 0, width, height);

            float ratio = (float) width / height;
            gl.glMatrixMode(GL10.GL_PROJECTION);
            gl.glLoadIdentity();
            gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7);
        }

        @Override
        public void onDrawFrame(GL10 gl) {
            gl.glMatrixMode(GL10.GL_MODELVIEW);
            gl.glLoadIdentity();

            GLU.gluLookAt(gl, 0, 0, 5, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

            gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

            points.draw(gl, mCurrentMode);
        }
    }
}


text:
<?php
namespace Embed\Providers\OEmbed;

class DotSub extends \Embed\Providers\OEmbedImplementationAbstract
{
	/**
	 * {@inheritDoc}
	 */
    public static function getEndPoint()
    {
        return 'http://dotsub.com/services/oembed';
    }

    /**
	 * {@inheritDoc}
	 */
    public static function getPatterns()
    {
        return array('https?://dotsub.com/view/*');
    }
}


text:
from django.contrib.admin import (
    autodiscover, site, AdminSite, ModelAdmin, StackedInline, TabularInline,
    HORIZONTAL, VERTICAL,
)
# Geographic admin options classes and widgets.
from django.contrib.gis.admin.options import GeoModelAdmin, OSMGeoAdmin
from django.contrib.gis.admin.widgets import OpenLayersWidget

__all__ = [
    'autodiscover', 'site', 'AdminSite', 'ModelAdmin', 'StackedInline',
    'TabularInline', 'HORIZONTAL', 'VERTICAL', 'GeoModelAdmin', 'OSMGeoAdmin',
    'OpenLayersWidget',
]


text:
import PlaybackControls from '../../playback-controls';

export default {
  component: PlaybackControls,
  layoutFor: 'binarySearch',

  props: {
    isPlaying: true,
    pos: 300,
    maxPos: 1229,
    onPlay: () => console.log('play'),
    onPause: () => console.log('pause'),
    onScrollTo: to => console.log('scroll', to)
  }
};


text:
influxdb-scala
==============
# Latest Scala client can be found here: https://github.com/influxdata/influxdb-client-java/tree/master/client-scala

# This library is not updated for InfluxDB 0.9. There are breaking changes to the API, use at your own risk.

We encourage you to submit a pull request if you have a contribution. If you make a PR please explicitly call @beckettsean to get eyes on your PR.

---------

Scala client for InfluxDB heavily inspired by [influxdb-go](https://github.com/influxdb/influxdb-go).


text:
This is my pet project writing ansible playbooks. If you like my work please share your feedback.

## Index
+ AWS
    - assign-eip
    - create-ec2-key
    - [create-iam-admin-group](https://github.com/adithyakhamithkar/ansible/blob/master/AWS/roles/create-iam-admin-group)
    - [create-iam-group](https://github.com/adithyakhamithkar/ansible/blob/master/AWS/roles/create-iam-group)
    - [create-iam-policy](https://github.com/adithyakhamithkar/ansible/blob/master/AWS/roles/create-iam-policy)
    - [create-iam-read-only-group](https://github.com/adithyakhamithkar/ansible/blob/master/AWS/roles/create-iam-read-only-group)
    - create-iam-role
    - [create-iam-user](https://github.com/adithyakhamithkar/ansible/blob/master/AWS/roles/create-iam-user)
    - create-sg-db
    - create-sg-web
    - create-vpc
    - launch-ec2
    - start-ec2
    - stop-ec2
+ MySql
    - mysql-create-db
    - mysql-create-user
    - mysql-dump
    - mysql-import
    - transfer-db
+ Hacking
    - [john-the-ripper](https://github.com/adithyakhamithkar/ansible/blob/master/Hacking/roles/john-the-ripper)
+ List of Roles
    - [agar](https://github.com/adithyakhamithkar/ansible/blob/master/roles/agar)
    - [ansible](https://github.com/adithyakhamithkar/ansible/blob/master/roles/ansible)
    - beef
    - bitcoin (WIP)
    - bittorrentsync
    - build-docker-image
    - cachethq (Not working)
    - [cassandra](https://github.com/adithyakhamithkar/ansible/blob/master/roles/cassandra)
    - common
    - create-user
    - datadog-agent
    - deployment-nginx
    - deployment-phpmyadmin
    - docker
    - docker-clean
    + [elasticsearch](https://github.com/adithyakhamithkar/ansible-playbooks/blob/master/roles/elasticsearch/README.md)
        - elasticsearch-data
        - elasticsearch-master
    - epoch
    - fail2ban
    - filebeat
    - galera
    - gitlab
    - glassfish
    - gradle
    - grafana-server
    - hadoop
    - hostname
    - ipa-client
    - ipa-server
    - jdk
    - jenkins
        - jenkins-configure
    - [kafka](https://github.com/adithyakhamithkar/ansible/blob/master/roles/kafka)
        - [kafka-manager](https://github.com/adithyakhamithkar/ansible/tree/master/roles/kafka-manager)
    - kibana
    - kubernetes
    - ldap-server
    - lets-encrypt
    - logstash
    - [mesos](https://github.com/adithyakhamithkar/ansible/blob/master/roles/mesos)
        - mesos-master
        - mesos-slave
    - mongodb
    - motd
    - mysql
    - newrelic
        - new-relic-java-agent (WIP)
        - new-relic-php-agent
        - new-relic-server-agent
    - nexus
    - nginx (Configured to support http 2.0)
        - nginx-jenkins
        - nginx-load-balancer
        - nginx-sensu-master
    - nodejs
    - [ntp](https://github.com/adithyakhamithkar/ansible/tree/master/roles/ntp)
    - odoo
    + [ossec](https://github.com/adithyakhamithkar/ansible/blob/master/roles/ossec-server)
        - ossec-server
        - ossec-agent
    - packer
    - [phabricator](https://github.com/adithyakhamithkar/ansible/blob/master/roles/phabricator)
    - php
    - php7
    - [postfix](https://github.com/adithyakhamithkar/ansible/tree/master/roles/postfix)
    - psad
    - rabbit-mq
    - rancher
    - redis
    - roles-template
    - rootkit-scanners
        - chkrootkit
        - rkhunter
    - [s3fs](https://github.com/adithyakhamithkar/ansible/blob/master/roles/s3fs)
    - [saltstack](https://github.com/adithyakhamithkar/ansible/tree/master/roles/salt-master)
        - salt-master
        - salt-minion
    - scala
    - sensu
        - sensu-client
        - sensu-client-checks
        - sensu-master
    - solr
    - ssh-banner
    - ssh-keys
    - teamcity
    - tiger
    - tomcat
    - varnish
    - youtrack
    - [zookeeper](https://github.com/adithyakhamithkar/ansible/blob/master/roles/zookeeper)


text:
package dblentry

import "regexp"

type Payee struct {
	name      string
	aliases   []string // regular expression that can match transactions.
	realiases []*regexp.Regexp
	uuids     []string
}

func NewPayee(name string) *Payee {
	return &Payee{
		name:      name,
		aliases:   []string{},
		realiases: []*regexp.Regexp{},
		uuids:     []string{},
	}
}

func (payee *Payee) addAlias(pattern string) error {
	if pattern == "" {
		return nil
	}
	payee.aliases = append(payee.aliases, pattern)
	regc, err := regexp.Compile(pattern)
	if err != nil {
		return err
	}
	payee.realiases = append(payee.realiases, regc)
	return nil
}

func (payee *Payee) addUuid(uuid string) {
	if uuid == "" {
		return
	}
	payee.uuids = append(payee.uuids, uuid)
}

func (payee *Payee) matchAlias(alias string) (string, bool) {
	for _, regc := range payee.realiases {
		if regc.MatchString(alias) {
			return payee.name, true
		}
	}
	return "", false
}

func (payee *Payee) matchUuid(uuid string) (string, bool) {
	for _, xuuid := range payee.uuids {
		if xuuid == uuid {
			return payee.name, true
		}
	}
	return "", false
}


text:
{% extends "base.html" %}
{% load staticfiles %}

{% block title %}CodeCarrots Challenge{% endblock title %}

{% block body_class %}home{% endblock body_class %}

{% block body %}

CodeCarrots Challenge!

Zmierz się z zestawem przygotowanych na dzisiaj zadań programistycznych - zobacz ile dasz radę rozwiązać!

        {% if user.is_authenticated %}

Przejdź do zadań »

        {% else %}

Zarejestruj lub zaloguj się aby uzyskać dostęp do zadań.

        {% endif %}

{% endblock body %}


text:
import React, { Component } from 'react';
import {
    View,
    Animated,
    PanResponder,
    Dimensions,
    LayoutAnimation,
    UIManager,
    Platform
} from 'react-native';
import _ from 'lodash'
const SCREEN_WIDTH = Dimensions.get('window').width;
const SWIPE_THRESHOLD = 0.09 * SCREEN_WIDTH;
const SWIPE_OUT_DURATION = 250;

class Swipe extends Component {
    static defaultProps = {
        onSwipeRight: () => {},
        onSwipeLeft: () => {},
        keyProp: 'id'
    };

    constructor(props) {
        super(props);

        const position = new Animated.ValueXY();
        const panResponder = PanResponder.create({
            onStartShouldSetPanResponder: () => true,
            onPanResponderMove: (event, gesture) => {
                position.setValue({ x: gesture.dx, y: 0 });
            },
            onPanResponderRelease: (event, gesture) => {
                if (gesture.dx > SWIPE_THRESHOLD) {
                    this.forceSwipe('right');
                } else if (gesture.dx < -SWIPE_THRESHOLD) {
                    this.forceSwipe('left');
                } else {
                    this.resetPosition();
                }
            }
        });

        this.state = { panResponder, position, index: 0 };
    }

    componentWillReceiveProps(nextProps) {
        if (nextProps.data !== this.props.data) {
            this.setState({ index: 0 });
        }
    }

    componentWillUpdate() {
        UIManager.setLayoutAnimationEnabledExperimental && UIManager.setLayoutAnimationEnabledExperimental(true);
    }

    forceSwipe(direction) {
        const x = direction === 'right' ? SCREEN_WIDTH : -SCREEN_WIDTH;
        Animated.timing(this.state.position, {
            toValue: { x, y: 0 },
            duration: SWIPE_OUT_DURATION
        }).start(() => this.onSwipeComplete(direction));
    }

    onSwipeComplete(direction) {
        const { onSwipeLeft, onSwipeRight, data } = this.props;
        const item = data[this.state.index];

        direction === 'right' ? onSwipeRight(item) : onSwipeLeft(item);
        this.state.position.setValue({ x: 0, y: 0 });
        this.setState({ index: this.state.index + 1 });
    }

    resetPosition() {
        Animated.spring(this.state.position, {
            toValue: { x: 0, y: 0 }
        }).start();
    }

    getCardStyle() {
        const { position } = this.state;
        const rotate = position.x.interpolate({
            inputRange: [-SCREEN_WIDTH * 1.5, 0, SCREEN_WIDTH * 1.5],
            outputRange: ['-90deg', '0deg', '90deg']
        });

        return {
            ...position.getLayout(),
            transform: [{ rotate }]
        };
    }

    renderCards() {
        if (this.state.index >= this.props.data.length) {
            return this.props.renderNoMoreCards();
        }

        const deck = this.props.data.map((item, i) => {
            if (i < this.state.index) { return null; }

            if (i === this.state.index) {
                return (
                    <Animated.View
                        key={item[this.props.keyProp]}
                        style={[this.getCardStyle(), styles.cardStyle, { zIndex: 99 }]}
                        {...this.state.panResponder.panHandlers}
                    >

                        {this.props.renderCard(item)}
                    </Animated.View>
                );
            }

        });

        return Platform.OS === 'android' ? deck : deck.reverse();
    }

    render() {
        return (
            <View>
                {this.renderCards()}
            </View>
        );
    }
}

const styles = {
    cardStyle: {
        width: SCREEN_WIDTH,
        height: Dimensions.get('window').height
    }
};

export default Swipe;


text:
import java.util.Map;

public abstract class ScopedSymbol extends Symbol implements Scope {
    Scope enclosingScope;

    public ScopedSymbol(String name, Scope enclosingScope) {
        super(name);
        this.enclosingScope = enclosingScope;
    }

    public Symbol resolve(String name) {
        Symbol s = getMembers().get(name);
        if ( s!=null ) return s;
        // if not here, check any parent scope
        if ( getParentScope() != null ) {
            return getParentScope().resolve(name);
        }
        return null; // not found
    }

    public void define(Symbol sym) {
        getMembers().put(sym.name, sym);
        sym.scope = this; // track the scope in each symbol
    }

    public Scope getParentScope() { return getEnclosingScope(); }
    public Scope getEnclosingScope() { return enclosingScope; }

    public String getScopeName() { return name; }

    /** Indicate how subclasses store scope members. Allows us to
     *  factor out common code in this class.
     */
    public abstract Map<String, Symbol> getMembers();
}


text:
package gae.pointage;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.Image;
import android.os.CountDownTimer;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import gae.pointage.bdd.Equipe;
import gae.pointage.bdd.Infraction;
import gae.pointage.bdd.Joueur;
import gae.pointage.bdd.Partie;
import gae.pointage.bdd.Penalite;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class main extends AppCompatActivity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;
    private final Handler mHideHandler = new Handler();
    private View mContentView;
    private ListView listviewEquipe1, listviewEquipe2;
    private JoueurAdapter joueurAdapterEquipe1, joueurAdapterEquipe2;
    private static final String FORMAT = "%02d:%02d";
    private TextView chronoTexte;
    private Equipe equipe1, equipe2;
    private TextView nomEquipe1, nomEquipe2;
    private TextView textViewPeriode;
    private ImageButton boutonPlayPause;
    public Chrono chrono;
    private Joueur[] assists = {null, null};
    public List<Penalite> penalitesEnCours = new LinkedList<>();
    private TextView pointageTexteEquipe1, pointageTexteEquipe2;
    private int pointageEquipe1 = 0, pointageEquipe2 = 0;
    public Partie partie = new Partie();
    private SharedPreferences sharedPreferences;

    public static final int TEMPS_PERIODE = 1200000;

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)
            // and API 19 (KitKat). It is safe to use them, as they are inlined
            // at compile-time and do nothing on earlier devices.
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };
    private View mControlsView;
    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
            mControlsView.setVisibility(View.VISIBLE);
        }
    };
    private boolean mVisible;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        this.sharedPreferences = this.getSharedPreferences("Pointage", 0);

        mVisible = true;
        this.chronoTexte = (TextView) findViewById(R.id.chrono);
        this.textViewPeriode = (TextView) findViewById(R.id.textview_numero_periode);
        this.boutonPlayPause = (ImageButton) findViewById(R.id.play_pause);
        this.equipe1 = (Equipe) Equipe.find(Equipe.class, "nom=?", this.sharedPreferences.getString("NomEquipeLocale", "")).get(0);
        this.equipe2 = (Equipe) Equipe.find(Equipe.class, "nom=?", this.sharedPreferences.getString("NomEquipeVisiteur", "")).get(0);

        this.nomEquipe1 = (TextView) findViewById(R.id.textview_nom_equipe_1);
        this.nomEquipe2 = (TextView) findViewById(R.id.textview_nom_equipe_2);
        this.nomEquipe1.setText(this.equipe1.getNom());
        this.nomEquipe2.setText(this.equipe2.getNom());

        this.pointageTexteEquipe1 = (TextView)findViewById(R.id.textview_pointage_equipe_1);
        this.pointageTexteEquipe2 = (TextView)findViewById(R.id.textview_pointage_equipe_2);

        this.pointageTexteEquipe1.setText(String.valueOf(this.pointageEquipe1));
        this.pointageTexteEquipe2.setText(String.valueOf(this.pointageEquipe2));

        this.joueurAdapterEquipe1 = new JoueurAdapter(this, equipe1.getJoueurs(), R.layout.joueur_element_listview_inverse);
        this.joueurAdapterEquipe2 = new JoueurAdapter(this, equipe2.getJoueurs(), R.layout.joueur_element_listview);

        this.listviewEquipe1 = (ListView)findViewById(R.id.listview_equipe_1);
        this.listviewEquipe1.setAdapter(this.joueurAdapterEquipe1);

        this.listviewEquipe2 = (ListView)findViewById(R.id.listview_equipe_2);
        this.listviewEquipe2.setAdapter(this.joueurAdapterEquipe2);

        this.chrono = new Chrono(main.TEMPS_PERIODE){
            @Override
            public void onTick() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        chronoTexte.setText(chrono.getTempsRestantFormate());
                        textViewPeriode.setText(String.valueOf(chrono.periode));
                        joueurAdapterEquipe1.notifyDataSetChanged();
                        joueurAdapterEquipe2.notifyDataSetChanged();
                    }
                });
            }
        };

        ImageButton button = (ImageButton) findViewById(R.id.play_pause);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               if(!chrono.estEnMarche()){
                   System.out.println("Bouton Play appuyé.");
                   playChrono();
               }else{
                   System.out.println("Bouton Pause appuyé.");
                   pauseChrono();
               }
            }
        });
    }

    @Override
    protected void onStop() {
        this.penalitesEnCours.clear();
    }

    private void playChrono(){
        boutonPlayPause.setImageResource(R.drawable.pause);
        chrono.commencer();
    }

    private void pauseChrono(){
        if (this.chrono.estEnMarche()){
            this.boutonPlayPause.setImageResource(R.drawable.play);
            this.chrono.pause();
        }
    }

    public void retirerPenalite(Penalite penalite){
        this.penalitesEnCours.remove(penalite);
        System.out.println("hahaha");
    }

    public void penalite(Joueur joueur){
        pauseChrono();

        long nombreInfractions = Infraction.count(Infraction.class);
        CharSequence[] infractions = new CharSequence[(int) nombreInfractions];

        int i = 0;
        for(Infraction infraction : Infraction.listAll(Infraction.class)) {
            infractions[i] = infraction.getNom();
            i++;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final Joueur joueurFinal = joueur;
        builder.setTitle("Choisissez l'infraction");
        builder.setItems(infractions, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                int temps = chrono.tempsPasse - ((chrono.periode - 1) * TEMPS_PERIODE);
                Penalite penalite = BDD.ajouterPenalite(partie, Infraction.listAll(Infraction.class).get(which), joueurFinal.getEquipe(),
                        joueurFinal, temps, chrono.periode);
                penalitesEnCours.add(penalite);
                joueurAdapterEquipe1.notifyDataSetChanged();
                joueurAdapterEquipe2.notifyDataSetChanged();
            }
        });
        builder.show();

        System.out.println("Bouuuhhhh: " + joueur.getNom() + " avec: " + String.valueOf(this.penalitesEnCours.size()));
    }

    public void assist(Joueur joueur){
        pauseChrono();
        System.out.println("Cet assist provient de " + joueur.getNom());
    }

    public void ajouterAssist(Joueur joueur) {
        this.assists[1] = this.assists[0];
        this.assists[0] = joueur;
    }

    public void retirerAssist(Joueur joueur) {
        if (this.assists[0] == joueur) {
            this.assists[0] = this.assists[1];
        }
        this.assists[1] = null;
    }

    public void viderAssists() {
        this.assists[0] = null;
        this.assists[1] = null;
    }

    public void but(Joueur joueur) {
        pauseChrono();
        System.out.println("Ce but vous est présenté par: " + joueur.getNom());
        Joueur[] assistsCopie = this.assists.clone();
        this.viderAssists();
        BDD.ajouterBut(this.partie, joueur, this.assists[1], this.assists[0], this.chrono.tempsPasse, this.chrono.periode);
        if (this.equipe1.getId() == joueur.getEquipe().getId()) {
            this.pointageEquipe1 += 1;
            this.pointageTexteEquipe1.setText(String.valueOf(this.pointageEquipe1));
        } else {
            this.pointageEquipe2 += 1;
            this.pointageTexteEquipe2.setText(String.valueOf(this.pointageEquipe2));
        }
        System.out.println("Ce but vous est présenté par: " + joueur.getNom());
    }

    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mControlsView.setVisibility(View.GONE);
        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay
        mHideHandler.removeCallbacks(mShowPart2Runnable);
    }

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        mVisible = true;

        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable);
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }
}


text:
test.test_csvtools module
=========================

.. automodule:: test.test_csvtools
    :members:
    :undoc-members:
    :show-inheritance:


text:
import { compileToFunctions } from 'vue-template-compiler'
import Vue from 'vue'
import shallow from '~src/shallow'
import mount from '~src/mount'
import VueWrapper from '~src/wrappers/vue-wrapper'
import Component from '~resources/components/component.vue'
import ComponentWithChild from '~resources/components/component-with-child.vue'
import ComponentWithNestedChildren from '~resources/components/component-with-nested-children.vue'
import ComponentWithLifecycleHooks from '~resources/components/component-with-lifecycle-hooks.vue'

describe('shallow', () => {
  let info

  beforeEach(() => {
    info = sinon.stub(console, 'info')
  })

  afterEach(() => {
    info.restore()
  })

  it('returns new VueWrapper of Vue localVue if no options are passed', () => {
    const compiled = compileToFunctions('
<input />
')
    const wrapper = shallow(compiled)
    expect(wrapper).to.be.instanceOf(VueWrapper)
    expect(wrapper.vm).to.be.an('object')
  })

  it('returns new VueWrapper of Vue localVue with all children stubbed', () => {
    const wrapper = shallow(ComponentWithNestedChildren)
    expect(wrapper).to.be.instanceOf(VueWrapper)
    expect(wrapper.findAll(Component).length).to.equal(0)
    expect(wrapper.findAll(ComponentWithChild).length).to.equal(1)
  })

  it('returns new VueWrapper of Vue localVue with all children stubbed', () => {
    const wrapper = shallow(ComponentWithNestedChildren)
    expect(wrapper).to.be.instanceOf(VueWrapper)
    expect(wrapper.findAll(Component).length).to.equal(0)
    expect(wrapper.findAll(ComponentWithChild).length).to.equal(1)
  })

  it('does not modify component directly', () => {
    const wrapper = shallow(ComponentWithNestedChildren)
    expect(wrapper.findAll(Component).length).to.equal(0)
    const mountedWrapper = mount(ComponentWithNestedChildren)
    expect(mountedWrapper.findAll(Component).length).to.equal(1)
  })

  it('stubs globally registered components when options.localVue is provided', () => {
    const localVue = Vue.extend()
    localVue.component('registered-component', ComponentWithLifecycleHooks)
    const Component = {
      render: h => h('registered-component')
    }
    shallow(Component, { localVue })
    mount(Component, { localVue })

    expect(info.callCount).to.equal(4)
  })

  it('stubs globally registered components', () => {
    Vue.component('registered-component', ComponentWithLifecycleHooks)
    const Component = {
      render: h => h('registered-component')
    }
    shallow(Component)
    mount(Component)

    expect(info.callCount).to.equal(4)
  })

  it('does not call stubbed children lifecycle hooks', () => {
    shallow(ComponentWithNestedChildren)
    expect(info.called).to.equal(false)
  })
})


text:
This directory contains 3 examples of learning the XOR function with TensorFlow. The most basic solution [xor.py](xor.py) solves the problem using mean squared error as the loss function. [xor_summaries.py](xor_summaries.py) adds additional `summary` operations, for use with TensorBoard, the TensorFlow debugging UI. Output summaries include heatmaps of parameters at the last iteration of training. Loss and accuracy, throughout, as well as histograms of gradients, and an architecture diagram. Finally, [xor_summaries_softmax.py](xor_summaries_softmax.py) substitutes a more traditional cross-entropy loss function using softmax.

### Running locally

To run locally, first choose either:

1. a Google Cloud Storage location you have write access to.
2. A *prexisting* local directory.

```
python -m xor.xor_summaries --output-dir ${OUTPUT_DIR}
```

or if you want to try using the `gcloud ml-engine local train` command, the following will work:

```
gcloud ml-engine local train \
    --package-path xor \
    --module-name xor.xor_summaries \
    -- \
    --output-dir ${OUTPUT_DIR}
```

The `gcloud ml-engine local train` command runs your python code locally in an environment that emulates that of the Google Cloud Machine Learning API. This is primarily useful for distributed execution, where the local tool can serve as validation, that your code will run properly.

### Running in the Cloud

To run in the cloud you need a Google Cloud Storage bucket to which summaries can be written. You will also need a bucket where the `gcloud` tool can stage your code for execution e.g. `MY_BUCKET=gs://my-bucket`. This can be the same bucket to which you write summaries.

```
gcloud ml-engine jobs submit training myxorjob \
     --module-name xor.xor_summaries \
     --package-path xor \
     --staging-bucket ${MY_BUCKET} \
     -- \
     --output-dir ${OUTPUT_DIR}
```

The service may take some time to start up. Make sure you have authorized the Cloud Machine Learning service account to access your bucket, as described in the installation instructions.

### Using TensorBoard to view summaries

TensorBoard is the web UI which reads binary summary files written by TensorFlow training jobs, and renders them as graphics. TensorBoard ships with TensorFlow and so should be installed in your local environment. Run TensorBoard with:

```
tensorboard --logdir ${OUTPUT_DIR}
```

And it will read from both local and GCS directories. TensorBoard also recursively searches subdirectories of `--logdir` and renders each events file on the same graph allowing you to compare multiple runs of a training job, or different metrics from the same training job.


text:
int main(int argc, char **argv)
{
	IplImage *img = cvLoadImage(argv[1], CV_LOAD_IMAGE_COLOR);
	cvNamedWindow("Image_Show", CV_WINDOW_AUTOSIZE);
	cvShowImage("Image_Show", img);
	// cvReleaseImage(&img);
	// cvDestroyWindow("Image_Show");
	cvWaitKey(10);
	printf("Ha?\n");
	char c = getchar();
	return 0;
}


text:
FROM ruby:2.6-buster

# Install FreeTDS, a dependency of the tiny_tds Ruby connector
RUN apt-get update && apt-get --assume-yes install freetds-dev freetds-bin

# Set the working directory
WORKDIR /app

# Copy application dependency manifests to the container image.
# Copying this separately prevents re-running bundle install on every code change.
COPY Gemfile Gemfile.lock ./
ENV BUNDLE_FROZEN=true
RUN bundle install

# Copy local code to the container image.
COPY . ./

EXPOSE 8080

# Run the app on container startup.
CMD bundle exec rackup --port 8080 -o 0.0.0.0


text:
'use strict';

import { Component }        from '@angular/core';

@Component({
  templateUrl: './page2.html',
})

export class Page2 {

  public title: string = 'Page 2';

  public onGainChange(): void {
    return;
  }
}


text:
<?php

use yii\helpers\Html;
use yii\grid\GridView;

use app\models\general\GeneralLabel;
use app\models\general\GeneralMessage;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\TempahanKursusPersatuanSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = GeneralLabel::tempahan_kursus_persatuan;
$this->params['breadcrumbs'][] = $this->title;
?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>

        <?= Html::a('Tambah Tempahan Kursus Persatuan', ['create'], ['class' => 'btn btn-success']) ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],

            //'tempahan_kursus_persatuan_id',
            //'kursus_persatuan_id',
            [
                'attribute' => 'tarikh',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::tarikh,
                ]
            ],
            [
                'attribute' => 'jenis_tempahan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::jenis_tempahan,
                ]
            ],
            [
                'attribute' => 'unit_tempahan',
                'filterInputOptions' => [
                    'class'       => 'form-control',
                    'placeholder' => GeneralLabel::filter.' '.GeneralLabel::unit_tempahan,
                ]
            ],
            // 'kos_tempahan',

            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>


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

namespace Alicization.Model.Wealth.Assets
{
    class Equipment
    {
    }
}


text:
package org.usfirst.frc.team166.robot.commands.lifts;

import edu.wpi.first.wpilibj.command.Command;

import org.usfirst.frc.team166.robot.Robot;

/**
 *
 */
public class RaiseRCLift extends Command {

	public RaiseRCLift() {
		requires(Robot.rcLift);
	}

	// Called just before this Command runs the first time
	@Override
	protected void initialize() {
		Robot.rcLift.moveUp();
	}

	// Called repeatedly when this Command is scheduled to run
	@Override
	protected void execute() {
		Robot.rcLift.updatePIDSetpoint(-1);
		Robot.rcLift.printEncoderValues();
	}

	// Make this return true when this Command no longer needs to run execute()
	@Override
	protected boolean isFinished() {
		return Robot.rcLift.isBoundaryHit();
	}

	// Called once after isFinished returns true
	@Override
	protected void end() {
		Robot.rcLift.stop();
		Robot.rcLift.resetEncoder();
		Robot.rcLift.updatePIDSetpoint(0);
	}

	// Called when another command which requires one or more of the same
	// subsystems is scheduled to run
	@Override
	protected void interrupted() {
		Robot.rcLift.stop();
		Robot.rcLift.resetEncoder();
	}
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Tabs | Framework7 Documentation</title>
    <meta property="og:image" content="http://framework7.io/i/f7-banner.jpg">
    <link rel="stylesheet" href="//cdn.framework7.io/css/normalize.css">
    <link rel="stylesheet" href="//cdn.framework7.io/css/highlight.css">
    <link rel="stylesheet" href="//cdn.framework7.io/css/main.css">
    <link rel="shortcut icon" href="/favicon.png">

Language: ENCN

Framework7

Project:

DownloadContributeDonateChangelog

Learn:

Get StartedDocsTutorialsForum

Apps:

LayoutsPluginsDemo AppsShowcase

 stars forks

Core

Dom7 - Custom DOM Library

App HTML Layout

RTL Layout

Initialize App / App parameters

Views

Pages

Page Callbacks

Navigation / Router

API

Ajax Pages

Dynamic Pages

Inline Pages (DOM Cache)

Linking Between Views

Components

Navbars & Toolbars

Layout types

Navbar

Dynamic Navbar

Sub Navbar

Toolbar

Tab Bar

Hide Bars On Scroll

Search Bar

Status Bar overlay

Side Panels

Content Block

Layout Grid

Overlays

Modal

Popup

Popover

Action Sheet

Login Screen

Picker Modal

Preloader Indicator

Progress Bar

List View (Table View)

List View

Contacts List

Media List View

Swipeout

Sortable List

Virtual List

Accordion / Collapsible

Cards

Chips

Buttons

Floating Action Button

Forms

Form Elements

Checkboxes and Radios

Smart Select

Disabled Elements

Form Data

Form Storage

Ajax Form Submit

Tabs

Swiper Slider

Photo Browser

Autocomplete

Picker

Calendar / Datepicker

Pull to Refresh

Infinite Scroll

Messages

Message Bar

Notifications

Lazy Load

Styling

Color Themes

Hairlines

Template7

Getting Started

Templates Auto Compilation

Template7 Pages

Fast Clicks

Active State

Tap Hold Event (Long Tap)

Touch Ripple (Material)

Utilities

Device API

Support API

Plugins API

Plugins API

Custom Build

Custom Build

Tabs

Tabs allow to simply switch between different content.

Tabs Layout

Let's look at Tabs layout:

<!-- Tabs wrapper, shoud have "tabs" class. Required element -->
<div class="tabs">
  <!-- First tab, should have "tab" class and unique id attribute -->
  <!-- First tab is active by default - additional "active" class -->
  <div class="tab active" id="tab1">
    ... Tab 1 content goes here ...
  </div>
  <!-- Second tab, should have "tab" class and unique id attribute -->
  <div class="tab" id="tab2">
    ... Tab 2 content goes here ...
  </div>
  <!-- Third tab, should have "tab" class and unique id attribute -->
  <div class="tab" id="tab3">
    ... Tab 3 content goes here ...
  </div>
</div>

Where:

div class="tabs" - required wrapper for all tabs. If you miss this elements, tabs will now work

div class="tab" - single tab. Should have unique id attribute

div class="tab active" - single active tab. Tab which is active (visible) by default, should have additional "active" class

Switching between tabs

After we have our tabs layout we need some contoller so user can switch between them.

To make it work we need to create links (<a> tags) with "tab-link" class and href attribute equal to the id attribute of target tab:

<!-- Link that activates first tab, has the same href attribute (#tab1) as the id attribute of first tab (tab1)  -->
<a href="#tab1" class="tab-link active">Tab 1</a>

<!-- Link that activates 2nd tab, has the same href attribute (#tab2) as the id attribute of 2nd tab (tab2)  -->
<a href="#tab2" class="tab-link">Tab 2</a>

<!-- Link that activates 3rd tab, has the same href attribute (#tab2) as the id attribute of 3rd tab (tab3)  -->
<a href="#tab3" class="tab-link">Tab 3</a>

As you may see, first link also has "active" class. It is not required, but if all this links will be on the same DOM tree level (the same-level children of mutual parent), then script will also change this "active" class on link related to active tab. It is useful when your "active" link has different visual style (like buttons Buttons Row / Segmented Control or links in Tab bar)

Switch multiple tabs

Such notation as above uses ID attributes to specify tabs we need to switch to. But sometimes we may have situation when we need to switch few tabs using one tab-link, for this case we may use classes instead of IDs and "data-tab" attribute for tab-link. For example:

<!-- Top Tabs -->
<div class="tabs tabs-top">
  <div class="tab tab1 active">...</div>
  <div class="tab tab2">...</div>
  <div class="tab tab3">...</div>
</div>
<!-- Bottom Tabs -->
<div class="tabs tabs-bottom">
  <div class="tab tab1 active">...</div>
  <div class="tab tab2">...</div>
  <div class="tab tab3">...</div>
</div>
<!-- Tabs links -->
<div class="tab-links">
  <!-- This links will switch top and bottom tabs to .tab1 -->
  <a href="#" class="tab-link" data-tab=".tab1">Tab 1</a>
  <!-- This links will switch top and bottom tabs to .tab2 -->
  <a href="#" class="tab-link" data-tab=".tab2">Tab 2</a>
  <!-- This links will switch top and bottom tabs to .tab3 -->
  <a href="#" class="tab-link" data-tab=".tab3">Tab 3</a>
</div>

Where data-tab attribute of tab-link contains CSS selector of target tab/tabs

Inline Tabs example

<div class="page-content">
  <div class="content-block">
    <!-- Buttons row as tabs controller -->
    <div class="buttons-row">
      <!-- Link to 1st tab, active -->
      <a href="#tab1" class="tab-link active button">Tab 1</a>
      <!-- Link to 2nd tab -->
      <a href="#tab2" class="tab-link button">Tab 2</a>
      <!-- Link to 3rd tab -->
      <a href="#tab3" class="tab-link button">Tab 3</a>
    </div>
  </div>
  <!-- Tabs, tabs wrapper -->
  <div class="tabs">
    <!-- Tab 1, active by default -->
    <div id="tab1" class="tab active">
      <div class="content-block">
        <p>This is tab 1 content</p>
        ...
      </div>
    </div>
    <!-- Tab 2 -->
    <div id="tab2" class="tab">
      <div class="content-block">
        <p>This is tab 2 content</p>
        ...
      </div>
    </div>
    <!-- Tab 3 -->
    <div id="tab3" class="tab">
      <div class="content-block">
        <p>This is tab 3 content</p>
        ...
      </div>
    </div>
  </div>
</div>

Switch tabs from Navbar example

<div class="navbar">
  <div class="navbar-inner">
    <div class="center">
      <!-- Buttons row as tabs controller in navbar-->
      <div class="buttons-row">
        <!-- Link to 1st tab, active -->
        <a href="#tab1" class="tab-link active button">Tab 1</a>
        <!-- Link to 2nd tab -->
        <a href="#tab2" class="tab-link button">Tab 2</a>
        <!-- Link to 3rd tab -->
        <a href="#tab3" class="tab-link button">Tab 3</a>
      </div>
    </div>
  </div>
</div>
<div class="pages">
  <div class="page">
    <!-- Tabs, tabs wrapper, pate-content are tabs now -->
    <div class="page-content tabs">
      <!-- Tab 1, active by default -->
      <div id="tab1" class="tab active">
        <div class="content-block">
          <p>This is tab 1 content</p>
          ...
        </div>
      </div>
      <!-- Tab 2 -->
      <div id="tab2" class="tab">
        <div class="content-block">
          <p>This is tab 2 content</p>
          ...
        </div>
      </div>
      <!-- Tab 3 -->
      <div id="tab3" class="tab">
        <div class="content-block">
          <p>This is tab 3 content</p>
          ...
        </div>
      </div>
    </div>
  </div>
</div>

Switch views from Tab bar example

Why single Tab could not be a seprate View with its own navigation and layout? It can, so you can just switch Views as tabs:

<!-- Tabs, now tabs wrapper is "views" -->
<div class="views tabs toolbar-fixed">
  <!-- Tab 1 - View 1, active by default -->
  <div id="tab1" class="view tab active">
    <div class="navbar">
      <div class="navbar-inner">
        <div class="center">View 1</div>
      </div>
    </div>
    <div class="pages navbar-fixed">
      <div data-page="home-1" class="page">
        <div class="page-content">
          <div class="content-block">
            <p>This is view 1</p>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- Tab 2 - View 2 -->
  <div id="tab2" class="view tab">
    <div class="navbar">
      <div class="navbar-inner">
        <div class="center">View 2</div>
      </div>
    </div>
    <div class="pages navbar-fixed">
      <div data-page="home-2" class="page">
        <div class="page-content">
          <div class="content-block">
            <p>This is view 2</p>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- Tab 2 - View 3 -->
  <div id="tab3" class="view tab">
    <div class="navbar">
      <div class="navbar-inner">
        <div class="center">View 3</div>
      </div>
    </div>
    <div class="pages navbar-fixed">
      <div data-page="home-3" class="page">
        <div class="page-content">
          <div class="content-block">
            <p>This is view 3</p>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- Tab bar with tab links -->
  <div class="toolbar tabbar">
    <div class="toolbar-inner">
      <a href="#tab1" class="tab-link active"><i class="icon demo-icon-1"></i></a>
      <a href="#tab2" class="tab-link"><i class="icon demo-icon-2"></i></a>
      <a href="#tab3" class="tab-link"><i class="icon demo-icon-3"></i></a>
    </div>
  </div>
</div>

Animated Tabs

It is also possible to switch tabs with simple transition. This requires additional div class="tabs-animated-wrap" wrapper for div class="tabs":

<div class="navbar">
  <div class="navbar-inner">
    <div class="center">
      <!-- Buttons row as tabs controller in navbar-->
      <div class="buttons-row">
        <!-- Link to 1st tab, active -->
        <a href="#tab1" class="tab-link active button">Tab 1</a>
        <!-- Link to 2nd tab -->
        <a href="#tab2" class="tab-link button">Tab 2</a>
        <!-- Link to 3rd tab -->
        <a href="#tab3" class="tab-link button">Tab 3</a>
      </div>
    </div>
  </div>
</div>
<div class="pages">
  <div class="page">
    <div class="page-content">
      <!-- Tabs animated wrapper, required to switch tabs with transition -->
      <div class="tabs-animated-wrap">

        <!-- Tabs, tabs wrapper -->
        <div class="tabs">
          <!-- Tab 1, active by default -->
          <div id="tab1" class="tab active">
            ... Tab 1 content ...
          </div>

          <!-- Tab 2 -->
          <div id="tab2" class="tab">
            ... Tab 2 content ...
          </div>

          <!-- Tab 3 -->
          <div id="tab3" class="tab">
            ... Tab 3 content ...
          </div>
        </div>

      </div>
    </div>
  </div>
</div>

Note that animted tabs wrapper (div class="tabs-animated-wrap") should be a fixed height. By default, it is 100% height of its parent

Swipeable Tabs

It is also possible to switch tabs with simple transition. This requires additional div class="tabs-swipeable-wrap" wrapper for div class="tabs".

In this example let's put tab links in Subnavbar and we will use page-content as tab to keep scrolling position for each tab separately:

<div class="pages navbar-fixed">
  <div data-page="home" class="page with-subnavbar">
    <div class="navbar">
      <div class="navbar-inner">
        <div class="center">Swipeable Tabs</div>
        <div class="subnavbar">
          <!-- Buttons row as tabs controller in Subnavbar-->
          <div class="buttons-row">
            <!-- Link to 1st tab, active -->
            <a href="#tab1" class="button active tab-link">Tab 1</a>
            <!-- Link to 2nd tab -->
            <a href="#tab2" class="button tab-link">Tab 2</a>
            <!-- Link to 3rd tab -->
            <a href="#tab3" class="button tab-link">Tab 3</a>
          </div>
        </div>
      </div>
    </div>
    <!-- Tabs swipeable wrapper, required to switch tabs with swipes -->
    <div class="tabs-swipeable-wrap">
      <!-- Tabs, tabs wrapper -->
      <div class="tabs">
        <!-- Tab 1, active by default -->
        <div id="tab1" class="page-content tab active">
          <div class="content-block">
            ... Tab 1 content ...
          </div>
        </div>
        <!-- Tab 2 -->
        <div id="tab2" class="page-content tab">
          <div class="content-block">
            ... Tab 2 content ...
          </div>
        </div>
        <!-- Tab 3 -->
        <div id="tab3" class="page-content tab">
          <div class="content-block">
            ... Tab 3 content ...
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

Tabs JavaScript events

Tabs events could be very useful when you need to do something in JavaScript when some Tabs becomes active:

                  Event
                  Target
                  Description

                  show
                  Tab Element<div class="tab">
                  Event will be triggered when Tab becomes visible

var myApp = new Framework7();
var $$ = Dom7;

$$('#tab1').on('show', function () {
    myApp.alert('Tab 1 is visible');
});

$$('#tab2').on('show', function () {
    myApp.alert('Tab 2 is visible');
});

$$('#tab3').on('show', function () {
    myApp.alert('Tab 3 is visible');
});

Show Tab using JavaScript

It is also possible to show tab (switch tabs) using JavaScript. We should call the following App method:

myApp.showTab(tab)

tab - HTMLElement or string (with CSS Selector) of Tab to open. Requred

This method returns true if tab has been changed, otherwise it returns false

<a href="#" class="show-tab-1">Show Tab 1</a>
<a href="#" class="show-tab-2">Show Tab 2</a>
<a href="#" class="show-tab-3">Show Tab 3</a>

var myApp = new Framework7();
var $$ = Dom7;

$$('.show-tab-1').on('click', function () {
    myApp.showTab('#tab1');
});
$$('.show-tab-2').on('click', function () {
    myApp.showTab('#tab2');
});
$$('.show-tab-3').on('click', function () {
    myApp.showTab('#tab3');
});

 stars forks

Project

Download

Contribute

Donate

Changelog

Learn

Get Started

Docs

Tutorials

Forum

Apps

Layouts

Plugins

Demo Apps

Showcase

Code licensed under MIT

2016 © Framework7 is brought to you by Vladimir Kharlampidi from iDangero.us.

Proudly supported by


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.harvard.iq.dataverse;

import edu.harvard.iq.dataverse.DatasetVersion.VersionState;
import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

/**
 *
 * @author skraffmiller
 */
@Stateless
@Named
public class DatasetVersionServiceBean implements java.io.Serializable {

    private static final Logger logger = Logger.getLogger(DatasetVersionServiceBean.class.getCanonicalName());

    @EJB
    DatasetServiceBean datasetService;

    @EJB
    SettingsServiceBean settingsService;

    @PersistenceContext(unitName = "VDCNet-ejbPU")
    private EntityManager em;

    /**
     *  Response to a successful request from the DatasetPage
     *
     *  Used to help display messages in the cases when:
     *      (1) A specific dataset version (including a DRAFT) is requested
     *      (2) A different dataset is returned b/c the first one doesn't exist
     *
     *  Simple example:  "DRAFT" requested but no longer exists b/c it
     *      was published and is now version "1.0"
     */
    public class RetrieveDatasetVersionResponse{

        private DatasetVersion datasetVersionForResponse;
        private boolean wasSpecificVersionRequested = false;
        private boolean didSpecificVersionMatch = false;
        private String actualVersion = null;
        private String requestedVersion = null;

        public RetrieveDatasetVersionResponse(DatasetVersion datasetVersion, String requestedVersion){
            if (datasetVersion == null){
                throw new IllegalArgumentException("datasetVersion cannot be null");
            }
            //logger.fine("RetrieveDatasetVersionResponse: datasetVersion: " + datasetVersion.getSemanticVersion() + " requestedVersion: " + requestedVersion);
            //logger.fine("chosenVersion id: " + datasetVersion.getId() + "  getFriendlyVersionNumber: " + datasetVersion.getFriendlyVersionNumber());
            this.datasetVersionForResponse = datasetVersion;

            this.actualVersion = datasetVersion.getSemanticVersion();
            this.requestedVersion = requestedVersion;
            this.checkVersion();
        }

        public String getDifferentVersionMessage(){

            if (this.wasSpecificVersionRequested && !this.didSpecificVersionMatch){
                String userMsg;
                if (DatasetVersionServiceBean.this.isVersionAskingForDraft(this.requestedVersion)){
                    userMsg = "The \"DRAFT\" version was not found.";
                }else{
                    userMsg = "Version \"" + this.requestedVersion + "\" was not found.";
                }

                if (DatasetVersionServiceBean.this.isVersionAskingForDraft(this.actualVersion)){
                    userMsg += "  This is the \"DRAFT\" version.";
                }else{
                    userMsg += "  This is version \"" + this.actualVersion + "\".";
                }

                return userMsg;
            }
            return null;
        }

        private void checkVersion(){
            if (actualVersion==null){   // this shouldn't happen
                return;
            }
            //logger.fine("check version. requested: " + this.requestedVersion + " returned: " + actualVersion);
            // This may often be the case if version is not specified
            //
            if (requestedVersion == null || requestedVersion.equals("")){
                this.wasSpecificVersionRequested = false;
                return;
            }

            this.wasSpecificVersionRequested = true;

            if (this.requestedVersion.equalsIgnoreCase(actualVersion)){
                this.didSpecificVersionMatch = true;
            }else{
                this.didSpecificVersionMatch = false;       // redundant, already the default
            }

        }

        public boolean wasRequestedVersionRetrieved(){
            if (this.wasSpecificVersionRequested && !this.didSpecificVersionMatch){
                return false;
            }
            return true;
        }

        public DatasetVersion getDatasetVersion(){
            return this.datasetVersionForResponse;
        }
    } // end RetrieveDatasetVersionResponse

    public DatasetVersion find(Object pk) {
        return (DatasetVersion) em.find(DatasetVersion.class, pk);
    }

    public DatasetVersion findByFriendlyVersionNumber(Long datasetId, String friendlyVersionNumber) {

        Long majorVersionNumber = null;
        Long minorVersionNumber = null;

        String[] versions = friendlyVersionNumber.split("\\.");
        try {
            if (versions.length == 1) {
                majorVersionNumber = Long.parseLong(versions[0]);
            } else if (versions.length == 2) {
                majorVersionNumber = Long.parseLong(versions[0]);
                minorVersionNumber = Long.parseLong(versions[1]);
            } else {
                return null;
            }
        } catch (NumberFormatException n) {
            return null;
        }

        if (majorVersionNumber != null && minorVersionNumber != null) {
            String queryStr = "SELECT v from DatasetVersion v where v.dataset.id = :datasetId  and v.versionNumber= :majorVersionNumber and v.minorVersionNumber= :minorVersionNumber";
            DatasetVersion foundDatasetVersion = null;
            try {
                Query query = em.createQuery(queryStr);
                query.setParameter("datasetId", datasetId);
                query.setParameter("majorVersionNumber", majorVersionNumber);
                query.setParameter("minorVersionNumber", minorVersionNumber);
                foundDatasetVersion = (DatasetVersion) query.getSingleResult();
            } catch (javax.persistence.NoResultException e) {
                logger.warning("no ds version found: " + datasetId + " " + friendlyVersionNumber);
                // DO nothing, just return null.
            }
            return foundDatasetVersion;

        }

        if (majorVersionNumber == null && minorVersionNumber == null) {

            return null;

        }

        if (majorVersionNumber != null && minorVersionNumber == null) {

            try {
                TypedQuery<DatasetVersion> typedQuery = em.createQuery("SELECT v from DatasetVersion v where v.dataset.id = :datasetId  and v.versionNumber= :majorVersionNumber", DatasetVersion.class);
                typedQuery.setParameter("datasetId", datasetId);
                typedQuery.setParameter("majorVersionNumber", majorVersionNumber);
                DatasetVersion retVal = null;
                List<DatasetVersion> versionsList = typedQuery.getResultList();
                for (DatasetVersion dsvTest : versionsList) {
                    if (retVal == null) {
                        retVal = dsvTest;
                    } else {
                        if (retVal.getMinorVersionNumber().intValue() < dsvTest.getMinorVersionNumber().intValue()) {
                            retVal = dsvTest;
                        }
                    }
                }

                return retVal;

            } catch (javax.persistence.NoResultException e) {
                logger.warning("no ds version found: " + datasetId + " " + friendlyVersionNumber);
                // DO nothing, just return null.
            }

        }

        return null;
    }

    /**
     *   Parse a Persistent Id and return as 3 strings.
     *
     *   Example: 1.0, 1.1. 3.4, etc.
     *
     * @param version
     * @return Long[] with [ major_version, minor_version ]
     *                  - either or both may be null
     */
     public Long[] parseVersionNumber(String version){
        if (version == null){
            return null;
        }

        Long majorVersion;
        Long minorVersion = null;

        String[] vparts = version.split("\\.");
        if (vparts.length == 1){
            try{
                majorVersion = Long.parseLong(vparts[0]);
            }catch (NumberFormatException n) {
                return null;
            }
        }else if (vparts.length == 2){
            try{
                majorVersion = Long.parseLong(vparts[0]);
                minorVersion = Long.parseLong(vparts[1]);
            }catch (NumberFormatException n) {
                return null;
            }
        }else{
            return null;
        }

        Long versionNumbers[] = { majorVersion, minorVersion };

        return versionNumbers;
    }

    private void msg(String s){
        //logger.fine(s);
    }

    /**
     * Does the version identifier in the URL ask for a "DRAFT"?
     *
     * @param version
     * @return boolean
     */
    private boolean isVersionAskingForDraft(String version){

        if (version == null){
            return false;
        }

        return version.toUpperCase().equals(VersionState.DRAFT.toString());
    }

    private String getDatasetVersionBasicQuery(String identifierClause, String extraClause){

        if (identifierClause == null){
            return null;
        }

        if (extraClause == null){
            extraClause = "";
        }

        String queryStr = "SELECT dv.* FROM DatasetVersion dv";
        queryStr += " INNER JOIN Dataset ds";
        queryStr += " ON dv.dataset_id=ds.id";
        queryStr += identifierClause;      // either persistentId or id
        queryStr += extraClause;   // may be an empty string
        queryStr += " ORDER BY versionNumber DESC, minorVersionNumber DESC";
        queryStr += " LIMIT 1;";

        return queryStr;

    }

    /**
     * Query to return the last Released DatasetVersion by Persistent ID
     *
     * @param identifierClause  - query clause to retrieve via DatasetVersion.Id or DatasetVersion.persistentId
     * @return String fullQuery
     */
    private String getLatestReleasedDatasetVersionQuery(String identifierClause){

        if (identifierClause == null){
            return null;
        }
        String releasedClause = " AND dv.versionstate = '" + VersionState.RELEASED.toString() + "'";

        return getDatasetVersionBasicQuery(identifierClause, releasedClause);

    }

     /**
     * Query to return a DatasetVersion by Specific Version
     *
     * @param identifierClause  - query clause to retrieve via DatasetVersion.Id or DatasetVersion.persistentId
     * @return String fullQuery
     */
    private String getNumericDatasetVersionQueryByIdentifier(String identifierClause, Long majorVersion, Long minorVersion){

        if (identifierClause == null){
            return null;
        }
        String extraQueryClause = "";

        // For an exact version: retrieve either RELEASED or DEACCESSIONED
        //
        if (majorVersion != null && minorVersion != null){
            extraQueryClause += " AND dv.versionNumber= " + majorVersion;
            extraQueryClause += " AND dv.minorVersionNumber= " + minorVersion;
            extraQueryClause += " AND (dv.versionstate = '" + VersionState.RELEASED.toString() + "' or dv.versionstate = '" + VersionState.DEACCESSIONED.toString() + "')";
        } else {
            // Last released major version
            //
            extraQueryClause += " AND dv.versionNumber= " + majorVersion;
            extraQueryClause += " AND dv.versionstate = '" + VersionState.RELEASED.toString() + "'";
        }

        return getDatasetVersionBasicQuery(identifierClause, extraQueryClause);

    }

    /**
     * Query to return a Draft DatasetVersion by Persistent ID
     *
     * @param identifierClause  - query clause to retrieve via DatasetVersion.Id or DatasetVersion.persistentId
     * @return String fullQuery
     */
    private String getDraftDatasetVersionQuery(String identifierClause){

        if (identifierClause == null){
            return null;
        }
        String draftClause = " AND dv.versionstate = '" + VersionState.DRAFT.toString() + "'";

        return getDatasetVersionBasicQuery(identifierClause, draftClause);

    }

        /**
     * Query to return a DEACCESSIONED DatasetVersion by Persistent ID
     *
     * @param identifierClause  - query clause to retrieve via DatasetVersion.Id or DatasetVersion.persistentId
     * @return String fullQuery
     */
    private String getDeaccessionedDatasetVersionQuery(String identifierClause){

        if (identifierClause == null){
            return null;
        }
        String draftClause = " AND dv.versionstate = '" + VersionState.DEACCESSIONED.toString() + "'";

        return getDatasetVersionBasicQuery(identifierClause, draftClause);

    }

    /**
     * Execute a query to return DatasetVersion
     *
     * @param queryString
     * @return
     */
    private DatasetVersion getDatasetVersionByQuery(String queryString){
        msg("getDatasetVersionByQuery queryString: " + queryString);
        if (queryString == null){
            return null;
        }

        // Inexact check to see if one of the selected tables is DATASETVERSION
        //
        if (!queryString.toUpperCase().contains("FROM DATASETVERSION")){
            throw new IllegalArgumentException("This query does not select from the table DATASETVERSION");
        }

        try{
            Query query = em.createNativeQuery(queryString, DatasetVersion.class);
            DatasetVersion ds = (DatasetVersion) query.getSingleResult();

            msg("Found: " + ds);
            return ds;

        } catch (javax.persistence.NoResultException e) {
            msg("DatasetVersion not found: " + queryString);
            logger.log(Level.FINE, "DatasetVersion not found: {0}", queryString);
            return null;
         } catch (EJBException e) {
             logger.log(Level.WARNING, "EJBException exception: {0}", e.getMessage());
             return null;
         }
    } // end getDatasetVersionByQuery

    public DatasetVersion retrieveDatasetVersionByIdentiferClause(String identifierClause, String version){

        if (identifierClause == null){
            return null;
        }

        DatasetVersion chosenVersion;

        /* --------------------------------------------
            (1) Scenario: User asking for a DRAFT?
                - (1a) Look for draft
                - (1b) Not found: Get Latest Release
                - Permissions: check on DatasetPage
        -------------------------------------------- */
        if (DatasetVersionServiceBean.this.isVersionAskingForDraft(version)){

            // (1a) Try to retrieve a draft
            msg("(1a) Try to retrieve a draft");
            String draftQuery = this.getDraftDatasetVersionQuery(identifierClause);
            chosenVersion = this.getDatasetVersionByQuery(draftQuery);

            // Draft Exists! Return it!
            msg("Draft Exists! Return it!");
            if (chosenVersion != null){
                return chosenVersion;   // let DatasetPage check permissions
            }

            // (1b) No draft found - check for last released
            msg("(1b) No draft found - check for last released");
            String lastReleasedQuery = this.getLatestReleasedDatasetVersionQuery(identifierClause);
            chosenVersion = this.getDatasetVersionByQuery(lastReleasedQuery);

            return chosenVersion;  // This may be null -- let DatasetPage check
        }
        // END: User asking for a Draft

        /* --------------------------------------------
            (2) Scenario: Version specified
                - (2a) Look for major and minor version - RELEASE OR DEACCESSIONED
                    - OR Look for major version - RELEASE
                - (2c) Not found: look for latest released version
                - (2c) Not found: look for DEACCESSIONED
                - (2d) Not found: look for draft
                - Permissions: check on DatasetPage

            (3) Scenario: No version specified
                - Same as (2c)(2d) above
                - Permissions: check on DatasetPage
        -------------------------------------------- */
        Long[] versionNumbers = parseVersionNumber(version);
        if (versionNumbers != null && versionNumbers.length == 2){        // At least a major version found

            // (2a) Look for major and minor version - RELEASE OR DEACCESSIONED
            msg("(2a) Look for major and minor version -" + Arrays.toString(versionNumbers));
            String specificVersionQuery = this.getNumericDatasetVersionQueryByIdentifier(identifierClause, versionNumbers[0], versionNumbers[1]);

            chosenVersion = this.getDatasetVersionByQuery(specificVersionQuery);
            if (chosenVersion != null){
                return chosenVersion;
            }
        }

        // (2b) Look for latest released version
        msg("(2b) Look for latest released version");
        String latestVersionQuery = this.getLatestReleasedDatasetVersionQuery(identifierClause);
        //msg("latestVersionQuery: " + latestVersionQuery);
        chosenVersion = this.getDatasetVersionByQuery(latestVersionQuery);
        if (chosenVersion != null){
            return chosenVersion;
        }

        // (2c) Look for DEACCESSIONED
        msg("(2c) Look for draft");
        String dQuery = this.getDeaccessionedDatasetVersionQuery(identifierClause);
        //msg("draftQuery: " + draftQuery);
        chosenVersion = this.getDatasetVersionByQuery(dQuery);
        if (chosenVersion != null){
            return chosenVersion;
        }

        // (2d) Look for draft
        msg("(2d) Look for draft");
        String draftQuery = this.getDraftDatasetVersionQuery(identifierClause);
        //msg("draftQuery: " + draftQuery);
        chosenVersion = this.getDatasetVersionByQuery(draftQuery);

        return chosenVersion;   // This may be null -- let DatasetPage check

    } // end: retrieveDatasetVersionByPersistentId

    /**
     * Find a DatasetVersion using the persisentID and version string
     *
     * @param persistentId doi:10.5072/FK2/BYM3IW
     * @param version  "DRAFT", 1.0, 2, 3.4, null, etc
     * @return
     */
    public RetrieveDatasetVersionResponse retrieveDatasetVersionByPersistentId(String persistentId, String version){

        msg("retrieveDatasetVersionByPersistentId: " + persistentId + " " + version);
        if (persistentId==null){
            return null;
        }

        /*
            Parse the persistent id
        */
        GlobalId parsedId;
        try{
            parsedId = new GlobalId(persistentId);   // [ protocol, authority, identifier]
        } catch (IllegalArgumentException e){
            logger.log(Level.WARNING, "Failed to parse persistentID: {0}", persistentId);
            return null;
        }

        String identifierClause = " AND ds.protocol= '" + parsedId.getProtocol() + "'";
        identifierClause += " AND ds.authority = '" + parsedId.getAuthority() + "'";
        identifierClause += " AND ds.identifier = '" + parsedId.getIdentifier() + "'";

        DatasetVersion ds = retrieveDatasetVersionByIdentiferClause(identifierClause, version);

        if (ds != null){
            msg("retrieved dataset: " + ds.getId() + " semantic: " + ds.getSemanticVersion());
            return new RetrieveDatasetVersionResponse(ds, version);
        }

        return null;

    }

     /**
     * Find a DatasetVersion using the persisentID and version string
     *
     * @param datasetId
     * @param version  "DRAFT", 1.0, 2, 3.4, null, etc
     * @return
     */
    public RetrieveDatasetVersionResponse retrieveDatasetVersionById(Long datasetId, String version){
        msg("retrieveDatasetVersionById: " + datasetId + " " + version);
        if (datasetId==null){
            return null;
        }

        String identifierClause = " AND ds.id = " + datasetId;

        DatasetVersion ds = retrieveDatasetVersionByIdentiferClause(identifierClause, version);

        if (ds != null){
            return new RetrieveDatasetVersionResponse(ds, version);
        }

        return null;

    } // end: retrieveDatasetVersionById

     /**
     * Find a DatasetVersion using the dataset versionId
     *
     * @param versionId DatasetVersion id
     * @return
     */
    public RetrieveDatasetVersionResponse retrieveDatasetVersionByVersionId(Long versionId){
        //msg("retrieveDatasetVersionById: " + datasetId + " " + versionId);
        if (versionId==null ){
            return null;
        }

        // Try versionId - release state doesn't matte
        //
        String retrieveSpecifiedDSVQuery = "SELECT dv.* FROM DatasetVersion dv WHERE dv.id = " + versionId;

        DatasetVersion chosenVersion = this.getDatasetVersionByQuery(retrieveSpecifiedDSVQuery);
        if (chosenVersion != null) {
            return new RetrieveDatasetVersionResponse(chosenVersion, "");
        }
        return null;
    } // end: retrieveDatasetVersionByVersionId

} // end class


text:
namespace System.Runtime.Serialization
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = true, AllowMultiple = true)]
    public sealed class KnownTypeAttribute : Attribute
    {
        string methodName;
        Type type;

        private KnownTypeAttribute()
        {
            // Disallow default constructor
        }

        public KnownTypeAttribute(Type type)
        {
            this.type = type;
        }

        public KnownTypeAttribute(string methodName)
        {
            this.methodName = methodName;
        }

        public string MethodName
        {
            get { return methodName; }
            //set { methodName = value; }
        }

        public Type Type
        {
            get { return type; }
            //set { type = value; }
        }
    }
}