text:
from __future__ import print_function

import os
import difflib
import string
import random
import sys
from bond_dialog import OptionDialog

try:
    # Import bond safely
    from bond import spy_point
except ImportError:
    spy_point = lambda **kw: lambda f: f

"""
Reconcile the reference observations with the current ones
"""

BOLD_CHAR = '\033[1m'
RESET_CHAR = '\033[0m'

class ReconcileTool:
    """
    Base class for reconcile tools
    """

    TMP_FILE_BASE_NAME = '/tmp/bond_tmp_'

    @staticmethod
    def select(reconcile_tool=None):

        if reconcile_tool == 'accept':
            return ReconcileToolAccept()

        if reconcile_tool == 'abort':
            return ReconcileToolAbort()

        if reconcile_tool == 'console':
            return ReconcileToolConsole()

        if reconcile_tool == 'dialog':
            return ReconcileToolDialog()

        if reconcile_tool == 'kdiff3':
            return ReconcileToolKdiff3()

        if reconcile_tool is None:
            # Look at the environment variable BOND_RECONCILE
            reconcile_tool = os.environ.get('BOND_RECONCILE', 'console')
            if reconcile_tool is not None:
                return ReconcileTool.select(reconcile_tool)

        assert False, 'Unrecognized bond_reconcile tool name: {}'.format(reconcile_tool)

    @staticmethod
    @spy_point(enabled_for_groups='bond_self_test',
               require_agent_result=True)
    def _invoke_command(cmd):
        """
        Invoke a shell command. Return the exit code.
        :param cmd:
        :return:
        """
        return os.system(cmd)

    @staticmethod
    def _get_user_input_console(before_prompt, after_prompt, content, options, single_char_options):
        """
        Get input from the user using a console.
        :param prompt: The main prompt string to display to the user.
        :param options: A tuple of options to present to the user for them to select; must have
                        at least one. The last option is the default.
        :param single_char_options: A tuple of the single-character versions of each of the
                                    options supplied; this tuple must be the same length as ``options``,
                                    and each single-character version must appear within the option itself.
        :return: The user response, which is guaranteed to be one of the supplied ``options`` (if the user
                 input an invalid response the default option is used).
        """
        opts_with_single_char = \
            [string.replace(opt, char, '[' + char + ']', 1) for opt, char in zip(options, single_char_options)]
        # Default option, highlight it in bold
        opts_with_single_char[-1] = BOLD_CHAR + opts_with_single_char[-1] + RESET_CHAR
        if before_prompt != '' and after_prompt == '':
            # If there's only one, use the after, since that is when user input is grabbed
            after_prompt = before_prompt
            before_prompt = ''
        if before_prompt != '':
            print(BOLD_CHAR + before_prompt + RESET_CHAR)
        if content != '':
            print(content)
        response = raw_input(BOLD_CHAR + after_prompt + RESET_CHAR + ' (' + ' | '.join(opts_with_single_char) + '): ')
        if len(response) == 0:  # No input; return the default
            return options[-1]
        elif len(response) == 1:  # Single-character; find matching option
            return next((opt for opt, char in zip(options, single_char_options) if char == response), options[-1])
        else:
            # Make sure response is a valid option; if not return the default
            return next((opt for opt in options if opt == response), options[-1])

    @staticmethod
    def _get_user_input_dialog(before_prompt, after_prompt, content, options):
        """
        Get input from the user using a dialog box.
        :param prompt: The main prompt string to display to the user.
        :param options: A tuple of options to present to the user for them to select; must have
                        at least one. The last option is the default.
        :return: The user response, which is guaranteed to be one of the supplied ``options``
                 (if the user input an invalid response the default option is used).
        """
        return OptionDialog.create_dialog_get_value(before_prompt, after_prompt, content, options)

    @staticmethod
    @spy_point(enabled_for_groups='bond_self_test',
               require_agent_result=True,
               excluded_keys=('extra_dialog_prompt','single_char_options'),
               spy_result=True)
    def _get_user_input(before_prompt, after_prompt, content, options, single_char_options):
        """
        Acquire input from the user. Defaults to using the console to ask for input. If
        a console is not available, falls back to using a popup dialog window.
        :param prompt: The main prompt string to display to the user.
        :param options: A tuple of options to present to the user for them to select; must have
                        at least one. The last option is the default.
        :param single_char_options: A tuple of the single-character versions of each of the
                                    options supplied; this tuple must be the same length as ``options``,
                                    and each single-character version must appear within the option itself.
        :param extra_dialog_prompt: An extra message to display before the prompt only if the fallback
                                    dialog box is used.
        :return: The user response, which is guaranteed to be one of the supplied ``options`` (if the user
                 input an invalid response the default option is used).
        """
        if sys.stdin.isatty():  # We use the console to retrieve input
            return ReconcileTool._get_user_input_console(before_prompt, after_prompt,
                                                         content, options, single_char_options)
        else:  # We use a dialog box to retrieve input
            print('System console not found; using a dialog box to retrieve input instead.')
            return ReconcileTool._get_user_input_dialog(before_prompt, after_prompt, content, options)

    @staticmethod
    @spy_point(enabled_for_groups='bond_self_test')
    def _print(what):
        """
        A function to do the printing, so we can spy on it
        :param what:
        :return:
        """
        print(what)

    @staticmethod
    @spy_point(enabled_for_groups='bond_self_test', mock_only=True)
    def _random_string():
        """
        Generate a short random string
        """
        return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(8))

    @staticmethod
    def _tmp_file_name(flavor):
        """
        The name of the temporary file to use with a flavor-specific
        (e.g. diff, curr, ref) ending.
        """
        # We include a short random string to avoid potential collisions
        return ReconcileTool.TMP_FILE_BASE_NAME + ReconcileTool._random_string() + "." + flavor

    @staticmethod
    @spy_point(enabled_for_groups='bond_self_test')
    def _compute_diff(reference_lines, current_lines):
        return list(difflib.unified_diff(reference_lines, current_lines, 'reference', 'current'))

    def __init__(self):
        pass

    def reconcile(self,
                  test_name,
                  reference_file,
                  current_lines,
                  no_save=None):
        """
        Reconcile the differences
        @param test_name: the name of the test (for messages)
        @param reference_file: the name of the reference observation file
        @param current_lines: a list of the lines which make up the current set of observations
        :param no_save: if present, then disallows saving a new reference file.
               This parameter should be a string explaining why saving is disallowed.
        """

        if os.path.isfile(reference_file):
            with open(reference_file, 'r') as f:
                reference_lines = f.readlines()
        else:
            # if we do not have the reference file, pretend we have an empty one
            ReconcileTool._print('WARNING: No reference observation file found for {}: {}'.format(test_name, reference_file))
            reference_lines = list()

        # Compute a quick difference
        unified_diff = self._compute_diff(reference_lines, current_lines)

        if len(unified_diff) == 0:
            # There are no differences
            return True

        # There are differences
        merged_lines = self.invoke_tool(test_name,
                                        reference_lines,
                                        current_lines,
                                        unified_diff,
                                        no_save=no_save)
        if merged_lines is not None:
            # Accepted differences
            if no_save:
                ReconcileTool._print("Not saving reference observation file for {}: {}".format(test_name,
                                                                                no_save))
            else:
                ReconcileTool._print('Saving updated reference observation file for {}'.format(test_name))
                if os.path.isfile(reference_file):
                    os.unlink(reference_file)
                with open(reference_file, 'w') as f:
                    f.writelines(merged_lines)
            return True
        else:
            return False

    def get_diff(self, unified_diff):
        """
        Return a message showing the diff, or a message saying there were no differences.
        """
        if len(unified_diff) > 0:
            return ''.join(unified_diff)
        else:
            return 'No differences in observations.'

    def invoke_tool(self, test_name,
                    reference_lines,
                    current_lines,
                    unified_diff,
                    no_save=None):
        """
        Invoke the actual tool
        @param
        @return either False, for a failed merge, or a list of the new lines to use as the reference
        """
        assert False, 'Must override'

class ReconcileToolAbort(ReconcileTool):
    """
    Abort all merges
    """

    def invoke_tool(self,
                    test_name,
                    reference_lines,
                    current_lines,
                    unified_diff,
                    no_save=None):
        if not no_save:
            ReconcileTool._print('{}Differences in observations for {}:{}'.format(BOLD_CHAR, test_name, RESET_CHAR))
            ReconcileTool._print(self.get_diff(unified_diff))
        ReconcileTool._print('{}Aborting (reconcile=abort) due to differences for {}{}'
                             .format(BOLD_CHAR, test_name, RESET_CHAR))
        return None

class ReconcileToolAccept(ReconcileTool):
    """
    Accept all changes
    """

    def invoke_tool(self,
                    test_name,
                    reference_lines,
                    current_lines,
                    unified_diff,
                    no_save=None):
        if no_save:
            ReconcileTool._print('{}Test {} exited with failures; observations before failure:{}'
                                 .format(BOLD_CHAR, test_name, RESET_CHAR))
            ReconcileTool._print(''.join(self.get_diff(unified_diff)))
        else:
            ReconcileTool._print('{}Differences for {}:{}'.format(BOLD_CHAR, test_name, RESET_CHAR))
            ReconcileTool._print(self.get_diff(unified_diff))
            ReconcileTool._print('{}Accepting (reconcile=accept) differences for {}{}'
                                 .format(BOLD_CHAR, test_name, RESET_CHAR))
        return current_lines

