text:
import { defaultTextureSettings } from './asset-lib'
import { Painter } from './painter'
import { GL2, TextureData, Wrap } from './painter-types'

let textureCount = 1

export class Texture {
	_texture: WebGLTexture | null = null
	_data: TextureData = {}

	constructor(
		private _painter: Painter,
		public id = 'Texture' + textureCount++,
	) {}

	update(data: TextureData & { width?: number; height?: number }) {
		const gl = this._painter.gl

		if (this._texture == null) {
			this._texture = gl.createTexture()
		}

		gl.bindTexture(gl.TEXTURE_2D, this._texture)

		if (
			(data.wrap && data.wrap !== this._data.wrap) ||
			(data.wrapS && data.wrapS !== this._data.wrapS) ||
			(data.wrapT && data.wrapT !== this._data.wrapT)
		) {
			let wrapS: Wrap, wrapT: Wrap
			if (data.wrap) {
				wrapS = wrapT = data.wrap
			} else {
				wrapT = data.wrapT || defaultTextureSettings.wrap!
				wrapS = data.wrapS || defaultTextureSettings.wrap!
			}

			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl[wrapS])
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl[wrapT])
		} else if (!(this._data.wrap || this._data.wrapS || this._data.wrapT)) {
			this._data.wrap = this._data.wrapT = this._data.wrapS = defaultTextureSettings.wrap!
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl[this._data.wrap])
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl[this._data.wrap])
		}

		if (data.magFilter && data.magFilter !== this._data.magFilter) {
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl[data.magFilter])
		} else if (!this._data.magFilter) {
			this._data.magFilter = defaultTextureSettings.magFilter!
			gl.texParameteri(
				gl.TEXTURE_2D,
				gl.TEXTURE_MAG_FILTER,
				gl[this._data.magFilter],
			)
		}

		if (data.minFilter && data.minFilter !== this._data.minFilter) {
			gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl[data.minFilter])
		} else if (!this._data.minFilter) {
			this._data.minFilter = defaultTextureSettings.minFilter!
			gl.texParameteri(
				gl.TEXTURE_2D,
				gl.TEXTURE_MIN_FILTER,
				gl[this._data.minFilter],
			)
		}

		if (data.asset) {
			gl.texImage2D(
				gl.TEXTURE_2D,
				0,
				gl.RGBA,
				gl.RGBA,
				gl.UNSIGNED_BYTE,
				data.asset,
			)
		}

		if (data.data !== undefined) {
			gl.texImage2D(
				gl.TEXTURE_2D,
				0,
				data.type === 'FLOAT' && this._painter.isWebGL2
					? (gl as GL2).RGBA32F
					: gl.RGBA,
				data.width!, // width and height are required if using custom data
				data.height!,
				0,
				gl.RGBA,
				gl[data.type || 'UNSIGNED_BYTE'],
				data.data,
			)
		}

		if (data.flipY != null && data.flipY !== this._data.flipY) {
			gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, data.flipY as any)
		}

		if (data.minFilter && data.minFilter.indexOf('MIPMAP') > 0) {
			gl.generateMipmap(gl.TEXTURE_2D)
		}

		gl.bindTexture(gl.TEXTURE_2D, null)

		Object.assign(this._data, data)

		return this
	}

	destroy() {
		this._painter.gl.deleteTexture(this._texture)
		this._data = {}
		this._texture = null
	}
}


text:
""" Wrap the algorithms defined in `scikit.learn <http://scikit-learn.org/>`_ in pySPACE nodes

For details on parameter usage look at the
`scikit documentation <http://scikit-learn.org/>`_ or
the wrapped documentation of pySPACE: :ref:`scikit_nodes`.
The parameters given in the node specification are filtered, to check if they
are available, and then directly forwarded to the scikit algorithm.

This module is based heavily on the scikit.learn wrapper for the "Modular
toolkit for Data Processing"
(MDP, version 3.3, http://mdp-toolkit.sourceforge.net/).
All credit goes to the MDP authors.

MDP (version 3.3) is distributed under the following BSD license::

    This file is part of Modular toolkit for Data Processing (MDP).
    All the code in this package is distributed under the following conditions:

    Copyright (c) 2003-2012, MDP Developers <mdp-toolkit-devel@lists.sourceforge.net>

    All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

        * Redistributions of source code must retain the above copyright
          notice, this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright
          notice, this list of conditions and the following disclaimer in the
          documentation and/or other materials provided with the distribution.
        * Neither the name of the Modular toolkit for Data Processing (MDP)
          nor the names of its contributors may be used to endorse or promote
          products derived from this software without specific prior written
          permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
    ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
    WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
    DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
    FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
    SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
    CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
    OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import cPickle
from pySPACE.tools.filesystem import create_directory

__docformat__ = "restructuredtext en"

try:
    import sklearn
    _sklearn_prefix = 'sklearn'
except ImportError:
    try:
        import scikits.learn as sklearn
        _sklearn_prefix = 'scikits.learn'
    except ImportError:
        _sklearn_prefix = False

import inspect
import re

import numpy
import logging
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
import sys
import os

from pySPACE.missions.nodes.base_node import BaseNode
from pySPACE.missions.nodes import NODE_MAPPING, DEFAULT_NODE_MAPPING
from pySPACE.resources.data_types.prediction_vector import PredictionVector
from pySPACE.resources.data_types.feature_vector import FeatureVector

class ScikitException(Exception):
    """Base class for exceptions in nodes wrapping scikit algorithms."""
    pass

# import all submodules of sklearn (to work around lazy import)
def _version_too_old(version, known_good):
    """ version comparison """
    for part,expected in zip(version.split('.'), known_good):
        try:
            p = int(part)
        except ValueError:
            return None
        if p < expected:
            return True
        if p > expected:
            break
    return False

if not _sklearn_prefix:
    scikit_modules = []
elif _version_too_old(sklearn.__version__, (0, 8)):
    scikit_modules = ['ann', 'cluster', 'covariance', 'feature_extraction',
                       'feature_selection', 'features', 'gaussian_process', 'glm',
                       'linear_model', 'preprocessing', 'svm',
                       'pca', 'lda', 'hmm', 'fastica', 'grid_search', 'mixture',
                       'naive_bayes', 'neighbors', 'qda']
elif _version_too_old(sklearn.__version__, (0, 9)):
    # package structure has been changed in 0.8
    scikit_modules = ['svm', 'linear_model', 'naive_bayes', 'neighbors',
                       'mixture', 'hmm', 'cluster', 'decomposition', 'lda',
                       'covariance', 'cross_val', 'grid_search',
                       'feature_selection.rfe', 'feature_extraction.image',
                       'feature_extraction.text', 'pipelines', 'pls',
                       'gaussian_process', 'qda']
elif _version_too_old(sklearn.__version__, (0, 11)):
    # from release 0.9 cross_val becomes cross_validation and hmm is deprecated
    scikit_modules = ['svm', 'linear_model', 'naive_bayes', 'neighbors',
                       'mixture', 'cluster', 'decomposition', 'lda',
                       'covariance', 'cross_validation', 'grid_search',
                       'feature_selection.rfe', 'feature_extraction.image',
                       'feature_extraction.text', 'pipelines', 'pls',
                       'gaussian_process', 'qda', 'ensemble', 'manifold',
                       'metrics', 'preprocessing', 'tree']
elif _version_too_old(sklearn.__version__, (0, 17)):
    scikit_modules = ['svm', 'linear_model', 'naive_bayes', 'neighbors',
                       'mixture', 'cluster', 'decomposition', 'lda',
                       'covariance', 'cross_validation', 'grid_search',
                       'feature_selection', 'feature_extraction',
                       'pipeline', 'pls', 'gaussian_process', 'qda',
                       'ensemble', 'manifold', 'metrics', 'preprocessing',
                       'semi_supervised', 'tree', 'hmm']
else:
    scikit_modules = ['calibration', 'cluster', 'covariance',
                       'cross_decomposition', 'cross_validation',
                       'decomposition', 'discriminant_analysis',
                       'ensemble', 'feature_extraction', 'feature_selection',
                       'gaussian_process', 'grid_search', 'isotonic',
                       'kernel_approximation', 'kernel_ridge', 'learning_curve',
                       'linear_model', 'manifold', 'metrics', 'mixture',
                       'multiclass', 'naive_bayes', 'neighbors',
                       'neural_network', 'preprocessing', 'random_projection',
                       'semi_supervised', 'svm', 'tree']

for name in scikit_modules:
    # not all modules may be available due to missing dependencies
    # on the user system.
    # we just ignore failing imports
    try:
        __import__(_sklearn_prefix + '.' + name)
    except ImportError:
        pass

_WS_LINE_RE = re.compile(r'^\s*$')
_WS_PREFIX_RE = re.compile(r'^(\s*)')
_HEADINGS_RE = re.compile(r'''^(Parameters|Attributes|Methods|Examples|Notes)\n
                           (----+|====+)''', re.M + re.X)
_UNDERLINE_RE = re.compile(r'----+|====+')
_VARWITHUNDER_RE = re.compile(r'(\s|^)([a-zA-Z_][a-zA-Z0-9_]*_)(\s|$|[,.])')

_HEADINGS = set(['Parameters', 'Attributes', 'Methods', 'Examples',
                 'Notes', 'References'])

_DOC_TEMPLATE = """
%s

This node has been automatically generated by wrapping the
`%s.%s <http://scikit-learn.org/stable/modules/generated/%s.%s.html>`_ class
from the ``sklearn`` library.  The wrapped instance can be accessed
through the ``scikit_alg`` attribute.

%s
"""

def _gen_docstring(object, docsource=None):
    """ Generate and modify the docstring for each wrapped node """
    module = object.__module__
    name = object.__name__

    if hasattr(__import__(".".join(module.split(".")[:-1])), name):
        link_module = ".".join(module.split(".")[:-1])
    else:
        link_module = module

    # search for documentation string
    if docsource is None:
        docsource = object
    docstring = docsource.__doc__
    if docstring is None:
        docstring = object.__doc__
    if docstring is None:
        docstring = "This algorithm contains no documentation."
        # # error search for getting docstring
        # print object
        # print module
        # print object.__dict__
        # print docsource
        #warnings.warn("No documentation found for %s.%s" % (module, name))
        #return None  # old case
        pass

    lines = docstring.strip().split('\n')
    for i, line in enumerate(lines):
        if _WS_LINE_RE.match(line):
            break
    header = [line.strip() for line in lines[:i]]

    therest = [line.rstrip() for line in lines[i + 1:]]
    body = []

    if therest:
        prefix = min(len(_WS_PREFIX_RE.match(line).group(1))
                     for line in therest if line)
        quoteind = None
        for i, line in enumerate(therest):
            line = line[prefix:]
            if line in _HEADINGS:
                body.append('**%s**' % line)
            elif _UNDERLINE_RE.match(line):
                body.append('')
            else:
                line = _VARWITHUNDER_RE.sub(r'\1``\2``\3', line)
                if quoteind:
                    if len(_WS_PREFIX_RE.match(line).group(1)) >= quoteind:
                        line = quoteind * ' ' + '- ' + line[quoteind:]
                    else:
                        quoteind = None
                        body.append('')
                body.append(line)

            if line.endswith(':'):
                body.append('')
                if i + 1 < len(therest):
                    next = therest[i + 1][prefix:]
                    quoteind = len(_WS_PREFIX_RE.match(next).group(1))

    return _DOC_TEMPLATE % ('\n'.join(header), module, name, link_module, name,
                            '\n'.join(body))

# TODO: generalize dtype support
# TODO: have a look at predict_proba for Classifier.prob
# TODO: inverse <-> generate/rvs
# TODO: deal with input_dim/output_dim
# TODO: change signature of overwritten functions
# TODO: wrap_scikit_instance
# TODO: add sklearn availability to test info strings
# TODO: which tests ? (test that particular algorithm are / are not trainable)
# XXX: if class defines n_components, allow output_dim, otherwise throw exception
#      also for classifiers (overwrite _set_output_dim)
#      Problem: sometimes they call it 'k' (e.g., algorithms in sklearn.cluster)

def apply_to_scikit_algorithms(current_module, action,
                                processed_modules=None,
                                processed_classes=None):
    """ Function that traverses a module to find scikit algorithms.

    'sklearn' algorithms are identified by the 'fit' 'predict',
    or 'transform' methods. The 'action' function is applied to each found
    algorithm.

    action -- a function that is called with as ``action(class_)``, where
              ``class_`` is a class that defines the 'fit' or 'predict' method
    """

    # only consider modules and classes once
    if processed_modules is None:
        processed_modules = []
    if processed_classes is None:
        processed_classes = []

    if current_module in processed_modules:
        return
    processed_modules.append(current_module)

    for member_name, member in current_module.__dict__.items():
        if not member_name.startswith('_'):
            # classes
            if inspect.isclass(member) and member not in processed_classes:
                if ((hasattr(member, 'fit')
                        or hasattr(member, 'predict')
                        or hasattr(member, 'transform'))
                        and not member.__module__.endswith('_')):
                    processed_classes.append(member)
                    try:
                        action(member)
                    # ignore failed imports
                    except:
                        warnings.warn("Could not wrap sklearn nodes.")

            # other modules
            elif (inspect.ismodule(member) and
                  member.__name__.startswith(_sklearn_prefix)):
                apply_to_scikit_algorithms(member, action, processed_modules,
                                            processed_classes)
    return processed_classes

_OUTPUTDIM_ERROR = """'output_dim' keyword not supported.