class ReconcileToolConsole(ReconcileTool):
    """
    Uses diff and console prompts to accept the changes. Falls back to a dialog window
    if no console is available for input.
    """

    def invoke_tool(self,
                    test_name,
                    reference_lines,
                    current_lines,
                    unified_diff,
                    no_save=None):

        response = 'observations' if no_save else 'diff'
        error_after_prompt = 'Saving not available due to errors in the test'.format(test_name)
        while True:
            if response == 'observations':
                if no_save:
                    after_prompt = error_after_prompt
                    options = ('kdiff3', 'diff', 'errors', 'continue')
                    single_char_opts = ('k', 'd', 'e', 'c')
                else:
                    after_prompt = 'Save new set of observations with these differences for {}?'.format(test_name)
                    options = ('kdiff3', 'diff', 'yes', 'no')
                    single_char_opts = ('k', 'd', 'y', 'n')
                before_prompt = 'Observations are shown for {}:'.format(test_name)
                response = self._input(before_prompt, after_prompt, ''.join(current_lines),
                                       options, single_char_opts)
            elif response == 'diff':
                before_prompt = 'Differences in observations are shown for {}:'.format(test_name)
                if no_save:
                    after_prompt = error_after_prompt
                    options = ('kdiff3', 'observations', 'errors', 'continue')
                    single_char_opts = ('k', 'o', 'e', 'c')
                else:
                    after_prompt = 'Save new set of observations with these differences for {}?'.format(test_name)
                    options = ('kdiff3', 'observations', 'yes', 'no')
                    single_char_opts = ('k', 'o', 'y', 'n')
                response = self._input(before_prompt, after_prompt, self.get_diff(unified_diff),
                                       options, single_char_opts)
            elif response == 'errors':
                before_prompt = 'Errors are shown for {}:'.format(test_name)
                response = self._input(before_prompt, error_after_prompt, no_save,
                                       ('kdiff3', 'observations', 'diff', 'continue'), ('k', 'o', 'd', 'c'))
            elif response == 'kdiff3':
                return ReconcileToolKdiff3().invoke_tool(test_name, reference_lines, current_lines, unified_diff,
                                                         no_save=no_save)
            elif response == 'yes':
                ReconcileTool._print('{}Accepting differences for {}{}'.format(BOLD_CHAR, test_name, RESET_CHAR))
                return current_lines
            elif response == 'no':
                ReconcileTool._print('{}Rejecting differences for {}{}'.format(BOLD_CHAR, test_name, RESET_CHAR))
                return None
            elif response == 'continue':
                return None
            else:
                assert False, 'Unknown input received!'  # Should never be reached

    def _input(self, before_prompt, after_prompt, content, options, single_char_options):
        return ReconcileTool._get_user_input(before_prompt, after_prompt, content, options, single_char_options)

class ReconcileToolDialog(ReconcileToolConsole):
    """
    Merge with a dialog window.
    """
    def _input(self, before_prompt, after_prompt, content, options, single_char_options):
        return ReconcileTool._get_user_input_dialog(before_prompt, after_prompt, content, options)

class ReconcileToolKdiff3(ReconcileTool):
    """
    Merge with kdiff3
    """

    def invoke_tool(self,
                    test_name,
                    reference_lines,
                    current_lines,
                    unified_diff,
                    no_save=None):

        # Save the current lines out to a temporary file to use with kdiff3
        current_file = self._tmp_file_name('curr')
        reference_file = self._tmp_file_name('ref')
        try:
            with open(current_file, 'w') as f:
                f.writelines(current_lines)
            with open(reference_file, 'w') as f:
                f.writelines(reference_lines)

            merged_file = None
            if no_save:
                response = ReconcileTool._get_user_input(
                    'Encountered failures while running test {}:'.format(test_name),
                    'Still want to start kdiff3?', no_save,
                    ('yes', 'no'), ('y', 'n'))
                if response != 'yes':
                    return None

                cmd = ('kdiff3 "{reference_file}" --L1 "{test_name}_REFERENCE" '
                       '"{current_file}" --L2 "{test_name}_CURRENT" ').format(
                    reference_file=reference_file,
                    current_file=current_file,
                    test_name=test_name)
                ReconcileTool._invoke_command(cmd)
                return None

            else:
                merged_file = self._tmp_file_name('merged')
                cmd = ('kdiff3 -m "{reference_file}" --L1 "{test_name}_REFERENCE" '
                       '"{current_file}" --L2 "{test_name}_CURRENT" '
                       ' -o "{merged_file}"').format(reference_file=reference_file,
                                                     current_file=current_file,
                                                     merged_file=merged_file,
                                                     test_name=test_name)

                code = ReconcileTool._invoke_command(cmd)
                if code == 0:
                    # Merged ok
                    with open(merged_file, 'r') as f:
                        merged_lines = f.readlines()
                    message = 'Merge successful; saving a new reference file. '
                    ret = merged_lines
                else:
                    message = 'Merge unsuccessful; not saving a new reference file. '
                    ret = None

                ReconcileTool._get_user_input(message, '', '', ('continue',), ('c',))
                return ret
        finally:
            if os.path.isfile(current_file):
                os.unlink(current_file)
            if os.path.isfile(reference_file):
                os.unlink(reference_file)
            if merged_file is not None and os.path.isfile(merged_file):
                os.unlink(merged_file)

def reconcile_observations(settings,
                           test_name,
                           reference_file,
                           current_lines,
                           no_save=None):
    """
    Reconcile the observations
    :param settings: a settings object
    :param reference_file: the reference file
    :param current_lines: a list of all of the lines in the current set of observations
    :param no_save: If present, then saving of new references is not allowed. This parameter
            should be a short string explaining why saving is not allowed.
    :return:
    """

    reconcile_tool = ReconcileTool.select(settings.get('reconcile'))
    return reconcile_tool.reconcile(test_name,
                                    reference_file,
                                    current_lines,
                                    no_save=no_save)

if __name__ == '__main__':
    import optparse

    optParser = optparse.OptionParser(usage=os.path.basename(__file__),
                                      description='Compare and reconciles differences in Bond observation files')

    optParser.add_option('--reconcile', dest='reconcile', action='store', default=None,
                         help='The reconcile tool to use. Available: accept, abort, console, dialog, kdiff3.')
    optParser.add_option('--reference', dest='reference', action='store', default=None,
                         help='The reference observation file')
    optParser.add_option('--current', dest='current', action='store', default=None,
                         help='The current observation file')
    optParser.add_option('--test', dest='test', action='store', default=None,
                         help='The name of the test (for UI). Default is to extract from --current')
    optParser.add_option('--no-save', dest='no_save', action='store', default=None,
                         help='If given, the reason why saving of new references is not allowed')
    (opts, args) = optParser.parse_args()
    if opts.reference is None:
        sys.exit(1)

    if opts.current is None or not os.path.isfile(opts.current):
        print('The current file does not exist: {}'.format(opts.current), file=sys.stderr)
        sys.exit(1)

    with open(opts.current, 'r') as f:
        current_lines = f.readlines()
    os.unlink(opts.current)

    # Guess the test name from the current file
    if opts.test:
        main_test_name = opts.test
    else:
        main_test_name = os.path.splitext(os.path.basename(opts.current))[0]

    if opts.reconcile:
        main_reconcile = opts.reconcile
    else:
        main_reconcile = os.environ.get('BOND_RECONCILE', 'console')

    main_settings = dict(reconcile=main_reconcile)

    if reconcile_observations(main_settings,
                              main_test_name,
                              opts.reference,
                              current_lines,
                              no_save=opts.no_save):
        sys.exit(0)
    else:
        sys.exit(1)


text:
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import HomePage from '../components/HomePage';
import ContacList from './ContactList';
import * as userActions from '../actions/userActions';
import toastr from 'toastr';
import {browserHistory} from 'react-router';

class ManageHomePage extends React.Component {
  constructor(props) {
    super(props);

    this.logoutUser = this.logoutUser.bind(this);
  }

  logoutUser() {
    this.props.actions.logoutUser()
      .then(function () {
        toastr.success('Logout Successful');
        browserHistory.push('/');
      });
  }

  render() {
    return (
      <HomePage onLogout={this.logoutUser} >
        <ContacList />
      </HomePage>
    );
  }

}

ManageHomePage.propTypes = {
  actions: PropTypes.object.isRequired,
};

ManageHomePage.contextTypes = {
  router: PropTypes.object.isRequired,
};

const mapDispatchToProps = (dispatch) => {
  return {
    actions: bindActionCreators(userActions, dispatch),
  };
};

export default connect(null, mapDispatchToProps)(ManageHomePage);

redpajama_set_name: RedPajamaGithub


text:
local runner = require('user_modules/script_runner')
local common = require('user_modules/sequences/actions')

--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false

--[[ Local variables ]]
local rpcCreateChoiceSet = {
  name = "CreateInteractionChoiceSet",
  params = {
    interactionChoiceSetID = 42,
    choiceSet = {
      { choiceID = 1, menuName = "choice1" },
      { choiceID = 2, menuName = "choice2" }
    }
  }
}

local rpcInteraction = {
  name = "PerformInteraction",
  hmi_name = "UI.PerformInteraction",
  hmi_name2 = "VR.PerformInteraction",
  params = {
    cancelID = 99,
    initialText = "hello",
    interactionMode = 0,
    interactionChoiceSetIDList = { 42 },
    helpPrompt = { { text = "tts_chunk", type = "SILENCE" } }
  },
  ui_params = {
    cancelID = 99,
    choiceSet = {
      { choiceID = 1, menuName = "choice1" },
      { choiceID = 2, menuName = "choice2" }
    },
    initialText = {
      fieldName = "initialInteractionText",
      fieldText = "hello"
    },
    timeout = 10000
  },
  vr_params = {
    cancelID = 99,
    helpPrompt = {
      { text = "tts_chunk", type = "SILENCE" }
    },
    timeoutPrompt = {
      { text = "tts_chunk", type = "SILENCE" }
    },
    timeout = 10000
  }
}

local rpcCancelInteraction = {
  name = "CancelInteraction",
  hmi_name = "UI.CancelInteraction",
  params = {
    cancelID = 99,
    functionID = 10
  }
}

local successResponse = {
  success = true,
  resultCode = "SUCCESS"
}

local abortedResponse = {
  success = false,
  resultCode = "ABORTED"
}

--[[ Local functions ]]
local function SendCancelInteraction()
  local mobileSession = common.getMobileSession(1)
  local hmiSession = common.getHMIConnection()

  mobileSession:SendRPC(rpcCreateChoiceSet.name, rpcCreateChoiceSet.params)
  local cid0 = mobileSession:SendRPC(rpcInteraction.name, rpcInteraction.params)
  local ui_perform_interaction_id = 0
  local vr_perform_interaction_id = 0

  EXPECT_HMICALL(rpcInteraction.hmi_name2, rpcInteraction.vr_params)
  :Do(function(_, data)
    vr_perform_interaction_id = data.id
  end)

  EXPECT_HMICALL(rpcInteraction.hmi_name, rpcInteraction.ui_params)
  :Do(function(_, data)
    ui_perform_interaction_id = data.id

    local cid1 = mobileSession:SendRPC(rpcCancelInteraction.name, rpcCancelInteraction.params)

    EXPECT_HMICALL(rpcCancelInteraction.hmi_name, rpcCancelInteraction.params)
    :Do(function(_, data2)
      hmiSession:SendResponse(ui_perform_interaction_id, rpcInteraction.hmi_name, "ABORTED", {})
      hmiSession:SendResponse(vr_perform_interaction_id, rpcInteraction.hmi_name2, "ABORTED", {})
      hmiSession:SendResponse(data2.id, data2.method, "SUCCESS", {})
    end)

    mobileSession:ExpectResponse(cid1, successResponse)
  end)

  mobileSession:ExpectResponse(cid0, abortedResponse)
end

--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("RAI App 1", common.registerApp)
runner.Step("Activate App", common.activateApp)

runner.Title("Test")
runner.Step("Send CancelInteraction", SendCancelInteraction)

runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Interface com.obdobion.funnel.provider.RandomAccessInputSource (FunnelSort)</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Interface
com.obdobion.funnel.provider.RandomAccessInputSource

Packages that use RandomAccessInputSource

Package
Description

com.obdobion.funnel.provider

Uses of RandomAccessInputSource in com.obdobion.funnel.provider

Classes in com.obdobion.funnel.provider that implement RandomAccessInputSource

Modifier and Type
Class and Description

class
AbstractInputCache

 Abstract AbstractInputCache class.

class
FileSource

 FileSource class.

class
FixedLengthInputCache

 FixedLengthInputCache class.

class
InputCache

 InputCache class.

class
VariableLengthInputCache

 VariableLengthInputCache class.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Open-Source on GitHub.


text:
namespace Concurrency
{
    namespace extras
    {
        template <typename Func>
        pplx::task<void> create_delayed_task(std::chrono::milliseconds delay, Func func)
        {
            pplx::task_completion_event<void> tce;

            auto pTimer = new boost::asio::deadline_timer(crossplat::threadpool::shared_instance().service());
            pTimer->expires_from_now(boost::posix_time::milliseconds(delay.count()));
            pTimer->async_wait([tce](const boost::system::error_code& ec)
            {
                tce.set();
            });

            return create_task(tce).then([pTimer]() {
                delete pTimer;
            }).then(func);
        }
    }
}


text:
package com.envoy.rater.orm;

import com.envoy.rater.orm.DaoSession;
import de.greenrobot.dao.DaoException;

// THIS CODE IS GENERATED BY greenDAO, EDIT ONLY INSIDE THE "KEEP"-SECTIONS

// KEEP INCLUDES - put your custom includes here
// KEEP INCLUDES END
/**
 * Entity mapped to table "GAME".
 */
public class Game {

    private Long id;
    private String gameName;
    private String consoleName;
    private byte[] gameImage;
    private Boolean isGameFinished;
    private Integer starsNumber;

    /** Used to resolve relations */
    private transient DaoSession daoSession;

    /** Used for active entity operations. */
    private transient GameDao myDao;

    // KEEP FIELDS - put your custom fields here
    // KEEP FIELDS END

    public Game() {
    }

    public Game(Long id) {
        this.id = id;
    }

    public Game(Long id, String gameName, String consoleName, byte[] gameImage, Boolean isGameFinished, Integer starsNumber) {
        this.id = id;
        this.gameName = gameName;
        this.consoleName = consoleName;
        this.gameImage = gameImage;
        this.isGameFinished = isGameFinished;
        this.starsNumber = starsNumber;
    }

    /** called by internal mechanisms, do not call yourself. */
    public void __setDaoSession(DaoSession daoSession) {
        this.daoSession = daoSession;
        myDao = daoSession != null ? daoSession.getGameDao() : null;
    }

    public Long getId() {
        return id;
    }

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

    public String getGameName() {
        return gameName;
    }

    public void setGameName(String gameName) {
        this.gameName = gameName;
    }

    public String getConsoleName() {
        return consoleName;
    }

    public void setConsoleName(String consoleName) {
        this.consoleName = consoleName;
    }

    public byte[] getGameImage() {
        return gameImage;
    }

    public void setGameImage(byte[] gameImage) {
        this.gameImage = gameImage;
    }

    public Boolean getIsGameFinished() {
        return isGameFinished;
    }

    public void setIsGameFinished(Boolean isGameFinished) {
        this.isGameFinished = isGameFinished;
    }

    public Integer getStarsNumber() {
        return starsNumber;
    }

    public void setStarsNumber(Integer starsNumber) {
        this.starsNumber = starsNumber;
    }

    /** Convenient call for {@link AbstractDao#delete(Object)}. Entity must attached to an entity context. */
    public void delete() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.delete(this);
    }

    /** Convenient call for {@link AbstractDao#update(Object)}. Entity must attached to an entity context. */
    public void update() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.update(this);
    }

    /** Convenient call for {@link AbstractDao#refresh(Object)}. Entity must attached to an entity context. */
    public void refresh() {
        if (myDao == null) {
            throw new DaoException("Entity is detached from DAO context");
        }
        myDao.refresh(this);
    }

    // KEEP METHODS - put your custom methods here
    // KEEP METHODS END

}


text:
package org.opencypher.tools.grammar;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;

import org.antlr.runtime.ANTLRReaderStream;
import org.antlr.v4.Tool;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.LexerInterpreter;
import org.antlr.v4.runtime.ParserInterpreter;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.tool.ANTLRMessage;
import org.antlr.v4.tool.ANTLRToolListener;
import org.antlr.v4.tool.ErrorManager;
import org.antlr.v4.tool.Rule;
import org.antlr.v4.tool.ast.GrammarRootAST;
import org.opencypher.grammar.CharacterSet;
import org.opencypher.grammar.Grammar;
import org.opencypher.grammar.NonTerminal;
import org.opencypher.grammar.Production;
import org.opencypher.tools.io.Output;

import static java.lang.Character.charCount;
import static java.lang.Character.isUpperCase;
import static java.lang.Character.toUpperCase;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;

import static org.opencypher.tools.grammar.Main.execute;
import static org.opencypher.tools.io.Output.output;

/**
 * Generates an ANTLR (version 4) grammar from a {@link Grammar}.
 */
public class Antlr4 extends BnfWriter {
    static String PREFIX = "oC_";

    private static String prefix = PREFIX;

    public static void setPrefix(String newPrefix) {
        prefix = newPrefix;
    }

    public static void resetPrefix() {
        prefix = PREFIX;
    }

    public static void write(Grammar grammar, Writer writer) {
        write(grammar, output(writer));
    }

    public static void write(Grammar grammar, OutputStream stream) {
        write(grammar, output(stream));
    }

    public static void write( Grammar grammar, Path path, OutputStream stream )
    {
        write( grammar, stream );
    }

    public static void write( Grammar grammar, Output output )
    {
        try ( Antlr4 antlr = new Antlr4( ProductionMappingListener.NONE, output ) )
        {
            antlr.write( grammar );
        }
    }

    private void write( Grammar grammar )
    {
        String header = grammar.header();
        if ( header != null )
        {
            output.println( "/**" ).append( " * " ).printLines( header, " * " ).println( " */" );
        }
        output.append( "grammar " ).append( unspaceString( grammar.language() ) ).println( ";" ).println();

        grammar.accept( this );
    }

    public static void main(String... args) throws Exception {
        List<String> argsList = new ArrayList<>(Arrays.asList(args));
        int index = argsList.indexOf("-o");
        String g4OutputFilePath = null;
        if (index >= 0) {
            g4OutputFilePath = argsList.remove(index + 1);
            argsList.remove(index);
        }

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        execute( ( grammar, workingDir, stream ) -> write( grammar, stream ), out, "grammar/cypher.xml");

        if (g4OutputFilePath == null) {
            System.out.print(out.toString(UTF_8.name()));
        } else {
            Files.write(Paths.get(g4OutputFilePath), out.toByteArray());
            System.out.println("Wrote output grammar to " + g4OutputFilePath);

        }
    }

    public static Parser generateParser( Grammar grammar, String root, Output output )
    {
        return ParserGenerator.generateParser( grammar, root, output );
    }

    private static class ParserGenerator
    {
        static Parser generateParser( Grammar grammar, String root, Output output )
        {
            Output.Readable source = Output.stringBuilder();
            org.antlr.v4.Tool tool = new org.antlr.v4.Tool();
            AntlrMessageLogger messages = new AntlrMessageLogger( tool, output );
            try ( Antlr4 antlr = new Antlr4( messages, source ) )
            {
                antlr.write( grammar );
            }
            ANTLRReaderStream generatorInput;
            try
            {
                generatorInput = new ANTLRReaderStream( source.reader() );
            }
            catch ( IOException e )
            {
                throw new IllegalStateException( "Failed to create reader from buffer." );
            }
            GrammarRootAST ast = tool.parse( grammar.language(), generatorInput );
            org.antlr.v4.tool.Grammar g = tool.createGrammar( ast );
            tool.process( g, false );
            messages.report( source, grammar );
            String rootRuleName = ruleName( root );
            Rule rootRule = g.getRule( rootRuleName );
            if ( rootRule == null )
            {
                throw new IllegalArgumentException(
                        "The generated parser does not define a rule for '" + root + "' (it should have been called '" + rootRuleName + "' by the parser)." );
            }
            int rootRuleIndex = rootRule.index;
            return input ->
            {
                LexerInterpreter lexer = g.createLexerInterpreter( CharStreams.fromString( input ) );
                ParserInterpreter parser = g.createParserInterpreter( new CommonTokenStream( lexer ) );
                ParseTree tree = parser.parse( rootRuleIndex );
                return new Antlr4Tree( tree );
            };
        }
    }

    private static class AntlrMessageLogger implements ProductionMappingListener, ANTLRToolListener
    {
        private final Output output;
        private final ErrorManager errMgr;
        private boolean errors;
        private final Map<String, Production> productions = new HashMap<>();
        private final List<Message> messages = new ArrayList<>();

        AntlrMessageLogger( Tool tool, Output output )
        {
            this.errMgr = tool.errMgr;
            this.output = output;
            tool.addListener( this );
        }

        @Override
        public void map( String name, Production production )
        {
            productions.put( name, production );
        }

        @Override
        public void info( String msg )
        {
            output.format( "ANTLR Parser Generator: %s%n", msg );
        }

        @Override
        public void error( ANTLRMessage msg )
        {
            errors = true;
            messages.add( new Message( true, msg ) );
        }