Please set the output dimensionality using sklearn keyword
arguments (e.g., 'n_components', or 'k'). See the docstring of
this class for details."""

def wrap_scikit_classifier(scikit_class):
    """Wrap a sklearn classifier as a BaseNode subclass.

    The wrapper maps these node methods to their sklearn equivalents:

    - _stop_training -> fit
    - _execute -> predict
    """

    newaxis = numpy.newaxis

    # create a wrapper class for a sklearn classifier
    class ScikitClassifier(BaseNode):
        input_types = ["FeatureVector"]

        def __init__(self, input_dim=None, output_dim=None, dtype=None,
                     class_labels=None, **kwargs):

            if output_dim is not None:
                # output_dim and n_components cannot be defined at the same time
                if 'n_components' in kwargs:
                    msg = ("Dimensionality set both by "
                           "output_dim=%d and n_components=%d""")
                    raise ScikitException(msg % (output_dim,
                                                  kwargs['n_components']))
            try:
                accepted_args = inspect.getargspec(scikit_class.__init__)[0]
                base_kwargs = {}
                for key in kwargs.keys():
                    if key not in accepted_args:
                        base_kwargs[key] = kwargs.pop(key)
                    del(key)
                del(accepted_args)
            except TypeError:  # happens for GaussianNBSklearnNode
                base_kwargs = kwargs
                kwargs = {}

            super(ScikitClassifier, self).__init__(
                input_dim=input_dim, output_dim=output_dim, dtype=dtype,
                **base_kwargs)

            self.kwargs = kwargs

            self.set_permanent_attributes(kwargs=kwargs,
                                          scikit_alg=scikit_class(**self.kwargs),
                                          data=[],
                                          labels=[],
                                          class_labels=class_labels)

        # ---- re-direct training and execution to the wrapped algorithm

        def _train(self, data, y):
            x = data.view(numpy.ndarray)
            self.data.append(x[0])
            self.labels.append(y)

        def _stop_training(self, **kwargs):
            super(ScikitClassifier, self)._stop_training(self)
            if self.class_labels is None:
                self.class_labels = sorted(list(set(self.labels)))

            data = numpy.array(self.data)
            label_values = \
                numpy.array(map(lambda s: self.class_labels.index(s),
                                self.labels))
            try:
                return self.scikit_alg.fit(data, label_values, **kwargs)
            except Exception as e:
                raise type(e), \
                type(e)("in node %s:\n\t"%self.__class__.__name__+e.args[0]),\
                sys.exc_info()[2]

        def _execute(self, data):
            x = data.view(numpy.ndarray)
            try:
                prediction = self.scikit_alg.predict(x)[0]
            except Exception as e:
                raise type(e), \
                type(e)("in node %s:\n\t"%self.__class__.__name__+e.args[0]), \
                sys.exc_info()[2]
            if hasattr(self.scikit_alg, "predict_proba"):
                try:
                    score = self.scikit_alg.predict_proba(x)[0, 1]
                except Exception as e:
                    warnings.warn("%s in node %s:\n\t"\
                            %(type(e).__name__,self.__class__.__name__)+e.args[0])
                    try:
                        score = self.scikit_alg.decision_function(x)[0]
                    except:
                        score = prediction
            elif hasattr(self.scikit_alg, "decision_function"):
                score = self.scikit_alg.decision_function(x)[0]
            else:
                score = prediction
            label = self.class_labels[prediction]
            return PredictionVector(label=label, prediction=score,
                                    predictor=self)
        @classmethod
        def get_output_type(cls, input_type, as_string=True):
            if as_string:
                return "PredictionVector"
            else:
                return PredictionVector

        # ---- administrative details

        @staticmethod
        def is_trainable():
            """Return True if the node can be trained, False otherwise."""
            return hasattr(scikit_class, 'fit')

        @staticmethod
        def is_supervised():
            """Return True if the node requires labels for training, False otherwise."""
            return True

        # NOTE: at this point scikit nodes can only support up to
        # 64-bits floats because some call numpy.linalg.svd, which for
        # some reason does not support higher precisions
        def _get_supported_dtypes(self):
            """Return the list of dtypes supported by this node.
            The types can be specified in any format allowed by numpy.dtype."""
            return ['float32', 'float64']

        def store_state(self, result_dir, index=None):
            """ Stores *scikit_alg* """
            if self.store:
                node_dir = os.path.join(result_dir, self.__class__.__name__)
                create_directory(node_dir)
                name = "%s_sp%s.pickle" % ("Model", self.current_split)
                result_file = open(os.path.join(node_dir, name), "wb")
                result_file.write(cPickle.dumps(self.scikit_alg, protocol=2))
                result_file.close()
            super(ScikitClassifier,self).store_state(result_dir, index)

    # modify class name and docstring
    if "Classifier" not in scikit_class.__name__:
        ScikitClassifier.__name__ = scikit_class.__name__ + \
            'ClassifierSklearnNode'
    else:
        ScikitClassifier.__name__ = scikit_class.__name__ + 'SklearnNode'

    ScikitClassifier.__doc__ = _gen_docstring(scikit_class)

    # Class must be permanently accessible from module level
    globals()[ScikitClassifier.__name__] = ScikitClassifier

    # change the docstring of the methods to match the ones in sklearn

    # methods_dict maps ScikitNode method names to sklearn method names
    methods_dict = {'__init__': '__init__',
                    'stop_training': 'fit',
                    'execute': 'predict'}
    #if hasattr(scikit_class, 'predict_proba'):
    #    methods_dict['prob'] = 'predict_proba'

    for pyspace_name, scikit_name in methods_dict.items():
        pyspace_method = getattr(ScikitClassifier, pyspace_name)
        scikit_method = getattr(scikit_class, scikit_name)
        if hasattr(scikit_method, 'im_func'):
            # some scikit algorithms do not define an __init__ method
            # the one inherited from 'object' is a
            # "<slot wrapper '__init__' of 'object' objects>"
            # which does not have a 'im_func' attribute
            pyspace_method.im_func.__doc__ = _gen_docstring(scikit_class,
                                                           scikit_method.im_func)

    if scikit_class.__init__.__doc__ is None:
        ScikitClassifier.__init__.im_func.__doc__ = _gen_docstring(scikit_class)

    return ScikitClassifier

def wrap_scikit_transformer(scikit_class):
    """ Wrap a sklearn transformer as a pySPACE BaseNode subclass

    The wrapper maps these pySPACE methods to their sklearn equivalents:

    - _stop_training -> fit
    - _execute -> transform
    """

    # create a wrapper class for a sklearn transformer
    class ScikitTransformer(BaseNode):
        input_types = ["FeatureVector"]

        def __init__(self, input_dim=None, output_dim=None, dtype=None, **kwargs):
            if output_dim is not None:
                raise ScikitException(_OUTPUTDIM_ERROR)
            accepted_args = inspect.getargspec(scikit_class.__init__)[0]
            base_kwargs = {}
            for key in kwargs.keys():
                if key not in accepted_args:
                    base_kwargs[key] = kwargs.pop(key)
                del(key)
            del(accepted_args)
            super(ScikitTransformer, self).__init__(
                input_dim=input_dim, output_dim=output_dim, dtype=dtype,
                **base_kwargs)
            self.kwargs = kwargs

            self.set_permanent_attributes(kwargs=kwargs,
                                          scikit_alg=scikit_class(**self.kwargs),
                                          data=[],
                                          feature_names=None)

        # ---- re-direct training and execution to the wrapped algorithm

        def _train(self, data):
            assert type(data) == FeatureVector, \
                "Scikit-Learn Transformer nodes only support FeatureVector inputs."
            x = data.view(numpy.ndarray)
            self.data.append(x[0])

        def _stop_training(self, **kwargs):
            super(ScikitTransformer, self)._stop_training(self)
            data = numpy.array(self.data)
            return self.scikit_alg.fit(data, **kwargs)

        def _execute(self, data):
            x = data.view(numpy.ndarray)
            out = self.scikit_alg.transform(x[0])
            if self.feature_names is None:
                self.feature_names = \
                    ["%s_%s" % (self.__class__.__name__, i)
                        for i in range(out.shape[1])]
            return FeatureVector(out, self.feature_names)

        # ---- administrative details

        @staticmethod
        def is_trainable():
            """Return True if the node can be trained, False otherwise."""
            return hasattr(scikit_class, 'fit')

        @staticmethod
        def is_supervised():
            """Return True if the node requires labels for training, False otherwise."""
            return False

        # NOTE: at this point scikit nodes can only support up to
        # 64-bits floats because some call numpy.linalg.svd, which for
        # some reason does not support higher precisions
        def _get_supported_dtypes(self):
            """Return the list of dtypes supported by this node.
            The types can be specified in any format allowed by numpy.dtype."""
            return ['float32', 'float64']

        @classmethod
        def get_output_type(cls, input_type, as_string=True):
            if as_string:
                return "FeatureVector"
            else:
                return FeatureVector

        def store_state(self, result_dir, index=None):
            """ Stores *scikit_alg* """
            if self.store:
                node_dir = os.path.join(result_dir, self.__class__.__name__)
                create_directory(node_dir)
                name = "%s_sp%s.pickle" % ("Model", self.current_split)
                result_file = open(os.path.join(node_dir, name), "wb")
                result_file.write(cPickle.dumps(self.scikit_alg, protocol=2))
                result_file.close()
            super(ScikitTransformer,self).store_state(result_dir, index)

    # modify class name and docstring
    if "Transformer" not in scikit_class.__name__:
        ScikitTransformer.__name__ = scikit_class.__name__ + \
            'TransformerSklearnNode'
    else:
        ScikitTransformer.__name__ = scikit_class.__name__ + 'SklearnNode'

    ScikitTransformer.__doc__ = _gen_docstring(scikit_class)

    # Class must be permanently accessible from module level
    globals()[ScikitTransformer.__name__] = ScikitTransformer

    # change the docstring of the methods to match the ones in sklearn

    # methods_dict maps ScikitNode method names to sklearn method names
    methods_dict = {'__init__': '__init__',
                    'stop_training': 'fit',
                    'execute': 'transform'}

    for pyspace_name, scikit_name in methods_dict.items():
        pyspace_method = getattr(ScikitTransformer, pyspace_name)
        scikit_method = getattr(scikit_class, scikit_name, None)
        if hasattr(scikit_method, 'im_func'):
            # some scikit algorithms do not define an __init__ method
            # the one inherited from 'object' is a
            # "<slot wrapper '__init__' of 'object' objects>"
            # which does not have a 'im_func' attribute
            pyspace_method.im_func.__doc__ = _gen_docstring(scikit_class,
                                                            scikit_method.im_func)

    if scikit_class.__init__.__doc__ is None:
        ScikitTransformer.__init__.im_func.__doc__ = _gen_docstring(scikit_class)
    return ScikitTransformer