        @Override
        public void warning( ANTLRMessage msg )
        {
            messages.add( new Message( false, msg ) );
        }

        public void report( Output.Readable source, Grammar grammar )
        {
            if ( !messages.isEmpty() )
            {
                messages.sort( Comparator.comparingInt( ( Message msg ) -> msg.message.line ).thenComparing( ( Message msg ) -> msg.message.charPosition ) );
                source.lines( new BiConsumer<>()
                {
                    Iterator<Message> iterator = messages.iterator();
                    Message message = iterator.next();

                    @Override
                    public void accept( String line, Integer no )
                    {
                        output.format( "%7d: ", no ).println( line );
                        while ( message != null && message.message.line <= no )
                        {
                            if ( message.message.charPosition >= 0 )
                            {
                                output.append( message.error ? "ERROR:   " : "WARNING: " ).repeat( ' ', message.message.charPosition ).append( '^' ).println();
                            }
                            output.append( message.error ? "ERROR:   " : "WARNING: " ).println( errMgr.getMessageTemplate( message.message ).render() );
                            message = iterator.hasNext() ? iterator.next() : null;
                        }
                    }
                } );
                Map<String,List<Message>> productions = new HashMap<>();
                for ( Message message : messages )
                {
                    addProductions( productions, message, message.message.getArgs() );
                }
                for ( Map.Entry<String,List<Message>> entry : productions.entrySet() )
                {
                    output.println();
                    Production production;
                    try
                    {
                        production = grammar.production( entry.getKey() );
                    }
                    catch ( IllegalArgumentException noSuchProduction )
                    {
                        production = null;
                    }
                    if ( production != null )
                    {
                        ISO14977.append( production, output );
                    }
                    else
                    {
                        output.append( "Keyword \"" ).append( entry.getKey() ).println( "\"" );
                    }
                    for ( Message message : entry.getValue() )
                    {
                        output.println( errMgr.getMessageTemplate( message.message ).render() );
                    }
                    output.println();
                }
                if ( errors )
                {
                    throw new IllegalStateException(
                            "There were errors when generating the ANTLR parser. " + productions.size() + " productions in error: " + productions.keySet() );
                }
            }
        }

        private void addProductions( Map<String,List<Message>> productions, Message message, Object obj )
        {
            if ( obj instanceof String )
            {
                Production production = this.productions.get( obj );
                productions.computeIfAbsent( production != null ? production.name() : (String) obj, key -> new ArrayList<>() ).add( message );
            }
            else if ( obj instanceof Rule )
            {
                addProductions( productions, message, ((Rule) obj).name );
            }
            else if ( obj instanceof Object[] )
            {
                for ( Object object : (Object[]) obj )
                {
                    addProductions( productions, message, object );
                }
            }
            else if ( obj instanceof Collection<?> )
            {
                for ( Object object : (Collection<?>) obj )
                {
                    addProductions( productions, message, object );
                }
            }
        }

        static class Message
        {
            final boolean error;
            final ANTLRMessage message;

            Message( boolean error, ANTLRMessage message )
            {
                this.error = error;
                this.message = message;
            }
        }
    }

    private static class Antlr4Tree implements Parser.ParseTree
    {
        private final ParseTree tree;

        Antlr4Tree( ParseTree tree )
        {
            this.tree = tree;
        }
    }

    private static String ruleName( String rule )
    {
        return Antlr4.prefix + unspaceString( rule );
    }

    private final Map<String, CharacterSet> fragmentRules = new HashMap<>();
    private final Set<String> seenKeywords = new HashSet<>();
    /*
     * Mutable state -- this map keeps track of the keywords in the current
     * production, and is emptied when the production is exited.
     */
    private final Map<String, String> keywordsInProduction = new LinkedHashMap<>();
    private final ProductionMappingListener mappingListener;

    private Antlr4( ProductionMappingListener mappingListener, Output output )
    {
        super( output );
        this.mappingListener = mappingListener;
    }

    @Override
    public void close() {
        /*
         * This prints all the 'fragment' rules (rules that are used to construct lexer
         * tokens, and the only type of rule that can use the character set syntax [])
         * at the bottom of the grammar file.
         */
        // // now add the letter rules
        // if (seenKeywords.size() > 0) {
        // String[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
        // for (String letter : alphabet) {
        // output.append("fragment ").append(letter).append(" : '").append(letter)
        // .append("' | '").append(letter.toLowerCase()).append("'");
        // output.println(" ;");
        // }
        // output.println();
        // }
        for (Map.Entry<String, CharacterSet> rule : fragmentRules.entrySet()) {
            CharacterSet set = rule.getValue();
            output.append("fragment ");
            lexerRule(rule.getKey());
            output.append(" : ");
            if (set.name() != null && !set.isControlCharacter()) {
                // antlr 4.7.2 is thought to accept all the names we know except the control
                // characters
                output.append("[\\p{").append(set.name()).append("}]");
            }
            //
            // // this test used not have the haveExclusions test -
            ////// but setting an exception changes the name of the set to null (since it
            // isn't the any set anymore)
            else if (CharacterSet.ANY.equals(set.name())) {
                set.accept(new AnyCharacterExceptFormatter(output));
            } else if (set.hasExclusions()) {
                set.accept(new AnyCharacterExceptFormatter(output));
            } else {
                output.append('[');
                set.accept(new SetFormatter(output));
                output.append(']');
            }
            output.println(" ;").println();
        }
    }

    @Override
    protected void productionCommentPrefix() {
        output.println("/**").append(" * ");
    }

    @Override
    protected void productionCommentLinePrefix() {
        output.append(" * ");
    }

    @Override
    protected void productionCommentSuffix() {
        output.println(" */");
    }

    private String currentProduction;
    private int nextLexerRule;

    @Override
    protected void productionStart(Production p) {
        currentProduction = p.name();
        String name;
        if (p.lexer()) {
            name = lexerRule(currentProduction);
        } else {
            name = parserRule(currentProduction);
            nextLexerRule = 0;
        }
        mappingListener.map( name, p );
        // we don't really want the : to line up with all the pipes (at least, I don't)
        alternativesLinePrefix(currentProduction.length());
        output.append(":  ");
        // output.append(" : ");
    }

    @Override
    protected void productionEnd() {
        output.println(" ;").println();

        /*
         * We print out lexer rules for all literal words mentioned in the production
         */
        for (Map.Entry<String, String> lexerRule : keywordsInProduction.entrySet()) {
            String ruleName = lexerRule.getKey();
            // Except the ones we've already seen!
            if (!seenKeywords.contains(ruleName)) {
                seenKeywords.add(ruleName);
                caseInsensitiveProductionStart(ruleName);
                inline( lexerRule.getValue() );
                output.println(" ;").println();
            }
        }
        keywordsInProduction.clear();

        currentProduction = null;
    }

    private void addFragmentRule(CharacterSet characters) {
        String rule = currentProduction + "_" + nextLexerRule++;
        fragmentRules.put(rule, characters);
        lexerRule(rule);
    }

    @Override
    protected void alternativesLinePrefix(int altPrefix) {
        if (altPrefix > 0) {
            output.println();
            while (altPrefix-- > 0) {
                output.append(' ');
            }
        }
    }

    @Override
    protected void alternativesSeparator() {
        output.append(" | ");
    }

    @Override
    protected void sequenceSeparator() {
        output.append(" ");
    }

    @Override
    protected void groupPrefix() {
        output.append("( ");
    }

    @Override
    protected void groupSuffix() {
        output.append(" )");
    }

    @Override
    protected boolean optionalPrefix() {
        return false;
    }

    @Override
    protected void optionalSuffix() {
        output.append("?");
    }

    @Override
    protected void repeat(int minTimes, Integer maxTimes, Runnable repeated) {
        if (maxTimes == null) {
            if (minTimes == 0) {
                groupWith('(', repeated, ')');
                output.append("*");
                return;
            } else if (minTimes == 1) {
                groupWith('(', repeated, ')');
                output.append("+");
                return;
            }
        } else if (maxTimes == 1 && minTimes == 0) {
            groupWith('(', repeated, ')');
            optionalSuffix();
            return;
        } else if (minTimes == maxTimes) {
            groupWith('(', () -> {
                for (int i = 0; i < minTimes; i++) {
                    if (i > 0) {
                        sequenceSeparator();
                    }
                    repeated.run();
                }
            }, ')');
            return;
        }
        throw new UnsupportedOperationException(
                format("The Antlr formatter does not support minTimes=%d, maxTimes=%s", minTimes, maxTimes));
    }

    @Override
    protected void characterSet(CharacterSet characters) {
        String setName = characters.name();
        if (setName == null) {
            addFragmentRule(characters);
        } else if (setName.equals(CharacterSet.EOI)) {
            output.append("EOF");
        } else {
            fragmentRules.put(setName, characters);
            lexerRule(setName);
        }
    }

    @Override
    protected void nonTerminal(NonTerminal nonTerminal) {
        if (nonTerminal.production().lexer()) {
            lexerRule(nonTerminal.productionName());
        } else {
            parserRule(nonTerminal.productionName());
        }
    }

    private static String unspaceString(String original) {
        return original.replaceAll("(\\s+|-|\\.)", "_");
    }

    private String parserRule( String name )
    {
        String handle = prefix( unspaceString( name ) );
        output.append( handle );
        return handle;
    }

    private String lexerRule( String original )
    {
        String name = unspaceString( original );
        int cp = name.codePointAt( 0 );
        if ( !isUpperCase( cp ) )
        {
            if ( name.codePoints().noneMatch( Character::isUpperCase ) )
            {
                name = name.toUpperCase();
            }
            else
            {
                name = new StringBuilder( name.length() ).appendCodePoint( toUpperCase( cp ) ).append( name, charCount( cp ), name.length() ).toString();
            }
        }
//        name = Antlr4.prefix.toUpperCase() + name;
        output.append( name );
        return name;
    }

    @Override
    protected String prefix(String s) {
        return Antlr4.prefix + s;
    }

    @Override
    protected void literal(String value) {
        escapeAndEnclose(value);
    }

    private boolean reserved(String ruleName) {
        return ruleName.equals("SKIP") || ruleName.equals("MORE");
    }

    private void inline(String value) {
        group(() -> {
            String sep = "";
            int start = 0;
            for (int i = 0, end = value.length(), cp; i < end; i += Character.charCount(cp)) {
                cp = value.charAt(i);
                if (Character.isLowerCase(cp) || Character.isUpperCase(cp) || Character.isTitleCase(cp)) {
                    if (start < i) {
                        output.append(sep);
                        sep = " ";
                        escapeAndEnclose(value.substring(start, i));
                    }
                    output.append(sep);
                    sep = " ";
                    start = i + Character.charCount(cp);
                    cp = Character.toUpperCase(cp);
                    String upper = String.valueOf((char) cp);
                    groupWith( '(', () ->
                    {
                        escapeAndEnclose( upper );
                        alternativesSeparator();
                        escapeAndEnclose( upper.toLowerCase() );
                    }, ')' );
                }
            }
            if (start < value.length()) {
                output.append(sep);
                escapeAndEnclose(value.substring(start));
            }
        });
    }

    @Override
    protected void caseInsensitive(String value) {
        if (value.length() == 1) {
            inline(value);
        } else {
            String lexerRule = value.toUpperCase();
            if (!Character.isLetter(value.codePointAt(0)) || reserved(lexerRule)) {
                lexerRule = "L_" + lexerRule;
            }
            output.append(lexerRule);
            keywordsInProduction.put(lexerRule, value);
        }
    }

    private void escapeAndEnclose(String value) {
        output.append("'").escape(value, Antlr4::escapes).append("'");
    }

    @Override
    protected void caseInsensitiveProductionStart(String name) {
        currentProduction = name;
        lexerRule( currentProduction );
        output.append( " : " );
        nextLexerRule = 0;
    }

    @Override
    protected void epsilon() {
    }

    private static String escapes(int cp) {
        switch (cp) { // <pre>
        case '\r':
            return "\\r";
        case '\n':
            return "\\n";
        case '\t':
            return "\\t";
        case '\b':
            return "\\b";
        case '\f':
            return "\\f";
        case '\'':
            return "\\'";
        case '\\':
            return "\\\\";
        default:
            // how mad will this get ? PRF
            if (cp >= 128) {
                String hex = Integer.toHexString(cp);
                return "\\u" + (hex.length() < 4 ? "00" : "") + Integer.toHexString(cp);
            }
            return null;
        } // </pre>
    }

    private static class AnyCharacterExceptFormatter
            implements CharacterSet.DefinitionVisitor.NamedSetVisitor<RuntimeException>,
            CharacterSet.ExclusionVisitor<RuntimeException> {
        private final Output output;

        AnyCharacterExceptFormatter(Output output) {
            this.output = output;
        }

        @Override
        public CharacterSet.ExclusionVisitor<RuntimeException> visitSet(String name) {
            output.append("~[");
            return this;
        }

        @Override
        public void visitCodePoint(int cp) {
            throw new UnsupportedOperationException();
        }

        @Override
        public void excludeCodePoint(int cp) {
            codePoint(output, cp);
        }

        @Override
        public void excludeRange(int start, int end) {
            codePoint(output, start);
            output.append('-');
            codePoint(output, end);
        }

        @Override
        public void excludeSet(String name) {
            throw new UnsupportedOperationException("ANY except a named set.");
        }

        @Override
        public void close() {
            output.append("]");
        }
    }

    private static class SetFormatter implements CharacterSet.DefinitionVisitor<RuntimeException> {
        private final Output output;

        SetFormatter(Output output) {
            this.output = output;
        }

        @Override
        public void visitCodePoint(int cp) {
            if (cp <= Character.MAX_VALUE) {
                codePoint(output, cp);
            }
        }

        @Override
        public void visitRange(int start, int end) {
            // Antlr only supports unicode literals up to \uFFFF
            if (end <= Character.MAX_VALUE) {
                codePoint(output, start);
                output.append('-');
                codePoint(output, end);
            } else if (start <= Character.MAX_VALUE) {
                codePoint(output, start);
                output.append('-');
                // truncate the range
                codePoint(output, Character.MAX_VALUE);
            }
            // just skip larger values
        }
    }

    private static void codePoint(Output output, int cp) {
        switch (cp) {// <pre>
        case '\r':
            output.append("\\r");
            break;
        case '\n':
            output.append("\\n");
            break;
        case '\t':
            output.append("\\t");
            break;
        case '\b':
            output.append("\\b");
            break;
        case '\f':
            output.append("\\f");
            break;
        case '\\':
            output.append("\\\\");
            break;
        case '-':
            output.append("\\-");
            break;
        case ']':
            output.append("\\]");
            break;
        // </pre>
        default:
            if (' ' <= cp && cp <= '~') {
                output.appendCodePoint(cp);
            } else {
                output.format("\\u%04X", cp);
            }
        }
    }
}


text:
Pointy Haired Boss - A weird tool we use for time tracking and high level priority management

This is only used internally at my work at the moment. It is not fit for human consumption.

It may be useful as an example of a non-trivial snap/heist/digestive functors/esqueleto application but I'm not entirely happy with the code yet for those purposes either. ;)


text:
"""
Created on Mon Nov 16 15:24:11 2015

@author: jl
"""

from openalea.tissueshape import cell_main_axes, cell_volume, centroid
from multicell import utilities
import numpy as np

def symmetrical_division(mesh, pos, cid):
    """Divide a cell, roughly in the middle.

    The division plane is perpendicular to the longest axis and goes through
    the barycenter of the cell.
    """

    utilities.check_pos(pos)
    bary, V1, V2, V3 = cell_main_axes(mesh, pos, cid)
    return bary, V1

def division_with_normal(mesh, pos, cid, normal):
    bary = centroid(mesh, pos, 3, cid)
    return bary, np.array(normal)

def volume_trigger(mesh, pos, cid, volume_threshold):
    """Indicates if the volume of a cell is above the threshold.
    """

    utilities.check_pos(pos)
    volume = cell_volume(mesh, pos, cid)
    return volume > volume_threshold

def always_trigger(mesh, pos, cid):
    return True


text:
package com.nowgroup.scsee.controller.rest;

import java.io.Serializable;
import java.util.List;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.nowgroup.scsee.controller.rest.dto.GlobalRestResponseDto;
import com.nowgroup.scsee.model.EditValidation;
import com.nowgroup.scsee.model.Model;
import com.nowgroup.scsee.service.SupplyChainService;

/**
 *
 * @author https://github.com/diego-torres
 *
 * @param <T>
 * @param <U>
 */