def wrap_scikit_predictor(scikit_class):
    """ Wrap a sklearn predictor as an pySPACE BaseNode subclass

    The wrapper maps these pySPACE methods to their sklearn equivalents:

    * _stop_training -> fit
    * _execute -> predict
    """

    # create a wrapper class for a sklearn predictor
    class ScikitPredictor(BaseNode):
        input_types = ["FeatureVector"]

        def __init__(self, input_dim=None, output_dim=None, dtype=None, **kwargs):
            if output_dim is not None:
                raise ScikitException(_OUTPUTDIM_ERROR)
            accepted_args = inspect.getargspec(scikit_class.__init__)[0]
            base_kwargs = {}
            for key in kwargs.keys():
                if key not in accepted_args:
                    base_kwargs[key] = kwargs.pop(key)
                del(key)
            del(accepted_args)
            super(ScikitPredictor, self).__init__(
                input_dim=input_dim, output_dim=output_dim, dtype=dtype,
                **base_kwargs)
            self.kwargs = kwargs

            self.set_permanent_attributes(kwargs=kwargs,
                                          data=[],
                                          labels=[],
                                          scikit_alg=scikit_class(**self.kwargs))

        # ---- re-direct training and execution to the wrapped algorithm

        def _train(self, data, y):
            x = data.view(numpy.ndarray)
            self.data.append(x[0])
            self.labels.append(numpy.float64(y))

        def _stop_training(self, **kwargs):
            super(ScikitPredictor, self)._stop_training(self)
            data = numpy.array(self.data)
            label_values = numpy.array(self.labels)
            try:
                return self.scikit_alg.fit(data, label_values, **kwargs)
            except Exception as e:
                raise type(e), \
                    type(e)("in node %s:\n\t"%self.__class__.__name__+e.args[0]), \
                    sys.exc_info()[2]

        def _execute(self, data):
            x = data.view(numpy.ndarray)
            try:
                prediction = self.scikit_alg.predict(x)[0]
            except Exception as e:
                raise type(e), \
                    type(e)("in node %s:\n\t"%self.__class__.__name__+e.args[0]), \
                    sys.exc_info()[2]

            if hasattr(self.scikit_alg, "predict_proba"):
                try:
                    score = self.scikit_alg.predict_proba(x)[0, 1]
                except Exception as e:
                    warnings.warn("%s in node %s:\n\t" \
                                  %(type(e).__name__,self.__class__.__name__)+e.args[0])
                    try:
                        score = self.scikit_alg.decision_function(x)[0]
                    except:
                        score = prediction
            elif hasattr(self.scikit_alg, "decision_function"):
                score = self.scikit_alg.decision_function(x)[0]
            else:
                # if nothing else works, we set the score of the
                # prediction to be equal to the prediction itself.
                score = prediction

            return PredictionVector(label=prediction, prediction=score,
                                    predictor=self)
        # ---- administrative details

        def is_trainable(self):
            """Return True if the node can be trained, False otherwise."""
            return hasattr(scikit_class, 'fit')

        # NOTE: at this point scikit nodes can only support up to 64-bits floats
        # because some call numpy.linalg.svd, which for some reason does not
        # support higher precisions
        def _get_supported_dtypes(self):
            """Return the list of dtypes supported by this node.
            The types can be specified in any format allowed by numpy.dtype."""
            return ['float32', 'float64']

        def is_supervised(self):
            return self.is_trainable()

        @classmethod
        def get_output_type(cls, input_type, as_string=True):
            if as_string:
                return "PredictionVector"
            else:
                return PredictionVector

        def store_state(self, result_dir, index=None):
            """ Stores *scikit_alg* """
            if self.store:
                node_dir = os.path.join(result_dir, self.__class__.__name__)
                create_directory(node_dir)
                name = "%s_sp%s.pickle" % ("Model", self.current_split)
                result_file = open(os.path.join(node_dir, name), "wb")
                result_file.write(cPickle.dumps(self.scikit_alg, protocol=2))
                result_file.close()
            super(ScikitPredictor,self).store_state(result_dir, index)

    # modify class name and docstring
    if "Regression" not in scikit_class.__name__ and \
            "Regressor" not in scikit_class.__name__:
        ScikitPredictor.__name__ = scikit_class.__name__ + \
            'RegressorSklearnNode'
    else:
        ScikitPredictor.__name__ = scikit_class.__name__ + 'SklearnNode'
    ScikitPredictor.__doc__ = _gen_docstring(scikit_class)

    # Class must be permanently accessible from module level
    globals()[ScikitPredictor.__name__] = ScikitPredictor

    # change the docstring of the methods to match the ones in sklearn

    # methods_dict maps ScikitPredictor method names to sklearn method names
    methods_dict = {'__init__': '__init__',
                    'stop_training': 'fit',
                    'execute': 'predict'}

    for pyspace_name, scikit_name in methods_dict.items():
        pyspace_method = getattr(ScikitPredictor, pyspace_name)
        scikit_method = getattr(scikit_class, scikit_name)
        if hasattr(scikit_method, 'im_func'):
            # some scikit algorithms do not define an __init__ method
            # the one inherited from 'object' is a
            # "<slot wrapper '__init__' of 'object' objects>"
            # which does not have a 'im_func' attribute
            pyspace_method.im_func.__doc__ = _gen_docstring(scikit_class, scikit_method.im_func)

    if scikit_class.__init__.__doc__ is None:
        ScikitPredictor.__init__.im_func.__doc__ = _gen_docstring(scikit_class)
    return ScikitPredictor

#list candidate nodes
def print_public_members(class_):
    """ Print methods of sklearn algorithm """
    print '\n', '-' * 15
    print '%s (%s)' % (class_.__name__, class_.__module__)
    for attr_name in dir(class_):
        attr = getattr(class_, attr_name)
        #print attr_name, type(attr)
        if not attr_name.startswith('_') and inspect.ismethod(attr):
            print ' -', attr_name

def wrap_scikit_algorithms(scikit_class, nodes_list):
    """ Check *scikit_class* and append new wrapped class to *nodes_list*

    Currently only classifiers subclassing ``sklearn.base.ClassifierMixin``
    and having a *fit* method were integrated and tested.
    Algorithms with the *transform* function are also available.
    *predict* nodes will be available soon but require more testing especially
    of regression in pySPACE.
    """

    class_name = scikit_class.__name__
    if (class_name[:4] == 'Base' or class_name == 'LinearModel'
            or class_name.startswith('EllipticEnvelop')
            or class_name.startswith('ForestClassifier')):
        return

    if sklearn.base.is_classifier(scikit_class) \
            and hasattr(scikit_class, 'fit'):
        nodes_list.append(wrap_scikit_classifier(scikit_class))
    elif sklearn.base.is_regressor(scikit_class) \
            and hasattr(scikit_class, 'fit'):
        # WARNING: Regression is not sufficiently tested in pySPACE
        nodes_list.append(wrap_scikit_predictor(scikit_class))
    # Some (abstract) transformers do not implement fit.
    elif hasattr(scikit_class, 'transform') and hasattr(scikit_class, 'fit'):
        nodes_list.append(wrap_scikit_transformer(scikit_class))

if _sklearn_prefix:
    scikit_nodes = []
    apply_to_scikit_algorithms(
        sklearn, lambda c: wrap_scikit_algorithms(c, scikit_nodes))
    # add scikit nodes to dictionary
    for wrapped_c in scikit_nodes:
        DEFAULT_NODE_MAPPING[wrapped_c.__name__] = wrapped_c
        NODE_MAPPING[wrapped_c.__name__] = wrapped_c
        NODE_MAPPING[wrapped_c.__name__[:-4]] = wrapped_c
    if not len(scikit_nodes) == 0:
        del(wrapped_c)

redpajama_set_name: RedPajamaGithub


text:
import unittest
from conans.test.utils.tools import TestClient
from conans.util.files import load
import os
from conans.model.ref import ConanFileReference, PackageReference

conanfile = """from conans import ConanFile

class TestConan(ConanFile):
    name = "%s"
    version = "0.1"
    exports = "*"
    def package(self):
        self.copy("*")
"""

class ImportTest(unittest.TestCase):
    def _set_up(self):
        client = TestClient()
        client.save({"conanfile.py": conanfile % "LibA",
                     "LICENSE.txt": "LicenseA"})
        client.run("export . lasote/testing")

        client.save({"conanfile.py": conanfile % "LibB" + "    requires='LibA/0.1@lasote/testing'",
                     "LICENSE.md": "LicenseB"}, clean_first=True)
        client.run("export . lasote/testing")

        client.save({"conanfile.py": conanfile % "LibC" + "    requires='LibB/0.1@lasote/testing'",
                     "license.txt": "LicenseC"}, clean_first=True)
        client.run("export . lasote/testing")
        return client

    def repackage_test(self):
        client = self._set_up()
        conanfile = """from conans import ConanFile
class TestConan(ConanFile):
    requires='LibC/0.1@lasote/testing'
    keep_imports = True
    def imports(self):
        self.copy("license*", dst="licenses", folder=True, ignore_case=True)

    def package(self):
        self.copy("*")
"""
        client.save({"conanfile.py": conanfile}, clean_first=True)
        client.run("create . Pkg/0.1@user/testing --build=missing")
        self.assertIn("Pkg/0.1@user/testing package(): Copied 1 '.md' files: LICENSE.md",
                      client.out)
        pkg_ref = PackageReference(ConanFileReference.loads("Pkg/0.1@user/testing"),
                                   "e6f2dac07251ad9958120a7f7c324366fb3b6f2a")
        pkg_folder = client.client_cache.package(pkg_ref)
        self.assertTrue(os.path.exists(os.path.join(pkg_folder, "licenses/LibA/LICENSE.txt")))
        self.assertTrue(os.path.exists(os.path.join(pkg_folder, "licenses/LibB/LICENSE.md")))
        self.assertTrue(os.path.exists(os.path.join(pkg_folder, "licenses/LibC/license.txt")))

    def imports_folders_test(self):
        client = self._set_up()

        testconanfile = conanfile % "LibD" + "    requires='LibC/0.1@lasote/testing'"
        testconanfile += """
    def imports(self):
        self.copy("license*", dst="licenses", folder=True, ignore_case=True)
        import os
        self.output.info("IMPORTED FOLDERS: %s " % sorted(os.listdir(self.imports_folder)))
"""
        client.save({"conanfile.py": testconanfile}, clean_first=True)
        client.run("install . --build=missing")
        self.assertIn("IMPORTED FOLDERS: [", client.user_io.out)
        self.assertEqual(load(os.path.join(client.current_folder, "licenses/LibA/LICENSE.txt")),
                         "LicenseA")
        self.assertEqual(load(os.path.join(client.current_folder, "licenses/LibB/LICENSE.md")),
                         "LicenseB")
        self.assertEqual(load(os.path.join(client.current_folder, "licenses/LibC/license.txt")),
                         "LicenseC")

    def imports_folders_txt_test(self):
        client = self._set_up()

        conanfile = """[requires]
LibC/0.1@lasote/testing
[imports]
., license* -> licenses @ folder=True, ignore_case=True, excludes=*.md # comment
"""
        client.save({"conanfile.txt": conanfile}, clean_first=True)
        client.run("install . --build=missing")
        self.assertEqual(load(os.path.join(client.current_folder, "licenses/LibA/LICENSE.txt")),
                         "LicenseA")
        self.assertFalse(os.path.exists(os.path.join(client.current_folder,
                                                     "licenses/LibB/LICENSE.md")))
        self.assertEqual(load(os.path.join(client.current_folder, "licenses/LibC/license.txt")),
                         "LicenseC")


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>

<handler-chains xmlns="http://java.sun.com/xml/ns/javaee">
    <handler-chain>
        <handler>
            <handler-class>registofatura.ws.handler.MessageHandler</handler-class>
        </handler>
    </handler-chain>
</handler-chains>


text:
@interface XJRequestConfig()
{
}
@end
@implementation XJRequestConfig
+ (instancetype)config {
    return [[[self class] alloc] init];
}

@end


text:
using System.Collections.ObjectModel;
using System.Threading;

namespace Indigo.Endeca.EacToolkit
{

    public abstract class EndecaServiceComponent<CType> : EndecaComponent<CType> where CType : ComponentType
    {
        public EndecaServiceComponent(CType component, EndecaApplication app) : base(component, app)
        {
        }