public abstract class BaseRestController<T extends Model<U>, U extends Serializable>
		extends ReadOnlyRestController<T, U> {
	private SupplyChainService<T, U> service;

	/**
	 *
	 * @param service
	 */
	public BaseRestController(SupplyChainService<T, U> service) {
		super(service);
		this.service = service;
	}

	/**
	 *
	 * @param entity
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, produces = "application/json; charset=UTF-8", consumes = "application/json; charset=UTF-8")
	public GlobalRestResponseDto<T> add(@RequestBody(required = true) T entity) {
		GlobalRestResponseDto<T> response = new GlobalRestResponseDto<>(
				"Unable to persist entity in database: " + entity);
		try {
			List<EditValidation> validationErrors = service.add(entity);
			if (validationErrors == null || validationErrors.isEmpty()) {
				response = new GlobalRestResponseDto<>(entity);
			} else {
				response = new GlobalRestResponseDto<>(entity, validationErrors);
			}
		} catch (Exception e) {
			response = new GlobalRestResponseDto<>(e.getMessage());
		}

		return response;
	}

	/**
	 *
	 * @param entity
	 * @return
	 */
	@RequestMapping(method = RequestMethod.PUT, produces = "application/json; charset=UTF-8", consumes = "application/json; charset=UTF-8")
	public GlobalRestResponseDto<T> update(@RequestBody(required = true) T entity) {
		GlobalRestResponseDto<T> response = new GlobalRestResponseDto<>(
				"Unable to merge entity in database: " + entity);
		try {
			List<EditValidation> validationErrors = service.update(entity);
			if (validationErrors == null || validationErrors.isEmpty()) {
				response = new GlobalRestResponseDto<>(entity);
			} else {
				response = new GlobalRestResponseDto<>(entity, validationErrors);
			}
		} catch (Exception e) {
			response = new GlobalRestResponseDto<>(e.getMessage());
		}

		return response;
	}

	/**
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "{id}", method = RequestMethod.DELETE, produces = "application/json; charset=UTF-8")
	public GlobalRestResponseDto<T> delete(@PathVariable("id") U id) {
		GlobalRestResponseDto<T> response = new GlobalRestResponseDto<>(
				"Unable to delete entity from database with id: " + id);
		try {
			List<EditValidation> validationErrors = service.delete(id);
			if (validationErrors == null || validationErrors.isEmpty()) {
				response = new GlobalRestResponseDto<>();
			} else {
				response = new GlobalRestResponseDto<>(null, validationErrors);
			}
		} catch (Exception e) {
			response = new GlobalRestResponseDto<>(e.getMessage());
		}

		return response;
	}
}


text:
#define DARK_CALIB 100
#define BRIGHT_CALIB 1000
#define EPSILON 0.1
/*
//6 muscles
#define REC_FEM 1
#define SEMIT 4
#define CRAN_SART 5
#define BIC_FEM 2
#define ADDUCTOR 3
#define GRACILIS 6
#define SEMI_MEM 7
#define VAS_LAT 8
#define VAS_MED 10
#define VAS_INT 9
#define CAUD_SART 11
*/

//11 muscles
#define CRAN_SART 1
#define REC_FEM 2
#define BIC_FEM 3
#define GRACILIS 4
#define SEMI_MEM 5
#define ADDUCTOR 6
#define SEMIT 7
#define VAS_LAT 8
#define VAS_INT 9
#define VAS_MED 10
#define CAUD_SART 11

#define NUMBER_OF_MUSCLE 11
#define TRUE 1
#define FALSE 0
#define T2FIT
#define SEG_INTERPOLATE
#define false 0
#define true !false
#define progtitle    "POLYFIT"
#define progversion  "1.0.0"
#define progdate     "08.03.2003"
#define progauther   "K. Hough"
//#define MAXPAIRS 50
#define MAXPAIRS 9
#define MAXORDER 8      /* Can do higher, but who cares?   */
#define PI 3.1415926
#define ECHO_TIME 7    // unit ms 7 or 20
#define DATA_PAIRS 10    // unit ms 10 or 5
#define _POMPE
#define HISTOGRAM_TEXTURE
#define RUN_LENGTH_MATRIX
#define E_CONSTANT 2.71828
#define COOCURRENCE_MATRIX

//#include "DMDT2Fitting.h"
//#include "DMDCalib.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkTransformFileReader.h"
#include "itkAffineTransform.h"
#include "itkTransformFactory.h"
#include "itkResampleImageFilter.h"
#include "itkDivideImageFilter.h"
#include "TextureFeatureCal.h"
//#include "DMDCurveFit.h"
#include <itksys/Process.h>

#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>      /* need functions 'toupper' and tolower'   */
#include <float.h>      /* defines LDBL_MAX*/
#include <math.h>
#include <time.h>       /* for date marking of output data files   */


text:
// Direct Eval, Strict Mode, VariableEnvironment=GlobalEnv, LexicalEnvironment=not GlobalEnv

"use strict";

const {
  assertTrue,
  assertFalse,
  assertSame,
  assertUndefined,
} = Assert;

const global = this;

try { throw 0 } catch (e) {
  eval("function v1(){}");
  assertSame("undefined", typeof v1);
  assertFalse("v1" in global);
  assertUndefined(global["v1"]);
}
try { throw 0 } catch (e) {
  eval("function* v2(){}");
  assertSame("undefined", typeof v2);
  assertFalse("v2" in global);
  assertUndefined(global["v2"]);
}
try { throw 0 } catch (e) {
  eval("class v3{}");
  assertSame("undefined", typeof v3);
  assertFalse("v3" in global);
  assertUndefined(global["v3"]);
}
try { throw 0 } catch (e) {
  eval("var v4");
  assertSame("undefined", typeof v4);
  assertFalse("v4" in global);
  assertUndefined(global["v4"]);
}
try { throw 0 } catch (e) {
  eval("var v5 = 0");
  assertSame("undefined", typeof v5);
  assertFalse("v5" in global);
  assertUndefined(global["v5"]);
}
try { throw 0 } catch (e) {
  eval("let v6");
  assertSame("undefined", typeof v6);
  assertFalse("v6" in global);
  assertUndefined(global["v6"]);
}
try { throw 0 } catch (e) {
  eval("let v7 = 0");
  assertSame("undefined", typeof v7);
  assertFalse("v7" in global);
  assertUndefined(global["v7"]);
}
try { throw 0 } catch (e) {
  eval("const v8 = 0");
  assertSame("undefined", typeof v8);
  assertFalse("v8" in global);
  assertUndefined(global["v8"]);
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.Internal.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
    /// <summary>
    /// Called by the Solution Explorer to show a context menu on the items we add to it
    /// </summary>
    internal class ContextMenuController : IContextMenuController
    {
        private readonly int _menuId;
        private readonly Func<IEnumerable<object>, bool> _shouldShowMenu;
        private readonly Action _updateMenu;

        public ContextMenuController(int menuId, Func<IEnumerable<object>, bool> shouldShowMenu, Action updateMenu)
        {
            _menuId = menuId;
            _shouldShowMenu = shouldShowMenu;
            _updateMenu = updateMenu;
        }

        public bool ShowContextMenu(IEnumerable<object> items, Point location)
        {
            if (!_shouldShowMenu(items))
            {
                return false;
            }

            _updateMenu();

            var shell = Package.GetGlobalService(typeof(SVsUIShell)) as IVsUIShell;
            var guidContextMenu = Guids.RoslynGroupId;
            var locationPoints = new[] { new POINTS() { x = (short)location.X, y = (short)location.Y } };
            return shell != null && ErrorHandler.Succeeded(shell.ShowContextMenu(
                0,
                ref guidContextMenu,
                _menuId,
                locationPoints,
                pCmdTrgtActive: null));
        }
    }
}


text:
package main

import (
	"fmt"

	"github.com/bwmarrin/discordgo"
	"go.uber.org/zap"
)

// DiscordManager holds program state and shares access to resources
type DiscordManager struct {
	app           *App
	DiscordClient *discordgo.Session
	Sender        chan Message
	Receiver      chan Message
	channels      []string
}

// NewDiscordManager sets up a Discord client and prepares it for starting
func NewDiscordManager(app *App, channels []string) *DiscordManager {
	var err error

	dm := DiscordManager{
		app:      app,
		Sender:   make(chan Message),
		Receiver: make(chan Message),
		channels: channels,
	}

	dm.DiscordClient, err = discordgo.New("Bot " + app.config.DiscordToken)
	if err != nil {
		logger.Fatal("failed to create discord client", zap.Error(err))
	}

	return &dm
}

// Close cleans up and shuts down the Discord client
func (dm *DiscordManager) Close() error {
	return dm.DiscordClient.Close()
}

// Connect prepares the Discord client library and connects to the API.
func (dm *DiscordManager) Connect(callback func()) {
	found := false
	// Once the connection is ready, the client is prepared and the daemon multiplexer is started
	dm.DiscordClient.AddHandler(func(s *discordgo.Session, event *discordgo.Ready) {
		dm.DiscordClient.AddHandler(func(s *discordgo.Session, m *discordgo.MessageCreate) {
			found = false
			for _, chn := range dm.channels {
				if chn == m.ChannelID {
					found = true
				}
			}
			if found {
				dm.Receiver <- Message{
					User:   m.Author.Username,
					Text:   m.Content,
					Origin: m.ChannelID,
				}
			}
		})
		go dm.Daemon()
		callback()
	})

	err := dm.DiscordClient.Open()
	if err != nil {
		logger.Fatal("discord client connection error", zap.Error(err))
	}
}

// Daemon passes messages between rediscord and the Discord API
func (dm *DiscordManager) Daemon() {
	for msg := range dm.Sender {
		_, err := dm.DiscordClient.ChannelMessageSend(msg.Destination, fmt.Sprintf("%s: %s", msg.User, msg.Text))
		if err != nil {
			logger.Error("ChannelMessageSend failed", zap.Error(err))
		}
	}
}


text:
/**
 * Classes in this package are internal and are not intended to be accessed directly. Therefore, they are not included in the JavaDocs.
 */
package com.xeiam.xchart.internal;


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/fragment_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="10sp"
            />
    </LinearLayout>

</ScrollView>


text:
<?php

namespace ThreadAndMirror\ProductsBundle\Service\Crawler;

class HarveyNicholsCrawler extends AbstractCrawler
{
	protected function getExpired(DomCrawler $crawler)
	{
		// Page not found
		// try {
		// 	if ($this->getTextFromElement($crawler, '#breadcrumb > ul > li > a', 'last') === 'Page Not Found') {
		// 		return true;
		// 	} else {
		// 		return false;
		// 	}
		// } catch (\Exception $e) { }

		// // Redirected back to category page
		// try {
		// 	if ($this->getTextFromElement($crawler, '.filteroptions') !== null) {
		// 		return true;
		// 	}
		// } catch (\Exception $e) {
			return false;
		// }
	}

	protected function getName(DomCrawler $crawler)
	{
		return $this->getTextFromElement($crawler, '.product-main-info h1 strong');
	}

	protected function getBrandName(DomCrawler $crawler)
	{
		return $this->getTextFromElement($crawler, '.product-main-info h1 a');
	}

	protected function getCategoryName(DomCrawler $crawler)
	{
		return $this->getTextFromElement($crawler, '.breadcrumbs ul li a.last');
	}

	protected function getPid(DomCrawler $crawler)
	{
		return $this->getTextFromElement($crawler, '.product-main-info h1 .product-ids');
	}

	protected function getDescription(DomCrawler $crawler)
	{
		return $this->getTextFromList($crawler, '#product-details .std-description ul:first-child li');
	}

	protected function getNow(DomCrawler $crawler)
	{
		return $this->getTextFromAlternatingElements($crawler, '#product-main-info .regular-price .price', '#product_price');
	}

	protected function getWas(DomCrawler $crawler)
	{
		return $this->getTextFromAlternatingElements($crawler, '#product-main-info .sale-price .price', null);
	}

	protected function getImages(DomCrawler $crawler)
	{
		return $this->getSrcFromList($crawler, '#imageslider li img');
	}

	protected function getPortraits(DomCrawler $crawler)
	{
		return $this->getSrcFromList($crawler, '#imageslider li img');
	}

	protected function getThumbnails(DomCrawler $crawler)
	{
		return $this->getSrcFromList($crawler, '#imageslider li img');
	}

	protected function getAvailableSizes(DomCrawler $crawler)
	{
		return $this->getTextFromElement($crawler, '#product-options-wrapper script:nth-child(3)');
	}

	protected function getStockedSizes(DomCrawler $crawler)
	{
		return $this->getTextFromElement($crawler, '#product-options-wrapper script:nth-child(3)');
	}

	protected function getStyleWith(DomCrawler $crawler)
	{
		return null;
	}
}


text:
var svg = require("svg")

var text = "<rect fill='blue' height='50' width='50'>"
var elem = svg(text);
console.log( elem )


text:
'use strict';

// ### Parent route for backend.
// - All routes for the admin interface have cms/ as their prefix
angular.module('meanbaseApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('cms', {
        url: '/cms',
        templateUrl: 'app/cms/cms.html',
        controller: 'cmsCtrl'
      });
  });


text:
extern id IOSArray_NewArrayWithDimensions(
    Class self, NSUInteger dimensionCount, const jint *dimensionLengths, IOSClass *type);

static IOSObjectArray *IOSObjectArray_NewArray(jint length, IOSClass *type, BOOL retained) {
  IOSObjectArray *array = NSAllocateObject([IOSObjectArray class], length * sizeof(id), nil);
  array->size_ = length;
  array->elementType_ = type; // All IOSClass types are singleton so don't need to retain.
  array->isRetained_ = retained;
  return array;
}

static IOSObjectArray *IOSObjectArray_NewArrayWithObjects(
    jint length, IOSClass *type, BOOL retained, const id *objects) {
  IOSObjectArray *array = IOSObjectArray_NewArray(length, type, retained);
  if (retained) {
    for (jint i = 0; i < length; i++) {
      array->buffer_[i] = [objects[i] retain];
    }
  } else {
    memcpy(array->buffer_, objects, length * sizeof(id));
  }
  return array;
}

@implementation IOSObjectArray

@synthesize elementType = elementType_;

+ (instancetype)newArrayWithLength:(NSUInteger)length type:(IOSClass *)type {
  return IOSObjectArray_NewArray((jint)length, type, YES);
}