        /// <summary>
        /// Returns true if a component's status is Starting. Only makes sense for a service type components.
        /// </summary>
        public bool IsStarting
        {
            get { return Status.state == StateType.Starting; }
        }

        /// <summary>
        /// Pauses a thread until a component's status is Starting.
        /// </summary>
        public void WaitStarting()
        {
            while (IsStarting)
            {
                Thread.Sleep(waitInterval);
            }
        }
    }

    public class Forge : EndecaComponent<ForgeComponentType>
    {
        public Forge(ForgeComponentType component, EndecaApplication app) : base(component, app)
        {
        }
    }

    public class Dgidx : EndecaComponent<DgidxComponentType>
    {
        public Dgidx(DgidxComponentType component, EndecaApplication app) : base(component, app)
        {
        }

        public string OutputDir
        {
            get { return ResolveRelativePath(RemovePrefixNameFromDir(component.outputPrefix)); }
        }
    }

    public class Dgraph : EndecaServiceComponent<DgraphComponentType>
    {
        public Dgraph(DgraphComponentType component, EndecaApplication app) : base(component, app)
        {
        }

        public string InputDir
        {
            get { return ResolveRelativePath(RemovePrefixNameFromDir(component.inputPrefix)); }
        }

        /// <summary>
        /// Starts copying files from a given location to the Dgraph's working folder and waits until the operation is completed.
        /// </summary>
        /// <param name="fromPath">Source location</param>
        /// <returns>Operation BatchStatusType value.</returns>
        /// <exception cref="EndecaApplicationException">Throws an EndecaApplicationException if the operation has failed.</exception>
        public BatchStatusType FetchIndexFiles(string fromPath)
        {
            if (!fromPath.EndsWith("\\*"))
            {
                fromPath += "\\*";
            }
            string token = app.EacGateway.StartCopyFiles(app.AppId, Host, fromPath, Host, InputDir, false);
            return WaitBatchOperationComplete(token);
        }

        /// <summary>
        /// Move the current index's files to a backup folder. Cleans up the Dgraph working directory. Requires to stop Dgraph before
        /// invoking this method.
        /// </summary>
        /// <param name="numBackups"></param>
        public BatchStatusType Backup(int numBackups)
        {
            string token = app.EacGateway.StartBackupFiles(app.AppId, Host, InputDir, numBackups, BackupMethodType.Move);
            return WaitBatchOperationComplete(token);
        }

        protected BatchStatusType WaitBatchOperationComplete(string token)
        {
            while (true)
            {
                BatchStatusType status = app.EacGateway.GetUtilityStatus(app.AppId, token);
                if (status.state == StateType.NotRunning)
                {
                    return status;
                }
                if (status.state == StateType.Failed)
                {
                    throw new EndecaApplicationException(Id, status);
                }
                Thread.Sleep(WaitInterval);
            }
        }
    }

    public class DgraphCollection : KeyedCollection<string, Dgraph>
    {
        protected override string GetKeyForItem(Dgraph item)
        {
            return item.Id;
        }
    }
}


text:
package edu.uiowa.icts.safeseed.domain;

import java.util.Set;
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import javax.persistence.*;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Table;
import javax.persistence.Table;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.springframework.format.annotation.DateTimeFormat;
import org.hibernate.annotations.*;
import javax.persistence.CascadeType;
import edu.uiowa.icts.*;

/* Generated by Protogen - www.icts.uiowa.edu/protogen
 * @date 2011/04/26 15:23:46
*/

@Entity(name="edu_uiowa_icts_safeseed_domain_searchStatus")
@Table(name = "search_status", schema="safeseed")
public class SearchStatus
{
        private String searchSeq;
        private String searchSeqFull;
        private Integer status;
        @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date entryTime;
        @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date checkoutTime;
        @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date finishTime;
        private Integer readCount;
        private Set<SearchResult> searchResults = new HashSet<SearchResult>(0);

    public SearchStatus()    {
        this.searchSeq = "";
        this.searchSeqFull = "";
        this.status = null;
        this.entryTime = null;
        this.checkoutTime = null;
        this.finishTime = null;
        this.readCount = null;
        this.searchResults = new HashSet<SearchResult>(0);
    }

    public SearchStatus(String searchSeq, String searchSeqFull, Integer status, Date entryTime, Date checkoutTime, Date finishTime, Integer readCount, Set<SearchResult> searchResults)
    {
        this.searchSeq = searchSeq;
        this.searchSeqFull = searchSeqFull;
        this.status = status;
        this.entryTime = entryTime;
        this.checkoutTime = checkoutTime;
        this.finishTime = finishTime;
        this.readCount = readCount;
        this.searchResults = searchResults;
    }

    /*****searchSeq*****/
    @Id
    @Column(name = "search_seq", unique = true, nullable = false)
    public String getSearchSeq()
    {
        return searchSeq;
    }

    public void setSearchSeq(String searchSeq)
    {
        this.searchSeq = searchSeq;
    }

    /*****searchSeqFull*****/
    @Column(name = "search_seq_full")
    public String getSearchSeqFull()
    {
        return searchSeqFull;
    }

    public void setSearchSeqFull(String searchSeqFull)
    {
        this.searchSeqFull = searchSeqFull;
    }

    /*****status*****/
    @Column(name = "status")
    public Integer getStatus()
    {
        return status;
    }

    public void setStatus(Integer status)
    {
        this.status = status;
    }

    /*****entryTime*****/
    @Column(name = "entry_time")
    public Date getEntryTime()
    {
        return entryTime;
    }

    public void setEntryTime(Date entryTime)
    {
        this.entryTime = entryTime;
    }

    public void setEntryTime(String entryTime)
    {
        try{
        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        formatter.setLenient(true);        this.entryTime = formatter.parse(entryTime);
        } catch (ParseException e) {e.printStackTrace();}
    }

    /*****checkoutTime*****/
    @Column(name = "checkout_time")
    public Date getCheckoutTime()
    {
        return checkoutTime;
    }

    public void setCheckoutTime(Date checkoutTime)
    {
        this.checkoutTime = checkoutTime;
    }

    public void setCheckoutTime(String checkoutTime)
    {
        try{
        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        formatter.setLenient(true);        this.checkoutTime = formatter.parse(checkoutTime);
        } catch (ParseException e) {e.printStackTrace();}
    }

    /*****finishTime*****/
    @Column(name = "finish_time")
    public Date getFinishTime()
    {
        return finishTime;
    }

    public void setFinishTime(Date finishTime)
    {
        this.finishTime = finishTime;
    }

    public void setFinishTime(String finishTime)
    {
        try{
        DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        formatter.setLenient(true);        this.finishTime = formatter.parse(finishTime);
        } catch (ParseException e) {e.printStackTrace();}
    }

    /*****readCount*****/
    @Column(name = "read_count")
    public Integer getReadCount()
    {
        return readCount;
    }

    public void setReadCount(Integer readCount)
    {
        this.readCount = readCount;
    }

    /*****searchResults*****/
    @OneToMany(fetch = FetchType.LAZY,   mappedBy = "searchStatus", targetEntity=SearchResult.class, cascade=CascadeType.REMOVE)
    public Set<SearchResult> getSearchResults()
    {
        return searchResults;
    }

    public void setSearchResults(Set<SearchResult> searchResults)
    {
        this.searchResults = searchResults;
    }

}


text:
function ex_link(original, target, linkpath, bSilent)

  local ok, reason = original(target, linkpath);
  if (not ok) then
    return reason;
  end

  if (not bSilent) then
    --print("local psym = require('persisted_symlinks');");
    --print("psym.storeLink(target, linkpath);");
  end

  return ok, reason;
end

function ex_remove(original, path)

  local ok, reason = original(path);
  if (not ok) then
    return reason;
  end

  if (bLink) then
    --print("local psym = require('persisted_symlinks');");
    --print("psym.removeLink(path);");
  end

  return ok, reason;
end

local hijack = require("hijack")
hijack.load("filesystem", "link", ex_link);
return hijack.load("filesystem", "remove", ex_remove);


text:
import os, sys
import collections
import itertools
import queue
import threading
import time

from ..core import config, exc, logging
log = logging.logger(__package__)
from . import remote
from ..sensors import ultrasonic

class Controller(remote.Controller):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.started = False

    def dispatch(self, action, params):
        if not self.started and action not in ("start", "stop"):
            log.warn("Cannot dispatch %s : %s when not yet started", action, ", ".join(params))
        else:
           super().dispatch(action, params)

    def drive(self):
        self.robot.forward(stop_after_secs=4.5)
        time.sleep(1)
        self.robot.turn(direction="left", extent=0.3, stop_after_secs=2)
        time.sleep(1)
        self.robot.backward(stop_after_secs=2.0)
        time.sleep(1)
        self.robot.turn(direction="right", extent=0.3, stop_after_secs=2)
        time.sleep(1)
        self.robot.forward(stop_after_secs=3.0)
        sys.exit()

    def handle_start(self):
        self.started = True
        self.drive()

    def handle_stop(self):
        self.robot.stop()
        self.started = False


text:
module RailsAdminHasManyNested
  VERSION = "0.0.8"
end


text:
package rere.ql.data

case class IndexCreationResult(created: Long)


text:
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import unittest
from config import *
from youku import YoukuOauth

class OauthTest(unittest.TestCase): pass
    # TODO

if __name__ == '__main__':
    unittest.main()


text:
#pragma once
#include <aws/ecs/ECS_EXPORTS.h>
#include <aws/ecs/model/UlimitName.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace ECS
{
namespace Model
{

  /**
   *
The ulimit settings to pass to the container.

See
   * Also:
   AWS API
   * Reference

   */
  class AWS_ECS_API Ulimit
  {
  public:
    Ulimit();
    Ulimit(Aws::Utils::Json::JsonView jsonValue);
    Ulimit& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The type of the ulimit.

     */
    inline const UlimitName& GetName() const{ return m_name; }

    /**
     *
The type of the ulimit.

     */
    inline bool NameHasBeenSet() const { return m_nameHasBeenSet; }

    /**
     *
The type of the ulimit.

     */
    inline void SetName(const UlimitName& value) { m_nameHasBeenSet = true; m_name = value; }

    /**
     *
The type of the ulimit.

     */
    inline void SetName(UlimitName&& value) { m_nameHasBeenSet = true; m_name = std::move(value); }

    /**
     *
The type of the ulimit.

     */
    inline Ulimit& WithName(const UlimitName& value) { SetName(value); return *this;}

    /**
     *
The type of the ulimit.

     */
    inline Ulimit& WithName(UlimitName&& value) { SetName(std::move(value)); return *this;}

    /**
     *
The soft limit for the ulimit type.

     */
    inline int GetSoftLimit() const{ return m_softLimit; }

    /**
     *
The soft limit for the ulimit type.

     */
    inline bool SoftLimitHasBeenSet() const { return m_softLimitHasBeenSet; }

    /**
     *
The soft limit for the ulimit type.

     */
    inline void SetSoftLimit(int value) { m_softLimitHasBeenSet = true; m_softLimit = value; }

    /**
     *
The soft limit for the ulimit type.

     */
    inline Ulimit& WithSoftLimit(int value) { SetSoftLimit(value); return *this;}

    /**
     *
The hard limit for the ulimit type.

     */
    inline int GetHardLimit() const{ return m_hardLimit; }

    /**
     *
The hard limit for the ulimit type.

     */
    inline bool HardLimitHasBeenSet() const { return m_hardLimitHasBeenSet; }

    /**
     *
The hard limit for the ulimit type.

     */
    inline void SetHardLimit(int value) { m_hardLimitHasBeenSet = true; m_hardLimit = value; }

    /**
     *
The hard limit for the ulimit type.

     */
    inline Ulimit& WithHardLimit(int value) { SetHardLimit(value); return *this;}

  private:

    UlimitName m_name;
    bool m_nameHasBeenSet;

    int m_softLimit;
    bool m_softLimitHasBeenSet;

    int m_hardLimit;
    bool m_hardLimitHasBeenSet;
  };

} // namespace Model
} // namespace ECS
} // namespace Aws


text:
Web application based around managing IT staff who are on call: managing shifts and organizing paging

# Installation
Clone this repository and run:
1. `yarn install`
1. `bundle install`

This will install all the dependencies required to run this application.