+ (instancetype)arrayWithLength:(NSUInteger)length type:(IOSClass *)type {
  return [IOSObjectArray_NewArray((jint)length, type, NO) autorelease];
}

+ (instancetype)newArrayWithObjects:(const id *)objects
                              count:(NSUInteger)count
                               type:(IOSClass *)type {
  return IOSObjectArray_NewArrayWithObjects((jint)count, type, YES, objects);
}

+ (instancetype)arrayWithObjects:(const id *)objects
                           count:(NSUInteger)count
                            type:(IOSClass *)type {
  return [IOSObjectArray_NewArrayWithObjects((jint)count, type, NO, objects) autorelease];
}

+ (instancetype)arrayWithArray:(IOSObjectArray *)array {
  return [IOSObjectArray arrayWithObjects:array->buffer_
                                    count:array->size_
                                     type:array->elementType_];
}

+ (instancetype)arrayWithNSArray:(NSArray *)array type:(IOSClass *)type {
  NSUInteger count = [array count];
  IOSObjectArray *result = IOSObjectArray_NewArray((jint)count, type, NO);
  [array getObjects:result->buffer_ range:NSMakeRange(0, count)];
  return [result autorelease];
}

+ (instancetype)arrayWithDimensions:(NSUInteger)dimensionCount
                            lengths:(const jint *)dimensionLengths
                               type:(IOSClass *)type {
  return [IOSArray_NewArrayWithDimensions(
      self, dimensionCount, dimensionLengths, type) autorelease];
}

+ (instancetype)newArrayWithDimensions:(NSUInteger)dimensionCount
                               lengths:(const jint *)dimensionLengths
                                  type:(IOSClass *)type {
  return IOSArray_NewArrayWithDimensions(self, dimensionCount, dimensionLengths, type);
}

+ (id)iosClassWithType:(IOSClass *)type {
  return [IOSClass arrayClassWithComponentType:type];
}

+ (id)iosClassWithDimensions:(NSUInteger)dimensions type:(IOSClass *)type {
  IOSClass *result = [IOSClass arrayClassWithComponentType:type];
  while (--dimensions > 0) {
    result = [IOSClass arrayClassWithComponentType:result];
  }
  return result;
}

id IOSObjectArray_Get(__unsafe_unretained IOSObjectArray *array, NSUInteger index) {
  IOSArray_checkIndex(array->size_, (jint)index);
  return array->buffer_[index];
}

- (id)objectAtIndex:(NSUInteger)index {
  IOSArray_checkIndex(size_, (jint)index);
  return buffer_[index];
}

#if !defined(J2OBJC_DISABLE_ARRAY_CHECKS)
static void ThrowArrayStoreException(IOSObjectArray *array, id value) {
  NSString *msg = [NSString stringWithFormat:
      @"attempt to add object of type %@ to array with type %@",
      [[value getClass] getName], [array->elementType_ getName]];
  @throw AUTORELEASE([[JavaLangArrayStoreException alloc] initWithNSString:msg]);
}
#endif

static inline id IOSObjectArray_checkValue(
    __unsafe_unretained IOSObjectArray *array, __unsafe_unretained id value) {
#if !defined(J2OBJC_DISABLE_ARRAY_CHECKS)
  if (value && ![array->elementType_ isInstance:value]) {
    ThrowArrayStoreException(array, value);
  }
#endif
  return value;
}

// Same as above, but releases the value before throwing an exception.
static inline void IOSObjectArray_checkRetainedValue(IOSObjectArray *array, id value) {
#if !defined(J2OBJC_DISABLE_ARRAY_CHECKS)
  if (value && ![array->elementType_ isInstance:value]) {
    [value autorelease];
    ThrowArrayStoreException(array, value);
  }
#endif
}

// Same as IOSArray_checkIndex, but releases the value before throwing an
// exception.
static inline void IOSObjectArray_checkIndexRetainedValue(jint size, jint index, id value) {
#if !defined(J2OBJC_DISABLE_ARRAY_CHECKS)
  if (index < 0 || index >= size) {
    [value autorelease];
    IOSArray_throwOutOfBoundsWithMsg(size, index);
  }
#endif
}

id IOSObjectArray_Set(
    __unsafe_unretained IOSObjectArray *array, NSUInteger index, __unsafe_unretained id value) {
  IOSArray_checkIndex(array->size_, (jint)index);
  IOSObjectArray_checkValue(array, value);
  if (array->isRetained_) {
    [array->buffer_[index] autorelease];
    [value retain];
  }
  return array->buffer_[index] = value;
}

id IOSObjectArray_SetAndConsume(IOSObjectArray *array, NSUInteger index, id value) {
  IOSObjectArray_checkIndexRetainedValue(array->size_, (jint)index, value);
  IOSObjectArray_checkRetainedValue(array, value);
  if (array->isRetained_) {
    [array->buffer_[index] autorelease];
  } else {
    [value autorelease];
  }
  return array->buffer_[index] = value;
}

- (id)replaceObjectAtIndex:(NSUInteger)index withObject:(id)value {
  return IOSObjectArray_Set(self, index, value);
}

- (void)getObjects:(NSObject **)buffer length:(NSUInteger)length {
  IOSArray_checkIndex(size_, (jint)length - 1);
  for (NSUInteger i = 0; i < length; i++) {
    id element = buffer_[i];
    buffer[i] = element;
  }
}

void CopyWithMemmove(id __strong *buffer, NSUInteger src, NSUInteger dest, NSUInteger length) {
  NSUInteger releaseStart = dest;
  NSUInteger releaseEnd = dest + length;
  NSUInteger retainStart = src;
  NSUInteger retainEnd = src + length;
  if (retainEnd > releaseStart && retainEnd <= releaseEnd) {
    NSUInteger tmp = releaseStart;
    releaseStart = retainEnd;
    retainEnd = tmp;
  } else if (releaseEnd > retainStart && releaseEnd <= retainEnd) {
    NSUInteger tmp = retainStart;
    retainStart = releaseEnd;
    releaseEnd = tmp;
  }
  for (NSUInteger i = releaseStart; i < releaseEnd; i++) {
    [buffer[i] autorelease];
  }
  memmove(buffer + dest, buffer + src, length * sizeof(id));
  for (NSUInteger i = retainStart; i < retainEnd; i++) {
    [buffer[i] retain];
  }
}

- (void)arraycopy:(jint)offset
      destination:(IOSArray *)destination
        dstOffset:(jint)dstOffset
           length:(jint)length {
  IOSArray_checkRange(size_, offset, length);
  IOSArray_checkRange(destination->size_, dstOffset, length);
  IOSObjectArray *dest = (IOSObjectArray *) destination;

#ifdef J2OBJC_DISABLE_ARRAY_TYPE_CHECKS
  BOOL skipElementCheck = YES;
#else
  // If dest element type can be assigned to this array, then all of its
  // elements are assignable and therefore don't need to be individually
  // checked.
  BOOL skipElementCheck = [dest->elementType_ isAssignableFrom:elementType_];
#endif

  if (self == dest) {
    if (dest->isRetained_) {
      CopyWithMemmove(buffer_, offset, dstOffset, length);
    } else {
      memmove(buffer_ + dstOffset, buffer_ + offset, length * sizeof(id));
    }
  } else {
    if (dest->isRetained_) {
      if (skipElementCheck) {
        for (jint i = 0; i < length; i++) {
          [dest->buffer_[i + dstOffset] autorelease];
          dest->buffer_[i + dstOffset] = [buffer_[i + offset] retain];
        }
      } else {
        for (jint i = 0; i < length; i++) {
          id newElement = IOSObjectArray_checkValue(dest, buffer_[i + offset]);
          [dest->buffer_[i + dstOffset] autorelease];
          [newElement retain];
          dest->buffer_[i + dstOffset] = newElement;
        }
      }
    } else {
      if (skipElementCheck) {
        memcpy(dest->buffer_ + dstOffset, buffer_ + offset, length * sizeof(id));
      } else {
        for (jint i = 0; i < length; i++) {
          dest->buffer_[i + dstOffset] = IOSObjectArray_checkValue(dest, buffer_[i + offset]);
        }
      }
    }
  }
}

- (id)copyWithZone:(NSZone *)zone {
  IOSObjectArray *result = IOSObjectArray_NewArray(size_, elementType_, YES);
  for (jint i = 0; i < size_; i++) {
    result->buffer_[i] = [buffer_[i] retain];
  }
  return result;
}

- (NSString *)descriptionOfElementAtIndex:(jint)index {
  return (NSString *) [buffer_[index] description];
}

- (id)retain {
  if (!isRetained_) {
    for (jint i = 0; i < size_; i++) {
      [buffer_[i] retain];
    }
    isRetained_ = YES;
  }
  return [super retain];
}

- (void)dealloc {
  if (isRetained_) {
    for (jint i = 0; i < size_; i++) {
      [buffer_[i] release];
    }
  }
  [super dealloc];
}

- (NSUInteger)countByEnumeratingWithState:(NSFastEnumerationState *)state
                                  objects:(__unsafe_unretained id *)stackbuf
                                    count:(NSUInteger)len {
  if (state->state == 0) {
    state->mutationsPtr = (unsigned long *) (ARCBRIDGE void *) self;
    state->itemsPtr = (__unsafe_unretained id *) (void *) buffer_;
    state->state = 1;
    return size_;
  } else {
    return 0;
  }
}

- (NSArray *)memDebugStrongReferences {
  NSMutableArray *result = [NSMutableArray array];
  for (jint i = 0; i < size_; i++) {
    [result addObject:[JreMemDebugStrongReference strongReferenceWithObject:buffer_[i] name:@"element"]];
  }
  return result;
}

@end


text:
package com.deleidos.rtws.commons.util;

import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.junit.Test;

import com.deleidos.rtws.commons.util.BugCheckException;

public class BugCheckExceptionTest extends TestCase {

	public BugCheckExceptionTest(String testName) {
		super(testName);
	}

	public static TestSuite suite() {
		TestSuite suite= new TestSuite();
	    suite.addTest(new BugCheckExceptionTest("testConstructor"));
	    return suite;
	}

    /**
     * Sets up the test fixture.
     * (Called before every test case method.)
     */
    protected void setUp() {
    }

    /**
     * Tears down the test fixture.
     * (Called after every test case method.)
     */
    protected void tearDown() {
    }