# Running
1. Ensure application dependencies are up to date `yarn install && bundle install`
1. Update the databse `rake db:migrate`
1. Start rails server `rails s`
1. Start webpack server `yarn start`
1. Navigate to `http://localhost:3000` to see application in progress

# License
TBD...


text:
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>{{ page.title }} | MAEC Project Documentation</title>
    <meta name="viewport" content="width=device-width">

    <!-- bootstrap CSS -->
    <link rel="stylesheet" href="{{site.root}}/css/bootstrap.min.css">

    <!-- syntax highlighting CSS -->
    <link rel="stylesheet" href="{{site.root}}/css/syntax.css">

    <!-- Custom CSS -->
    <link rel="stylesheet" href="{{site.root}}/css/main.css">

    <script type="text/javascript">
      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-35243969-1']);
      _gaq.push(['_setDomainName', 'maecproject.github.io'])
      _gaq.push(['_trackPageview']);

      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();
    </script>

</head>


text:
#include "tensorflow/c/checkpoint_reader.h"

#include <unordered_set>

#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/saved_tensor_slice_util.h"

namespace tensorflow {

namespace checkpoint {

class TensorSliceReader;

CheckpointReader::CheckpointReader(const string& filename,
                                   TF_Status* out_status)
    : reader_(nullptr), v2_reader_(nullptr), var_to_shape_map_ptr_(nullptr) {
  // Depending on whether this is a V2 ckpt, initializes "reader_" or
  // "v2_reader_".
  std::vector<string> v2_path;
  if (Env::Default()->GetMatchingPaths(MetaFilename(filename), &v2_path).ok() &&
      !v2_path.empty()) {
    v2_reader_ =
        new BundleReader(Env::Default(), filename /* prefix to a V2 ckpt */);
    if (!v2_reader_->status().ok()) {
      Set_TF_Status_from_Status(out_status, v2_reader_->status());
      return;
    }
    var_to_shape_map_ptr_ = BuildV2VarToShapeMap();
  } else {
    reader_ = new TensorSliceReader(filename);
    if (!reader_->status().ok()) {
      Set_TF_Status_from_Status(out_status, reader_->status());
      return;
    }
    var_to_shape_map_ptr_ =
        new TensorSliceReader::VarToShapeMap(reader_->GetVariableToShapeMap());
  }
}

CheckpointReader::~CheckpointReader() {
  delete var_to_shape_map_ptr_;
  delete reader_;
  delete v2_reader_;
}

bool CheckpointReader::HasTensor(const string& name) const {
  if (reader_ != nullptr) {
    return reader_->HasTensor(name, nullptr, nullptr);
  }
  return v2_reader_->Contains(name);
}

const TensorSliceReader::VarToShapeMap&
CheckpointReader::GetVariableToShapeMap() const {
  CHECK(var_to_shape_map_ptr_);
  return *var_to_shape_map_ptr_;
}

const string CheckpointReader::DebugString() const {
  if (reader_ != nullptr) return reader_->DebugString();
  return v2_reader_->DebugString();
}

void CheckpointReader::GetTensor(
    const string& name, std::unique_ptr<tensorflow::Tensor>* out_tensor,
    TF_Status* out_status) const {
  Status status;
  if (reader_ != nullptr) {
    status = reader_->GetTensor(name, out_tensor);
  } else {
    tensorflow::DataType dtype;
    tensorflow::TensorShape shape;
    status = v2_reader_->LookupDtypeAndShape(name, &dtype, &shape);
    if (status.ok()) {
      out_tensor->reset(new Tensor(dtype, shape));
      status = v2_reader_->Lookup(name, out_tensor->get());
      if (!status.ok()) out_tensor->reset();
    }
  }
  if (!status.ok()) {
    Set_TF_Status_from_Status(out_status, status);
  }
}

TensorSliceReader::VarToShapeMap* CheckpointReader::BuildV2VarToShapeMap() {
  CHECK(v2_reader_ != nullptr);
  CHECK(v2_reader_->status().ok());

  // First pass: filters out the entries of the slices.
  std::unordered_set<string> filtered_keys;
  BundleEntryProto entry;
  v2_reader_->Seek(kHeaderEntryKey);
  for (v2_reader_->Next(); v2_reader_->Valid(); v2_reader_->Next()) {
    CHECK(entry.ParseFromArray(v2_reader_->value().data(),
                               v2_reader_->value().size()))
        << entry.InitializationErrorString();
    for (int i = 0; i < entry.slices_size(); ++i) {
      const auto& slice_proto = entry.slices(i);
      CHECK(filtered_keys
                .insert(EncodeTensorNameSlice(
                    v2_reader_->key().ToString() /* full var's name */,
                    TensorSlice(slice_proto)))
                .second);
    }
  }

  // Second pass: adds the entries, ignoring the filtered keys.
  TensorSliceReader::VarToShapeMap* var_to_shape_map =
      new TensorSliceReader::VarToShapeMap;
  v2_reader_->Seek(kHeaderEntryKey);
  for (v2_reader_->Next(); v2_reader_->Valid(); v2_reader_->Next()) {
    if (filtered_keys.count(v2_reader_->key().ToString()) > 0) continue;
    CHECK(entry.ParseFromArray(v2_reader_->value().data(),
                               v2_reader_->value().size()))
        << entry.InitializationErrorString();
    (*var_to_shape_map)[v2_reader_->key().ToString()] =
        TensorShape(entry.shape());
  }
  return var_to_shape_map;  // Owned by caller.
}

}  // namespace checkpoint
}  // namespace tensorflow


text:
using UnityEngine;

public class Foo : MonoBehaviour
{
  public void Whatever()
  {
    StartCoroutine("MyCorout{caret}ine", 10f);
  }
}


text:
Pattern: Use of non-contextual decorator

Issue: -

## Description

Some decorators should only be used in certain class types. For example, the decorator `@Input()` should not be used in a class decorated with `@Injectable()`.

## Further Reading

* [TSLint - contextual-decorator](http://codelyzer.com/rules/contextual-decorator/)


text:
using std::string;
using std::tr1::shared_ptr;
using std::vector;

namespace chromeos_update_engine {

void Subprocess::GChildExitedCallback(GPid pid, gint status, gpointer data) {
  SubprocessRecord* record = reinterpret_cast<SubprocessRecord*>(data);

  // Make sure we read any remaining process output. Then close the pipe.
  GStdoutWatchCallback(record->gioout, G_IO_IN, &record->stdout);
  int fd = g_io_channel_unix_get_fd(record->gioout);
  g_source_remove(record->gioout_tag);
  g_io_channel_unref(record->gioout);
  close(fd);

  g_spawn_close_pid(pid);
  gint use_status = status;
  if (WIFEXITED(status))
    use_status = WEXITSTATUS(status);

  if (status) {
    LOG(INFO) << "Subprocess status: " << use_status;
  }
  if (!record->stdout.empty()) {
    LOG(INFO) << "Subprocess output:\n" << record->stdout;
  }
  if (record->callback) {
    record->callback(use_status, record->stdout, record->callback_data);
  }
  Get().subprocess_records_.erase(record->tag);
}

void Subprocess::GRedirectStderrToStdout(gpointer user_data) {
  dup2(1, 2);
}

gboolean Subprocess::GStdoutWatchCallback(GIOChannel* source,
                                          GIOCondition condition,
                                          gpointer data) {
  string* stdout = reinterpret_cast<string*>(data);
  char buf[1024];
  gsize bytes_read;
  while (g_io_channel_read_chars(source,
                                 buf,
                                 arraysize(buf),
                                 &bytes_read,
                                 NULL) == G_IO_STATUS_NORMAL &&
         bytes_read > 0) {
    stdout->append(buf, bytes_read);
  }
  return TRUE;  // Keep the callback source. It's freed in GChilExitedCallback.
}

namespace {
void FreeArgv(char** argv) {
  for (int i = 0; argv[i]; i++) {
    free(argv[i]);
    argv[i] = NULL;
  }
}

void FreeArgvInError(char** argv) {
  FreeArgv(argv);
  LOG(ERROR) << "Ran out of memory copying args.";
}

// Note: Caller responsible for free()ing the returned value!
// Will return NULL on failure and free any allocated memory.
char** ArgPointer() {
  const char* keys[] = {"LD_LIBRARY_PATH", "PATH"};
  char** ret = new char*[arraysize(keys) + 1];
  int pointer = 0;
  for (size_t i = 0; i < arraysize(keys); i++) {
    if (getenv(keys[i])) {
      ret[pointer] = strdup(StringPrintf("%s=%s", keys[i],
                                         getenv(keys[i])).c_str());
      if (!ret[pointer]) {
        FreeArgv(ret);
        delete [] ret;
        return NULL;
      }
      ++pointer;
    }
  }
  ret[pointer] = NULL;
  return ret;
}

class ScopedFreeArgPointer {
 public:
  ScopedFreeArgPointer(char** arr) : arr_(arr) {}
  ~ScopedFreeArgPointer() {
    if (!arr_)
      return;
    for (int i = 0; arr_[i]; i++)
      free(arr_[i]);
    delete[] arr_;
  }
 private:
  char** arr_;
  DISALLOW_COPY_AND_ASSIGN(ScopedFreeArgPointer);
};
}  // namespace {}

uint32_t Subprocess::Exec(const vector<string>& cmd,
                          ExecCallback callback,
                          void* p) {
  GPid child_pid;
  scoped_array<char*> argv(new char*[cmd.size() + 1]);
  for (unsigned int i = 0; i < cmd.size(); i++) {
    argv[i] = strdup(cmd[i].c_str());
    if (!argv[i]) {
      FreeArgvInError(argv.get());  // NULL in argv[i] terminates argv.
      return 0;
    }
  }
  argv[cmd.size()] = NULL;

  char** argp = ArgPointer();
  if (!argp) {
    FreeArgvInError(argv.get());  // NULL in argv[i] terminates argv.
    return 0;
  }
  ScopedFreeArgPointer argp_free(argp);

  shared_ptr<SubprocessRecord> record(new SubprocessRecord);
  record->callback = callback;
  record->callback_data = p;
  gint stdout_fd = -1;
  bool success = g_spawn_async_with_pipes(
      NULL,  // working directory
      argv.get(),
      argp,
      G_SPAWN_DO_NOT_REAP_CHILD,  // flags
      GRedirectStderrToStdout,  // child setup function
      NULL,  // child setup data pointer
      &child_pid,
      NULL,
      &stdout_fd,
      NULL,
      NULL);
  FreeArgv(argv.get());
  if (!success) {
    LOG(ERROR) << "g_spawn_async failed";
    return 0;
  }
  record->tag =
      g_child_watch_add(child_pid, GChildExitedCallback, record.get());
  subprocess_records_[record->tag] = record;

  // Capture the subprocess output.
  record->gioout = g_io_channel_unix_new(stdout_fd);
  g_io_channel_set_encoding(record->gioout, NULL, NULL);
  LOG_IF(WARNING,
         g_io_channel_set_flags(record->gioout, G_IO_FLAG_NONBLOCK, NULL) !=
         G_IO_STATUS_NORMAL) << "Unable to set non-blocking I/O mode.";
  record->gioout_tag = g_io_add_watch(
      record->gioout,
      static_cast<GIOCondition>(G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP),
      GStdoutWatchCallback,
      &record->stdout);
  return record->tag;
}

void Subprocess::CancelExec(uint32_t tag) {
  subprocess_records_[tag]->callback = NULL;
}

bool Subprocess::SynchronousExecFlags(const vector<string>& cmd,
                                      GSpawnFlags flags,
                                      int* return_code,
                                      string* stdout) {
  if (stdout) {
    *stdout = "";
  }
  GError* err = NULL;
  scoped_array<char*> argv(new char*[cmd.size() + 1]);
  for (unsigned int i = 0; i < cmd.size(); i++) {
    argv[i] = strdup(cmd[i].c_str());
    if (!argv[i]) {
      FreeArgvInError(argv.get());  // NULL in argv[i] terminates argv.
      return false;
    }
  }
  argv[cmd.size()] = NULL;

  char** argp = ArgPointer();
  if (!argp) {
    FreeArgvInError(argv.get());  // NULL in argv[i] terminates argv.
    return false;
  }
  ScopedFreeArgPointer argp_free(argp);

  char* child_stdout;
  bool success = g_spawn_sync(
      NULL,  // working directory
      argv.get(),
      argp,
      static_cast<GSpawnFlags>(G_SPAWN_STDERR_TO_DEV_NULL |
                               G_SPAWN_SEARCH_PATH | flags),  // flags
      GRedirectStderrToStdout,  // child setup function
      NULL,  // data for child setup function
      &child_stdout,
      NULL,
      return_code,
      &err);
  FreeArgv(argv.get());
  LOG_IF(INFO, err) << utils::GetAndFreeGError(&err);
  if (child_stdout) {
    if (stdout) {
      *stdout = child_stdout;
    } else if (*child_stdout) {
      LOG(INFO) << "Subprocess output:\n" << child_stdout;
    }
    g_free(child_stdout);
  }
  return success;
}

bool Subprocess::SynchronousExec(const std::vector<std::string>& cmd,
                                 int* return_code,
                                 std::string* stdout) {
  return SynchronousExecFlags(cmd,
                              static_cast<GSpawnFlags>(0),
                              return_code,
                              stdout);
}

bool Subprocess::SubprocessInFlight() {
  for (std::map<int, shared_ptr<SubprocessRecord> >::iterator it =
           subprocess_records_.begin();
       it != subprocess_records_.end(); ++it) {
    if (it->second->callback)
      return true;
  }
  return false;
}

Subprocess* Subprocess::subprocess_singleton_ = NULL;

}  // namespace chromeos_update_engine


text:
<?xml version="1.0" encoding="UTF-8"?>
<app:root xmlns:app="http://ui.purelib.chav1961/">
	<app:i18n location="i18n:xml:root://chav1961.purelib.ui.html.HtmlUtils/chav1961/purelib/i18n/localization.xml"/>
	<app:menu id="mainmenu">
		<app:submenu name="menu.file" caption="testSet1" tooltip="testSet2">
			<app:item name="menu.file.new" caption="testSet3" tooltip="testSet2" action="testAction"/>
		</app:submenu>
	</app:menu>
</app:root>


text:
package org.apache.lens.server.api.util;

import java.io.IOException;

import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * Tests for lens util
 */
public class TestLensUtil {

  @Test
  public void testExceptionCauseMessage() {
    Throwable th = null;

    try {
      try {
        throw new IOException("base cause");
      } catch (IOException e) {
        throw new RuntimeException("run time exception", e);
      }
    } catch (Exception e) {
      th = e;
    }
    Assert.assertEquals(LensUtil.getCauseMessage(th), "base cause");

    // no message in base exception
    try {
      try {
        throw new IOException();
      } catch (IOException e) {
        throw new RuntimeException("run time exception", e);
      }
    } catch (Exception e) {
      th = e;
    }
    Assert.assertEquals(LensUtil.getCauseMessage(th), "run time exception");
  }
}


text:
package repo

import (
	"errors"

	g2g "github.com/libgit2/git2go"
)

var (
	// ErrNetwork represents any type of network error.
	ErrNetwork = errors.New("network error")

	// ErrNoSpace represents a space storage error.
	ErrNoSpace = errors.New("no space left on device")
)

// g2gErrorToRepoError returns a repo error when given a git2go error if it
// it finds a corresponding match or simply the given error otherwise.
// TODO when git2go adds support for ENOSPC type of error, update this method
// accordingly to return ErrNoSpace.
func g2gErrorToRepoError(err error) error {
	if g2g.IsErrorClass(err, g2g.ErrClassNet) {
		return ErrNetwork
	}
	return err
}


text:
#include <stdio.h>
#include <string.h>
#include "mcfio_Sequential.h"
#include <string.h>
#include <sys/param.h>
#include <rpc/types.h>
#include <sys/types.h>
#include <rpc/xdr.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>
#ifdef SUNOS
#include <floatingpoint.h>
#else /* SUNOS */
#include <float.h>
#endif /* SUNOS */
#include "mcf_xdr.h"
#include "mcfio_Dict.h"
#include "mcfio_Util1.h"
#include "mcfio_Sequential.h"
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
#define INITIATE 3

int mcfioC_OpenReadSequential(char *device, char *vsn, int filenumber)
{
   int i, jstr, idtmp, ntot, ll, iost, jfn, ldat, lrdat;
   u_int p1, p2;
   mcfStream *str;
   char *fileRbio;
/*
** Prolog, as in mcfio_Direct
*/
  if (McfStreamPtrList == NULL) mcfioC_Init();
  if (McfNumOfStreamActive >= MCF_STREAM_NUM_MAX) {
     fprintf(stderr,
  " mcfio_OpenReadSequential: Too many streams opened simultaneously.\n");
     return -1;
   }
/*
** Check that this device is not already in used, if so, check that the
**  status is MCFIO_EOF, if so, assign the jstr to that stream.
*/
   for (i=0, jstr = -1; i<McfNumOfStreamActive; i++) {
       if (McfStreamPtrList[i] != NULL) {
           str = McfStreamPtrList[i];
           if ((str->row == MCFIO_READ) && (str->dos == MCFIO_SEQUENTIAL)) {
              if (strcmp(device, str->device) == 0) {
                  if (str->status != MCFIO_EOF)
                      mcfioC_CloseSequentialFile((i+1));
                  jstr = i;
              }
           }
       }
   }
   while ((jstr == -1) && (i<MCF_STREAM_NUM_MAX)) {
          if (McfStreamPtrList[i] == NULL) jstr=i;
          i++;
          }
   if(jstr == -1) {
     fprintf(stderr,
  " mcfio_OpenReadSequential: Internal error, please report \n");
     return -1;
   }
/*
** building the filename string for rbio.  Note that we do not repeat the
** label if the device has already been opened prior to this call.
**
*/
   jfn = jstr+1;
   if (McfStreamPtrList[jstr] == NULL) {
       ll = strlen(device) + strlen(vsn) + 40;
       fileRbio = (char *) malloc (sizeof(char)*ll);
       if (strcmp(vsn,"None") == 0)
           sprintf(fileRbio,"%s:S=%d",
               device, filenumber);
        else if (strcmp(vsn,"Disk") == 0)
           sprintf(fileRbio,"%s:UFORT", device);
        else
           sprintf(fileRbio,"%s:VSN=%s:S=%d",
               device, vsn, filenumber);
       ll = strlen(fileRbio);
       rbfopen_(&jfn, fileRbio, "R", &iost, ll, 1);
   } else {
       ll = strlen(device) + 12;
       fileRbio = (char *) malloc (sizeof(char)*ll);
       sprintf(fileRbio,"%s:S=%d", device, filenumber);
       ll = strlen(fileRbio);
       rbopen_(&jfn, fileRbio, &iost, ll, 1);
   }
   free(fileRbio);
   if (iost != 0) {
           fprintf(stderr,
 " mcfio_OpenReadSequential: Problem opening device %s, \
 VSN %s, file %d \n", device, vsn, filenumber);
     return -1;
   }

   if (McfStreamPtrList[jstr] == NULL) {
      McfStreamPtrList[jstr] = (mcfStream *) malloc(sizeof(mcfStream));
      str = McfStreamPtrList[jstr];
      str->xdr = (XDR *) malloc(sizeof(XDR));
      str->id = jstr+1;
      str->row = MCFIO_READ;
      str->dos = MCFIO_SEQUENTIAL;
      str->filename = NULL;
      str->filePtr = 0;
      ll = strlen(device) + 1;
      str->device = (char*) malloc(sizeof(char) * ll);
      strcpy(str->device, device);
      str->filenumber = filenumber;
      ll = strlen(vsn) + 1;
      str->vsn = (char*) malloc(sizeof(char) * ll);
      strcpy(str->vsn, vsn);
      str->minlrec = MCF_XDR_MINLREC;
      if (strcmp(vsn,"Disk") == 0)
          ll = MCF_XDR_MAXLREC;
      else
         rblklen_(&jfn, &ll, &iost);
      str->maxlrec = ll;
      str->shead = NULL;
      str->ehead = NULL;
      str->fhead = NULL;
      str->table = NULL;
      str->buffer = NULL;
      str->buffer2 = NULL;
    } else {
      str->filenumber = filenumber;
      str->minlrec = MCF_XDR_MINLREC;
      rblklen_(&jfn, &ll, &iost);
      str->maxlrec = ll;
      str->bufferSize = 0;
      if (str->buffer != NULL) free(str->buffer);
      if (str->buffer2 != NULL) free(str->buffer2);
    }
    str->numWordsC = 0;
    str->numWordsT = 0;
/*
** decode the first buffer, the Sequential header.
*/
   if (str->buffer == NULL) {
       str->bufferSize = str->maxlrec;
       str->buffer = (char *) malloc(sizeof(char) * (str->maxlrec + 1));
   }
   ldat = str->maxlrec;
   rbread_(&jfn, str->buffer, &ldat, &lrdat, &iost);
   if (iost != 0) {
     fprintf(stderr,
 " mcfio_OpenReadSequential: Problem reading first record on \n device %s, \
 VSN %s, file %d \n", device, vsn, filenumber);
     mcfioC_FreeStream(&McfStreamPtrList[jstr]);
     rbfclose_(&jfn, &iost);
     return -1;
   }
   str->numWordsT += lrdat/4;
   xdrmem_create(str->xdr, str->buffer, str->maxlrec, XDR_DECODE);
   p1 = xdr_getpos(str->xdr);
   str->firstPos = p1;
   str->status = MCFIO_BOF;

   if (xdr_mcfast_fileheader(str->xdr, &idtmp,
                &ntot, McfGenericVersion, &(str->fhead), str->id) == FALSE) {
       fprintf (stderr,
               "mcfio_OpenReadSequential: Unable to decode seqheader \n");
       mcfioC_FreeStream(&McfStreamPtrList[jstr]);
       rbfclose_(&jfn, &iost);
       return -1;
   }
   if (idtmp != FILEHEADER) {
       fprintf (stderr,
            "mcfio_OpenReadSequential: First Structure not the file header \n");

       fprintf (stderr,
            "                    : Further accesses probably suspicious \n");
       mcfioC_FreeStream(&McfStreamPtrList[jstr]);
       rbfclose_(&jfn, &iost);
       return -1;
   }
   xdr_setpos(str->xdr, p1);
   str->currentPos = p1;
   str->numWordsC += (ntot/4);
   str->status = MCFIO_RUNNING;
   if (str->ehead == NULL)
       str->ehead = (mcfxdrEventHeader *) malloc(sizeof(mcfxdrEventHeader));
   str->ehead->dimBlocks = str->fhead->nBlocks;
   str->ehead->blockIds = NULL;
   str->ehead->ptrBlocks = NULL;
   str->ehead->dimNTuples = str->fhead->nNTuples;
   str->ehead->nTupleIds = NULL;
   str->ehead->ptrNTuples = NULL;
   McfNumOfStreamActive++;
   return (jstr+1);

}

int mcfioC_OpenWriteSequential(char *device, char *vsn, char *title,
             char *comment, int numevts_pred,
              int *blkIds, unsigned int nBlocks)
{
   int i, jstr, idtmp, ntot, ll, iost, jfn, ldat, lwdat, filenumber;
   u_int p1, p2;
   mcfStream *str;
   char *fileRbio;
/*
** Prolog, as in mcfio_Direct
*/
  if (McfStreamPtrList == NULL) {
     fprintf(stderr,
" mcfio_OpenWriteSequential: We will first initialize by calling mcfio_Init.\n");
     mcfioC_Init();
  }
  if (McfNumOfStreamActive >= MCF_STREAM_NUM_MAX) {
     fprintf(stderr,
  " mcfio_OpenWriteSequential: Too many streams opened simultaneously.\n");
     return -1;
   }
/*
** Check that this device is not already in used, if so, check that the
**  status is MCFIO_EOF, if so, assign the jstr to that stream.
*/
   for (i=0, jstr = -1; i<McfNumOfStreamActive; i++) {
       if (McfStreamPtrList[i] != NULL) {
           str = McfStreamPtrList[i];
           if ((str->row == MCFIO_WRITE) && (str->dos == MCFIO_SEQUENTIAL)) {
              if (strcmp(device, str->device) == 0) {
                  if (str->status != MCFIO_EOF)
                      mcfioC_CloseSequentialFile((i+1));
                  jstr = i;
              }
           }
       }
   }
   while ((jstr == -1) && (i<MCF_STREAM_NUM_MAX)) {
          if (McfStreamPtrList[i] == NULL) jstr=i;
          i++;
          }
   if(jstr == -1) {
     fprintf(stderr,
  " mcfio_OpenWriteSequential: Internal error, please report \n");
     return -1;
   }
   if ((title != NULL) && (strlen(title) > 255)) {
     fprintf(stderr,
  " mcfio_OpenWriteSequential: Title is too long\n");
     return -1;
   }

   if ((comment != NULL) && (strlen(comment) > 255)) {
     fprintf(stderr,
  " mcfio_OpenWriteSequential: comment is too long\n");
     return -1;
   }

/*
** building the filename string for rbio
*/
   jfn = jstr+1;
   lwdat = MCF_XDR_MAXLREC;
   if (McfStreamPtrList[jstr] == NULL) {
       filenumber = 1;
       ll = strlen(device) + strlen(vsn) + 80; /* more than 10 digits for
                                               ** filenumber block length O.K.
                                               */
       fileRbio = (char *) malloc (sizeof(char)*ll);
       if (strcmp(vsn,"None") == 0)
           sprintf(fileRbio,"%s:D=mcfio_%d.dat:S=%d:F=U:B=%d",
               device, filenumber, filenumber, lwdat);
        else if (strcmp(vsn,"Disk") == 0)
           sprintf(fileRbio,"%s:UFORT", device);
        else
           sprintf(fileRbio,"%s:D=mcfio_%d.dat:VSN=%s:S=%d:F=U:B=%d",
               device, filenumber,vsn, filenumber, lwdat);
       ll = strlen(fileRbio);
       rbfopen_(&jfn, fileRbio, "W", &iost, ll, 1);
   } else {
       str->filenumber++;
       filenumber = str->filenumber;
       ll = strlen(device) + 80;
       fileRbio = (char *) malloc (sizeof(char)*ll);
       sprintf(fileRbio,"%s:D=mcfio_%d.dat:S=%d:F=U:B=%d",
                device, filenumber, filenumber, lwdat);
       ll = strlen(fileRbio);
       rbopen_(&jfn, fileRbio, &iost, ll, 1);
   }
   free(fileRbio);
   if (iost != 0) {
           fprintf(stderr,
 " mcfio_OpenWriteSequential: \n\
    Problem opening device %s, \
 VSN %s, file %d, Rbio status =  \n", device, vsn, filenumber, iost);
     return -1;
   }

   if (McfStreamPtrList[jstr] == NULL) {
      McfStreamPtrList[jstr] = (mcfStream *) malloc(sizeof(mcfStream));
      str = McfStreamPtrList[jstr];
      str->xdr = (XDR *) malloc(sizeof(XDR));
      str->id = jstr+1;
      str->row = MCFIO_WRITE;
      str->dos = MCFIO_SEQUENTIAL;
      str->filename = NULL;
      str->filePtr = 0;
      ll = strlen(device) + 1;
      str->device = (char*) malloc(sizeof(char) * ll);
      strcpy(str->device, device);
      ll = strlen(vsn) + 1;
      str->vsn = (char*) malloc(sizeof(char) * ll);
      strcpy(str->vsn, vsn);
      str->filenumber = 1;
      str->minlrec = MCF_XDR_MINLREC;
      if (strcmp(vsn,"Disk") == 0)
          ll = MCF_XDR_MAXLREC;
      else
         rblklen_(&jfn, &ll, &iost);
      str->maxlrec = ll;
      str->shead = NULL;
      str->ehead = NULL;
      str->fhead = NULL;
      str->table = NULL;
      str->buffer = NULL;
      str->buffer2 = NULL;
    } else {
      str->minlrec = MCF_XDR_MINLREC;
      rblklen_(&jfn, &ll, &iost);
      str->maxlrec = ll;
      str->bufferSize = 0;
      if (str->buffer != NULL) free(str->buffer);
      if (str->buffer2 != NULL) free(str->buffer2);
    }
    str->numWordsC = 0;
    str->numWordsT = 0;
/*
** encode the first buffer, the file header.
*/
    if (str->buffer == NULL) {
       str->bufferSize =  str->maxlrec;
       str->buffer = (char *) malloc(sizeof(char) * (str->maxlrec + 1));
    }
    ldat = str->maxlrec;

    xdrmem_create(str->xdr, str->buffer, str->maxlrec, XDR_ENCODE);
    str->firstPos = xdr_getpos(str->xdr);
    str->status = MCFIO_BOF;

    if (str->fhead == NULL) {
       str->fhead = (mcfxdrFileHeader *) malloc(sizeof(mcfxdrFileHeader));
       str->fhead->blockIds = NULL;
       str->fhead->blockNames = NULL;
    }
   /*
   ** Fill the file header, additional info will be written on tape
   */
    if (title == NULL) strcpy(str->fhead->title,"No Title given");
      else strcpy(str->fhead->title,title);

    if (comment == NULL) strcpy(str->fhead->comment,"No comment");
       else strcpy(str->fhead->comment, comment);
    str->fhead->numevts_expect = numevts_pred;
    str->fhead->numevts = 0;
    str->fhead->dimTable = 0;
    str->fhead->firstTable = 0;
    str->fhead->nBlocks = nBlocks;
    str->fhead->nNTuples = 0;
    if (str->fhead->blockIds != NULL) free(str->fhead->blockIds);
    str->fhead->blockIds = (int *) malloc(sizeof(int) * nBlocks);
    if (str->fhead->blockNames != NULL) {
      for (i=0; i<nBlocks; i++) if (str->fhead->blockNames[i] != NULL) {
             free(str->fhead->blockNames[i]);
             str->fhead->blockNames[i] = NULL;
      }
      free(str->fhead->blockNames);
    }
    str->fhead->blockNames = (char**) malloc(sizeof(char*) * nBlocks);
    for (i=0; i<nBlocks; i++) {
      str->fhead->blockIds[i] = blkIds[i];
      str->fhead->blockNames[i] =
        (char *) malloc(sizeof(char) * (MCF_XDR_B_TITLE_LENGTH + 1));
      mcfioC_GetBlockName(blkIds[i], str->fhead->blockNames[i]);
    }

    p1 = xdr_getpos(str->xdr);
    idtmp = FILEHEADER;
    if (xdr_mcfast_fileheader(str->xdr, &idtmp,
              &ntot, McfGenericVersion, &(str->fhead), str->id) == FALSE) {
       fprintf (stderr,
               "mcfio_OpenWriteSequential: Unable to encode fileheader \n");
       mcfioC_FreeStream(&McfStreamPtrList[jstr]);
       rbfclose_(&jfn, &iost);
       return -1;
   }
/*
** write this buffer.
*/
    str->numWordsC += (ntot/4);
    p2 = xdr_getpos(str->xdr);
    ldat = p2 - p1;
    if (ldat < 512) ldat = 512;
    rbwrite_(&jfn, str->buffer, &ldat, &lwdat, &iost);
    if (iost != 0) {
     fprintf(stderr,
 " mcfio_OpenWriteSequential: Problem writing first record on \n device %s, \
 VSN %s, file %d \n", device, vsn, filenumber);
     fprintf(stderr, " Status from Rbio %d \n", iost);
     mcfioC_FreeStream(&McfStreamPtrList[jstr]);
     rbfclose_(&jfn, &iost);
     return -1;
   }
   str->numWordsT += (lwdat/4);
   /* printf(" Wrote in Open Seq. %d \n" , lwdat); */
   xdr_setpos(str->xdr, str->firstPos);
   str->currentPos = str->firstPos ;
   str->status = MCFIO_RUNNING;
/*
** Compose the dummy Sequential header to the first buffer.
*/
   if (str->shead == NULL)
       str->shead = (mcfxdrSequentialHeader *)
                    malloc(sizeof(mcfxdrSequentialHeader));
   str->shead->nRecords = 1;
   idtmp = SEQUENTIALHEADER;
   if (xdr_mcfast_seqheader(str->xdr, &idtmp,
                             &ntot, McfGenericVersion, &(str->shead)) == FALSE) {
       fprintf (stderr,
               "mcfio_OpenWriteSequential: Unable to encode fileheader \n");
       mcfioC_FreeStream(&McfStreamPtrList[jstr]);
       rbfclose_(&jfn, &iost);
       return -1;
   }

/*
** Compose the first dummy event header into memory. This will overwritten
**   with the complete information upon closure of the event.
*/
   str->ehead = (mcfxdrEventHeader *) malloc(sizeof(mcfxdrEventHeader));
   str->ehead->dimBlocks = str->fhead->nBlocks;
   str->ehead->nBlocks = 0;
   str->ehead->nNTuples = 0;
   str->ehead->dimNTuples = str->fhead->nNTuples;
   str->ehead->evtnum = 0;
   str->ehead->previousevtnum = 0;
   str->ehead->storenum = 0;
   str->ehead->runnum = 0;
   str->ehead->trigMask = 0;
   str->ehead->blockIds = (int *) malloc(sizeof(int) * str->fhead->nBlocks);
   str->ehead->ptrBlocks = (u_int *) malloc(sizeof(int) * str->fhead->nBlocks);
   str->ehead->nTupleIds = (int *) malloc(sizeof(int) * str->fhead->nNtuples);
   str->ehead->ptrNTuples =
       (u_int *) malloc(sizeof(int) * str->fhead->nNtuples);
   if (mcfioC_WrtEvt(str, INITIATE) == FALSE) {
       fprintf (stderr,
               "mcfio_OpenWriteSequential: Unable to encode Evtheader \n");
       mcfioC_FreeStream(&McfStreamPtrList[jstr]);
       rbfclose_(&jfn, &iost);
       return -1;
   }
   str->ehead->evtnum = 0;
   McfNumOfStreamActive++;
   return (jstr+1);

}

int mcfioC_NextEventSequential(int stream)
{
   int i, j, jstr, idtmp, ntot, ok, jfn, lrdat, lwdat, ldat, iost, lrem;
   u_int p1;
   mcfStream *str;
   char *tmpbuf;

  jfn = stream;
  jstr = stream -1;
  str = McfStreamPtrList[jstr];

/*
** Branching code Here, INPUT vs OUTPUT
*/
   if (str->row == MCFIO_READ) {
/*
** Read the first record. Decode the Sequential header. Read more records
**   if need be.
*/
      if (str->buffer2  == NULL)
          str->buffer2 = (char *) malloc(sizeof(char)* (str->maxlrec+1));
      rbread_(&jfn, str->buffer2, &(str->maxlrec), &lrdat, &iost);
      if (iost != 0) {
         fprintf(stderr,
                " mcfio_NextEventSequential: \n\
   Problem reading first record for this evt, stream %d, Rbio status %d \n",
                       stream, iost);
          mcfioC_FreeStream(&McfStreamPtrList[jstr]);
          rbfclose_(&jfn, &iost);
          return -1;
       }
/*
** Read the Sequential header to get the number of buffers.
*/
      if (str->shead == NULL)
          str->shead =
            (mcfxdrSequentialHeader *) malloc(sizeof(mcfxdrSequentialHeader));
      xdrmem_create(str->xdr, str->buffer2, str->maxlrec, XDR_DECODE);
      str->firstPos = xdr_getpos(str->xdr);
      if (xdr_mcfast_seqheader(str->xdr, &idtmp,
                             &ntot, McfGenericVersion, &(str->shead)) == FALSE) {
          fprintf (stderr,
               "mcfio_NextEventSequential: Unable to decode seqheader \n");
          mcfioC_FreeStream(&McfStreamPtrList[jstr]);
          rbfclose_(&jfn, &iost);
          return -1;
      }
      str->currentPos = xdr_getpos(str->xdr);
      str->numWordsC += (ntot/4);
      if (str->shead->nRecords > 1) {
         if (str->bufferSize < (str->shead->nRecords * str->maxlrec)) {
             if (str->buffer != NULL) free(str->buffer);
             str->bufferSize = (str->shead->nRecords * str->maxlrec);
             str->buffer = (char *) malloc(sizeof(char) * (str->bufferSize+1));
         }
         tmpbuf = str->buffer;
         memcpy(str->buffer, str->buffer2,lrdat);
         tmpbuf += lrdat;
         for (i=1; i<str->shead->nRecords; i++) {
             rbread_(&jfn, tmpbuf, &(str->maxlrec), &lrdat, &iost);
             if (iost != 0) {
                 fprintf(stderr,
                " mcfio_NextEventSequential: \n\
     Problem reading first record for this evt, stream %d, Rbio status\n",
               stream, iost);
              mcfioC_FreeStream(&McfStreamPtrList[jstr]);
              rbfclose_(&jfn, &iost);
              return -1;
             }
             tmpbuf += lrdat;
         }
         /*
         ** We have to reposition ourselves..
         */
         xdrmem_create(str->xdr, str->buffer, str->bufferSize, XDR_DECODE);
         xdr_setpos(str->xdr, str->currentPos);
       }
      if (xdr_mcfast_eventheader(str->xdr, &idtmp,
                          &ntot, McfGenericVersion, &(str->ehead)) == FALSE) {
          fprintf (stderr,
               "mcfio_NextEventSequential: Unable to decode evtheader \n");
          mcfioC_FreeStream(&McfStreamPtrList[jstr]);
          rbfclose_(&jfn, &iost);
          return -1;
      }
      str->currentPos = xdr_getpos(str->xdr);
      str->numWordsC += (ntot/4);
    } else {  /* Writing an event.. */
    /*
    ** The entire buffer is at str->buffer. it has a size of
    ** str->bufferSize bytes. First, we have to compute the number of
    ** records, rewrite the Sequential header, and the Event header.
    */
       p1 = str->currentPos;
       str->shead->nRecords = 1 + (p1 - str->firstPos)/str->maxlrec;
       if (((p1 - str->firstPos) % str->maxlrec) == 0) str->shead->nRecords--;
       xdr_setpos(str->xdr, str->firstPos);
       idtmp = SEQUENTIALHEADER;
       xdr_mcfast_seqheader(str->xdr, &idtmp,
                          &ntot, McfGenericVersion, &(str->shead));
       str->numWordsC += (ntot/4);
       str->currentPos = xdr_getpos(str->xdr);
       str->ehead->evtnum++;
       idtmp = EVENTHEADER;
       xdr_mcfast_eventheader(str->xdr, &idtmp,
            &ntot, McfGenericVersion, &(str->ehead));
       str->currentPos = xdr_getpos(str->xdr);
       str->numWordsC += (ntot/4);
    /*
    ** The buffer is ready to be written to sequential media
    **
    */

       lrem = p1 - str->firstPos;
       for (i=0, tmpbuf=str->buffer; i<str->shead->nRecords; i++) {
           if (i == (str->shead->nRecords - 1))
               ldat = (lrem > 512) ? lrem : 512;
           else
               ldat = str->maxlrec;
           rbwrite_(&jfn, tmpbuf, &ldat, &lwdat, &iost);
           /* printf(" Wrote in evt loop %d \n" , lwdat); */
           if (iost != 0) {
              fprintf(stderr,
                  " mcfio_NextEventSequential: \n\
     Problem writing record on Stream %d, Rbio status %d ", stream, iost);
            mcfioC_FreeStream(&McfStreamPtrList[jstr]);
            rbfclose_(&jfn, &iost);
            return -1;
           }
           str->numWordsT += lwdat/4;
           lrem -= ldat;
           tmpbuf += ldat;
        }
        /*
        ** Initiate a new bufffer
        */
        str->shead->nRecords = 1;
        xdr_setpos(str->xdr, str->firstPos);
        idtmp = SEQUENTIALHEADER;
        if (xdr_mcfast_seqheader(str->xdr, &idtmp,
                        &ntot, McfGenericVersion, &(str->shead)) == FALSE) {
            fprintf (stderr,
               "mcfio_OpenWriteSequential: Unable to encode fileheader \n");
            mcfioC_FreeStream(&McfStreamPtrList[jstr]);
            rbfclose_(&jfn, &iost);
            return -1;
        }
        str->currentPos = xdr_getpos(str->xdr);
        str->ehead->nBlocks = 0;
        str->ehead->previousevtnum = str->ehead->evtnum;
        if (mcfioC_WrtEvt(str, INITIATE) == FALSE) {
           fprintf (stderr,
               "mcfio_OpenWriteSequential: Unable to encode Evtheader \n");
           mcfioC_FreeStream(&McfStreamPtrList[jstr]);
           rbfclose_(&jfn, &iost);
           return -1;
        }
        str->ehead->evtnum = str->ehead->previousevtnum;

    }
    str->status = MCFIO_RUNNING;
    return MCFIO_RUNNING;
}

void mcfioC_CloseSequentialFile(int stream)
{
   mcfStream *str;
   int jfn, iost, jstr;

   jstr = stream -1;
   str =  McfStreamPtrList[jstr];
   str->status = MCFIO_EOF;
   jfn = jstr + 1;
   rbclose_(&jfn, &iost);
   if (iost != 0) {
      fprintf(stderr,
                  " mcfio_CloseSequentialFile: \n\
     Problem closing file Stream %d, Rbio status %d ", jstr, iost);
     mcfioC_FreeStream(&McfStreamPtrList[jstr]);
  }
}

void mcfioC_CloseSequentialTape(int stream)
{
   mcfStream *str;
   int jfn, iost, jstr;

   jstr = stream -1;
   str =  McfStreamPtrList[jstr];
   jfn = jstr + 1;
   rbfclose_(&jfn, &iost);
   /*
   ** This suppose to work,
   ** but does not..
   **
     if (strcmp(str->vsn,"Disk") != 0) rbrewind_(&jfn, &iost);
      rbumount_(&jfn, &iost);
   */
   if (iost != 0)
      fprintf(stderr,
                  " mcfio_CloseSequentialTape: \n\
   Problem closing file Stream %d, Rbio status %d ", stream, iost);
   mcfioC_FreeStream(&McfStreamPtrList[jstr]);

}


text:
"""
Purdue Computer Science Women's Network / Microsoft Hackathon Project
"""

# Import Modules
import os

import pygame
from pygame.locals import *

# functions to create our resources
def load_image(name, color_key=None):
    fullname = os.path.join('data', name)
    image = pygame.image.load(fullname)
    image = image.convert()
    if color_key is not None:
        if color_key is -1:
            color_key = image.get_at((0, 0))
        image.set_colorkey(color_key, RLEACCEL)
    return image, image.get_rect()

def load_sound(name):
    class NoneSound:
        def play(self):
            pass

    if not pygame.mixer or not pygame.mixer.get_init():
        return NoneSound()
    fullname = os.path.join('data', name)
    sound = pygame.mixer.Sound(fullname)
    return sound

# classes for our game objects
class Gun(pygame.sprite.Sprite):

    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image('sight.png', -1)
        self.firing = 0

    def update(self):
        pos = pygame.mouse.get_pos()
        self.rect.midtop = pos
        if self.firing:
            self.rect.move_ip(5, 10)

    def hitontarget(self, target):
        if not self.firing:
            self.firing = 1
            hitbox = self.rect.inflate(-3, -5)
            return hitbox.colliderect(target.rect)

    def pullback(self):
        self.firing = 0

class Bird(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image, self.rect = load_image('bird.png', -1)
        screen = pygame.display.get_surface()
        self.area = screen.get_rect()
        self.rect.topleft = 10, 10
        self.move = 8
        self.move1 = 9
        self.onHit = 0

    def update(self):

        if self.onHit:
            self._spin()
        else:
            self._walk()

    def _walk(self):

        new_pos = self.rect.move((self.move, self.move1))
        if self.rect.left < self.area.left or self.rect.right > self.area.right:
            self.move = -self.move
            new_pos = self.rect.move((self.move, 0))
            self.image = pygame.transform.flip(self.image, 1, 0)

        if self.rect.top < self.area.top or self.rect.bottom > self.area.bottom - 150:
            self.move1 = -self.move1

            new_pos = self.rect.move((self.move, self.move1))
        self.rect = new_pos

    def _spin(self):

        center = self.rect.center
        self.onHit += 12
        if self.onHit >= 180:
            self.onHit = 0
            self.image = self.original
        else:
            rotate = pygame.transform.rotate
            self.image = rotate(self.original, self.onHit)
        self.rect = self.image.get_rect(center=center)

    def gothit(self):

        if not self.onHit:
            self.onHit = 1
            # noinspection PyAttributeOutsideInit
            self.original = self.image

    def movefaster(self):

        move_point = 4

        if self.move > 0:
            self.move += move_point
        elif self.move < 0:
            self.move -= move_point

        if self.move1 > 0:
            self.move1 += move_point
        elif self.move1 < 0:
            self.move -= move_point

    def completestop(self):
        self.move = 0
        self.move1 = 0

def main():

    pygame.init()
    screen = pygame.display.set_mode((800, 600), pygame.FULLSCREEN)
    pygame.display.set_caption('Duck Hunt')
    pygame.mouse.set_visible(0)

    # Background
    # noinspection PyArgumentList
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((140, 180, 20))

    # Put Text On The Background, Centered
    if pygame.font:
        font = pygame.font.Font(None, 36)
        text = font.render("Duck Hunt!", 1, (10, 10, 10))
        textpos = text.get_rect(centerx=background.get_width() / 2)
        background.blit(text, textpos)

    # Display The Background
    screen.blit(background, (0, 0))
    pygame.display.flip()

    # Prepare Game Objects
    clock = pygame.time.Clock()
    miss_sound = load_sound('gun.wav')
    hit_sound = load_sound('exp.wav')
    level_sound = load_sound('tone.wav')
    sound_name = os.path.join('data', 'star.ogg')
    pygame.mixer.music.load(sound_name)
    pygame.mixer.music.play(0)

    score = 0
    s_level = 0
    level = 0
    rounds = 10

    myfont = pygame.font.SysFont("monospace", 20)

    bird = Bird()
    gunsight = Gun()

    allsprites = pygame.sprite.RenderPlain((gunsight, bird))
    label_name = myfont.render("Created by Hongda Zeng", 1, (204, 22, 0))

    # Main Loop
    while 1:
        clock.tick(50)
        label1 = myfont.render("Score: " + str(score), 1, (204, 22, 0))
        label2 = myfont.render("Level: " + str(level) + " Spd" + str(abs(bird.move)), 1, (204, 22, 0))

        # Handle Input Events
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return
            elif event.type == MOUSEBUTTONDOWN:

                rounds -= 1

                if gunsight.hitontarget(bird):
                    hit_sound.play()
                    bird.gothit()
                    score += 1
                    s_level += 0.2

                    if s_level > 0.9:
                        bird.movefaster()
                        level_sound.play()
                        rounds = 10
                        s_level = 0
                        level += 1

                else:
                    miss_sound.play()

            if rounds <= 0:
                    bird.completestop()
                    label4 = myfont.render("-=Game Over=- Press any key to quit", 1, (204, 22, 0))
                    pygame.mixer.music.pause()
                    a = True
                    while a:
                        screen.blit(label1, (100, 500))
                        screen.blit(label2, (120, 550))
                        # noinspection PyUnboundLocalVariable
                        screen.blit(label3, (400, 500))
                        screen.blit(label4, (200, 300))
                        screen.blit(label_name, (420, 550))
                        allsprites.draw(screen)
                        pygame.display.flip()
                        # noinspection PyAssignmentToLoopOrWithParameter
                        for event in pygame.event.get():  # User did something
                            if event.type == pygame.QUIT:  # If user clicked close
                                return
                            elif event.type == pygame.KEYDOWN:
                                return

            elif event.type is MOUSEBUTTONUP:
                gunsight.pullback()
        label3 = myfont.render("Bullets: " + str(rounds), 1, (204, 22, 0))
        allsprites.update()

        screen.blit(background, (0, 0))
        pygame.draw.line(background, (200, 200, 200), (0, 450), (800, 450), 1)
        # Draw Everything
        screen.blit(label1, (100, 500))
        screen.blit(label2, (120, 550))
        screen.blit(label3, (400, 500))
        screen.blit(label_name, (420, 550))
        allsprites.draw(screen)
        pygame.display.flip()

# Game Over

# this calls the 'main' function when this script is executed
if __name__ == '__main__':
    main()