	@Test
	public void testConstructor() {
		BugCheckException obj1 = new BugCheckException("Exception #1");
		assertNotNull(obj1);
		assertEquals(obj1.getMessage(), "Exception #1");

		BugCheckException obj2 = new BugCheckException("Exception #2", new Exception());
		assertNotNull(obj2);
	}

}


text:
import { connect } from 'react-redux';
import { logOut } from './actions';
import LogoutDialog from './LogoutDialog';

const mapActionToProps = (dispatch) => ({
	logOut: () => {
		dispatch(logOut());
	}
});

export default connect(null, mapActionToProps)(LogoutDialog);


text:
function Storage() {}

Storage.prototype.set = function(key, val, local, cb) {
  if (typeof local === 'function') cb = local

  localStorage.setItem(key, JSON.stringify(val))
  if (cb) cb()
}

Storage.prototype.get = function(key, local, cb) {
  if (typeof local === 'function') cb = local

  var val = parse(localStorage.getItem(key))
  if (cb) cb(val)
  else return val

  function parse(val) {
    try {
      return JSON.parse(val)
    } catch (e) {
      return val
    }
  }
}


text:
package ru.job4j.listspeed;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;

/**
 * Класс для сравнения скорости добавления и удаления э-тов в коллекции.
 * @author - Egor K.
 * @since - 28.09.17
 */
public class Speed {
    /**
     * Аррай лист.
     */
    private List<String> arrayList;
    /**
     * ЛинкедЛист.
     */
    private List<String> linkedList;
    /**
     * ТриСет.
     */
    private Set<String> treeSet;

    /**
     * Геттр для тестов.
     * @return arrayList
     */
    public List<String> getArrayList() {
        return arrayList;
    }

    /**
     * Геттр для тестов.
     * @return linkedList
     */
    public List<String> getLinkedList() {
        return linkedList;
    }

    /**
     * Геттр для тестов.
     * @return treeSet
     */
    public Set<String> getTreeSet() {
        return treeSet;
    }

    /**
     * Генерируем ArrayList с уникальными(скорее всего) строками и копируем его значения в.
     * LinkedList и TreeSet.
     * @param length размер коллекций.
     */
    public void generateLists(int length) {

        arrayList = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            arrayList.add(String.valueOf(System.currentTimeMillis() + new Random().nextInt()));
        }

        linkedList = new LinkedList<>();
        linkedList.addAll(arrayList);

        treeSet = new TreeSet<>();
        treeSet.addAll(arrayList);
    }

    /**
     * Метод для подсчета времени добавления эл-тов в коллекции.
     * Эл-ты добавляем в конец коллекций.
     * @param collection коллекция.
     * @param amount кол-во добавляемых эл-тов.
     * @return время процесса.
     */
    public long add(Collection<String> collection, int amount) {

        long start = System.currentTimeMillis();
        for (int i = 0; i < amount; i++) {
            collection.add(String.valueOf(System.currentTimeMillis() + new Random().nextInt()));
        }
        long finish = System.currentTimeMillis();
        return finish - start;
    }
    /**
     * Метод для подсчета времени удаления эл-тов из коллекции.
     * Эл-ты удаляем сначала коллекций.
     * @param collection коллекция.
     * @param amount кол-во удаляемых эл-тов.
     * @return время процесса.
     */
    public long delete(Collection<String> collection, int amount) {

        int count = 0;
        long start = System.currentTimeMillis();
        Iterator iterator = collection.iterator();
        while (iterator.hasNext()) {
            if (count < amount) {
                iterator.next();
                iterator.remove();
                count++;
            } else {
                break;
            }

        }
        long finish = System.currentTimeMillis();
        return finish - start;
    }
}


text:
package org.apache.flink.table.functions.python;

import org.apache.flink.annotation.Internal;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.typeutils.RowTypeInfo;
import org.apache.flink.table.catalog.DataTypeFactory;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.table.types.DataType;
import org.apache.flink.table.types.inference.TypeInference;
import org.apache.flink.table.types.inference.TypeStrategies;
import org.apache.flink.table.types.utils.TypeConversions;
import org.apache.flink.types.Row;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/** The wrapper of user defined python table function. */
@Internal
public class PythonTableFunction extends TableFunction<Row> implements PythonFunction {

    private static final long serialVersionUID = 1L;

    private final String name;
    private final byte[] serializedScalarFunction;
    private final TypeInformation[] inputTypes;
    private final RowTypeInfo resultType;
    private final PythonFunctionKind pythonFunctionKind;
    private final boolean deterministic;
    private final PythonEnv pythonEnv;
    private final boolean takesRowAsInput;

    public PythonTableFunction(
            String name,
            byte[] serializedScalarFunction,
            TypeInformation[] inputTypes,
            RowTypeInfo resultType,
            PythonFunctionKind pythonFunctionKind,
            boolean deterministic,
            boolean takesRowAsInput,
            PythonEnv pythonEnv) {
        this.name = name;
        this.serializedScalarFunction = serializedScalarFunction;
        this.inputTypes = inputTypes;
        this.resultType = resultType;
        this.pythonFunctionKind = pythonFunctionKind;
        this.deterministic = deterministic;
        this.pythonEnv = pythonEnv;
        this.takesRowAsInput = takesRowAsInput;
    }

    public void eval(Object... args) {
        throw new UnsupportedOperationException(
                "This method is a placeholder and should not be called.");
    }

    @Override
    public byte[] getSerializedPythonFunction() {
        return serializedScalarFunction;
    }

    @Override
    public PythonEnv getPythonEnv() {
        return pythonEnv;
    }

    @Override
    public PythonFunctionKind getPythonFunctionKind() {
        return pythonFunctionKind;
    }

    @Override
    public boolean takesRowAsInput() {
        return takesRowAsInput;
    }

    @Override
    public boolean isDeterministic() {
        return deterministic;
    }

    @Override
    public TypeInformation[] getParameterTypes(Class[] signature) {
        if (inputTypes != null) {
            return inputTypes;
        } else {
            return super.getParameterTypes(signature);
        }
    }

    @Override
    public TypeInformation<Row> getResultType() {
        return resultType;
    }

    @Override
    public TypeInference getTypeInference(DataTypeFactory typeFactory) {
        TypeInference.Builder builder = TypeInference.newBuilder();
        if (inputTypes != null) {
            final List<DataType> argumentDataTypes =
                    Stream.of(inputTypes)
                            .map(TypeConversions::fromLegacyInfoToDataType)
                            .collect(Collectors.toList());
            builder.typedArguments(argumentDataTypes);
        }
        return builder.outputTypeStrategy(
                        TypeStrategies.explicit(
                                TypeConversions.fromLegacyInfoToDataType(resultType)))
                .build();
    }

    @Override
    public String toString() {
        return name;
    }
}


text:
using namespace std;

namespace
{
using namespace diff_scheme;

char const kMaxVersionKey[] = "max_version";
char const kMwmsKey[] = "mwms";
char const kNameKey[] = "name";
char const kSizeKey[] = "size";
char const kVersionKey[] = "version";

auto const kTimeoutInSeconds = 5.0;

string SerializeCheckerData(Checker::LocalMapsInfo const & info)
{
  auto mwmsArrayNode = my::NewJSONArray();
  for (auto const & nameAndVersion : info.m_localMaps)
  {
    auto node = my::NewJSONObject();
    ToJSONObject(*node, kNameKey, nameAndVersion.first);
    ToJSONObject(*node, kVersionKey, nameAndVersion.second);
    json_array_append_new(mwmsArrayNode.get(), node.release());
  }

  auto const root = my::NewJSONObject();
  json_object_set_new(root.get(), kMwmsKey, mwmsArrayNode.release());
  ToJSONObject(*root, kMaxVersionKey, info.m_currentDataVersion);
  unique_ptr<char, JSONFreeDeleter> buffer(json_dumps(root.get(), JSON_COMPACT | JSON_ENSURE_ASCII));
  return buffer.get();
}

NameFileInfoMap DeserializeResponse(string const & response, Checker::NameVersionMap const & nameVersionMap)
{
  if (response.empty())
  {
    LOG(LERROR, ("Diff response shouldn't be empty."));
    return NameFileInfoMap{};
  }

  my::Json const json(response.c_str());
  if (json.get() == nullptr)
    return NameFileInfoMap{};

  auto const root = json_object_get(json.get(), kMwmsKey);
  if (root == nullptr || !json_is_array(root))
    return NameFileInfoMap{};

  auto const size = json_array_size(root);
  if (size == 0 || size != nameVersionMap.size())
  {
    LOG(LERROR, ("Diff list size in response must be equal to mwm list size in request."));
    return NameFileInfoMap{};
  }

  NameFileInfoMap diffs;

  for (size_t i = 0; i < size; ++i)
  {
    auto const node = json_array_get(root, i);

    if (!node)
    {
      LOG(LERROR, ("Incorrect server response."));
      return NameFileInfoMap{};
    }

    string name;
    FromJSONObject(node, kNameKey, name);
    int64_t size;
    FromJSONObject(node, kSizeKey, size);
    // Invalid size. The diff is not available.
    if (size < 0)
      continue;

    if (nameVersionMap.find(name) == nameVersionMap.end())
    {
      LOG(LERROR, ("Incorrect country name in response:", name));
      return NameFileInfoMap{};
    }

    FileInfo info(size, nameVersionMap.at(name));
    diffs.emplace(move(name), move(info));
  }

  return diffs;
}
}  // namespace

namespace diff_scheme
{
// static
void Checker::Check(LocalMapsInfo const & info, Callback const & fn)
{
  // TODO(Vlad): Log falling back to old scheme.
  if (info.m_localMaps.empty())
  {
    fn(NameFileInfoMap{});
    return;
  }

  threads::SimpleThread thread([info, fn] {
    platform::HttpClient request(DIFF_LIST_URL);
    string const body = SerializeCheckerData(info);
    ASSERT(!body.empty(), ());
    request.SetBodyData(body, "application/json");
    request.SetTimeout(kTimeoutInSeconds);
    NameFileInfoMap diffs;
    if (request.RunHttpRequest() && !request.WasRedirected() && request.ErrorCode() == 200)
      diffs = DeserializeResponse(request.ServerResponse(), info.m_localMaps);

    GetPlatform().RunOnGuiThread([fn, diffs] {
      fn(diffs);
    });
  });
  thread.detach();
}
}  // namespace diff_scheme