text:
import contextlib
import copy
import os

import mock

from cinder import exception
from cinder.image import image_utils
from cinder import test
from cinder.volume.drivers import smbfs

class SmbFsTestCase(test.TestCase):

    _FAKE_SHARE = '//1.2.3.4/share1'
    _FAKE_MNT_BASE = '/mnt'
    _FAKE_VOLUME_NAME = 'volume-4f711859-4928-4cb7-801a-a50c37ceaccc'
    _FAKE_TOTAL_SIZE = '2048'
    _FAKE_TOTAL_AVAILABLE = '1024'
    _FAKE_TOTAL_ALLOCATED = 1024
    _FAKE_VOLUME = {'id': '4f711859-4928-4cb7-801a-a50c37ceaccc',
                    'size': 1,
                    'provider_location': _FAKE_SHARE,
                    'name': _FAKE_VOLUME_NAME,
                    'status': 'available'}
    _FAKE_MNT_POINT = os.path.join(_FAKE_MNT_BASE, 'fake_hash')
    _FAKE_VOLUME_PATH = os.path.join(_FAKE_MNT_POINT, _FAKE_VOLUME_NAME)
    _FAKE_SNAPSHOT_ID = '5g811859-4928-4cb7-801a-a50c37ceacba'
    _FAKE_SNAPSHOT = {'id': _FAKE_SNAPSHOT_ID,
                      'volume': _FAKE_VOLUME,
                      'status': 'available',
                      'volume_size': 1}
    _FAKE_SNAPSHOT_PATH = (
        _FAKE_VOLUME_PATH + '-snapshot' + _FAKE_SNAPSHOT_ID)
    _FAKE_SHARE_OPTS = '-o username=Administrator,password=12345'
    _FAKE_OPTIONS_DICT = {'username': 'Administrator',
                          'password': '12345'}

    _FAKE_LISTDIR = [_FAKE_VOLUME_NAME, _FAKE_VOLUME_NAME + '.vhd',
                     _FAKE_VOLUME_NAME + '.vhdx', 'fake_folder']
    _FAKE_SMBFS_CONFIG = mock.MagicMock()
    _FAKE_SMBFS_CONFIG.smbfs_oversub_ratio = 2
    _FAKE_SMBFS_CONFIG.smbfs_used_ratio = 0.5
    _FAKE_SMBFS_CONFIG.smbfs_shares_config = '/fake/config/path'
    _FAKE_SMBFS_CONFIG.smbfs_default_volume_format = 'raw'
    _FAKE_SMBFS_CONFIG.smbfs_sparsed_volumes = False

    def setUp(self):
        super(SmbFsTestCase, self).setUp()
        smbfs.SmbfsDriver.__init__ = lambda x: None
        self._smbfs_driver = smbfs.SmbfsDriver()
        self._smbfs_driver._remotefsclient = mock.Mock()
        self._smbfs_driver._local_volume_dir = mock.Mock(
            return_value=self._FAKE_MNT_POINT)
        self._smbfs_driver._execute = mock.Mock()
        self._smbfs_driver.base = self._FAKE_MNT_BASE

    def test_delete_volume(self):
        drv = self._smbfs_driver
        fake_vol_info = self._FAKE_VOLUME_PATH + '.info'

        drv._ensure_share_mounted = mock.MagicMock()
        fake_ensure_mounted = drv._ensure_share_mounted

        drv._local_volume_dir = mock.Mock(
            return_value=self._FAKE_MNT_POINT)
        drv.get_active_image_from_info = mock.Mock(
            return_value=self._FAKE_VOLUME_NAME)
        drv._delete = mock.Mock()
        drv._local_path_volume_info = mock.Mock(
            return_value=fake_vol_info)

        with mock.patch('os.path.exists', lambda x: True):
            drv.delete_volume(self._FAKE_VOLUME)

            fake_ensure_mounted.assert_called_once_with(self._FAKE_SHARE)
            drv._delete.assert_any_call(
                self._FAKE_VOLUME_PATH)
            drv._delete.assert_any_call(fake_vol_info)

    def _test_setup(self, config, share_config_exists=True):
        fake_exists = mock.Mock(return_value=share_config_exists)
        fake_ensure_mounted = mock.MagicMock()
        self._smbfs_driver._ensure_shares_mounted = fake_ensure_mounted
        self._smbfs_driver.configuration = config

        with mock.patch('os.path.exists', fake_exists):
            if not (config.smbfs_shares_config and share_config_exists and
                    config.smbfs_oversub_ratio > 0 and
                    0 <= config.smbfs_used_ratio <= 1):
                self.assertRaises(exception.SmbfsException,
                                  self._smbfs_driver.do_setup,
                                  None)
            else:
                self._smbfs_driver.do_setup(None)
                self.assertEqual(self._smbfs_driver.shares, {})
                fake_ensure_mounted.assert_called_once_with()

    def test_setup_missing_shares_config_option(self):
        fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
        fake_config.smbfs_shares_config = None
        self._test_setup(fake_config, None)

    def test_setup_missing_shares_config_file(self):
        self._test_setup(self._FAKE_SMBFS_CONFIG, False)

    def test_setup_invlid_oversub_ratio(self):
        fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
        fake_config.smbfs_oversub_ratio = -1
        self._test_setup(fake_config)

    def test_setup_invalid_used_ratio(self):
        fake_config = copy.copy(self._FAKE_SMBFS_CONFIG)
        fake_config.smbfs_used_ratio = -1
        self._test_setup(fake_config)

    def _test_create_volume(self, volume_exists=False, volume_format=None):
        fake_method = mock.MagicMock()
        self._smbfs_driver.configuration = copy.copy(self._FAKE_SMBFS_CONFIG)
        self._smbfs_driver._set_rw_permissions_for_all = mock.MagicMock()
        fake_set_permissions = self._smbfs_driver._set_rw_permissions_for_all
        self._smbfs_driver.get_volume_format = mock.MagicMock()

        windows_image_format = False
        fake_vol_path = self._FAKE_VOLUME_PATH
        self._smbfs_driver.get_volume_format.return_value = volume_format

        if volume_format:
            if volume_format in ('vhd', 'vhdx'):
                windows_image_format = volume_format
                if volume_format == 'vhd':
                    windows_image_format = 'vpc'
                method = '_create_windows_image'
                fake_vol_path += '.' + volume_format
            else:
                method = '_create_%s_file' % volume_format
                if volume_format == 'sparsed':
                    self._smbfs_driver.configuration.smbfs_sparsed_volumes = (
                        True)
        else:
            method = '_create_regular_file'

        setattr(self._smbfs_driver, method, fake_method)

        with mock.patch('os.path.exists', new=lambda x: volume_exists):
            if volume_exists:
                self.assertRaises(exception.InvalidVolume,
                                  self._smbfs_driver._do_create_volume,
                                  self._FAKE_VOLUME)
                return

            self._smbfs_driver._do_create_volume(self._FAKE_VOLUME)
            if windows_image_format:
                fake_method.assert_called_once_with(
                    fake_vol_path,
                    self._FAKE_VOLUME['size'],
                    windows_image_format)
            else:
                fake_method.assert_called_once_with(
                    fake_vol_path, self._FAKE_VOLUME['size'])
            fake_set_permissions.assert_called_once_with(fake_vol_path)

    def test_create_existing_volume(self):
        self._test_create_volume(volume_exists=True)

    def test_create_vhdx(self):
        self._test_create_volume(volume_format='vhdx')

    def test_create_qcow2(self):
        self._test_create_volume(volume_format='qcow2')

    def test_create_sparsed(self):
        self._test_create_volume(volume_format='sparsed')

    def test_create_regular(self):
        self._test_create_volume()

    def _test_find_share(self, existing_mounted_shares=True,
                         eligible_shares=True):
        if existing_mounted_shares:
            mounted_shares = ('fake_share1', 'fake_share2', 'fake_share3')
        else:
            mounted_shares = None

        self._smbfs_driver._mounted_shares = mounted_shares
        self._smbfs_driver._is_share_eligible = mock.Mock(
            return_value=eligible_shares)
        fake_capacity_info = ((2, 1, 5), (2, 1, 4), (2, 1, 1))
        self._smbfs_driver._get_capacity_info = mock.Mock(
            side_effect=fake_capacity_info)

        if not mounted_shares:
            self.assertRaises(exception.SmbfsNoSharesMounted,
                              self._smbfs_driver._find_share,
                              self._FAKE_VOLUME['size'])
        elif not eligible_shares:
            self.assertRaises(exception.SmbfsNoSuitableShareFound,
                              self._smbfs_driver._find_share,
                              self._FAKE_VOLUME['size'])
        else:
            ret_value = self._smbfs_driver._find_share(
                self._FAKE_VOLUME['size'])
            # The eligible share with the minimum allocated space
            # will be selected
            self.assertEqual(ret_value, 'fake_share3')

    def test_find_share(self):
        self._test_find_share()

    def test_find_share_missing_mounted_shares(self):
        self._test_find_share(existing_mounted_shares=False)

    def test_find_share_missing_eligible_shares(self):
        self._test_find_share(eligible_shares=False)

    def _test_is_share_eligible(self, capacity_info, volume_size):
        self._smbfs_driver._get_capacity_info = mock.Mock(
            return_value=[float(x << 30) for x in capacity_info])
        self._smbfs_driver.configuration = self._FAKE_SMBFS_CONFIG
        return self._smbfs_driver._is_share_eligible(self._FAKE_SHARE,
                                                     volume_size)

    def test_share_volume_above_used_ratio(self):
        fake_capacity_info = (4, 1, 1)
        fake_volume_size = 2
        ret_value = self._test_is_share_eligible(fake_capacity_info,
                                                 fake_volume_size)
        self.assertEqual(ret_value, False)

    def test_eligible_share(self):
        fake_capacity_info = (4, 4, 0)
        fake_volume_size = 1
        ret_value = self._test_is_share_eligible(fake_capacity_info,
                                                 fake_volume_size)
        self.assertEqual(ret_value, True)

    def test_share_volume_above_oversub_ratio(self):
        fake_capacity_info = (4, 4, 7)
        fake_volume_size = 2
        ret_value = self._test_is_share_eligible(fake_capacity_info,
                                                 fake_volume_size)
        self.assertEqual(ret_value, False)

    def test_share_reserved_above_oversub_ratio(self):
        fake_capacity_info = (4, 4, 10)
        fake_volume_size = 1
        ret_value = self._test_is_share_eligible(fake_capacity_info,
                                                 fake_volume_size)
        self.assertEqual(ret_value, False)

    def test_parse_options(self):
        (opt_list,
         opt_dict) = self._smbfs_driver.parse_options(
            self._FAKE_SHARE_OPTS)
        expected_ret = ([], self._FAKE_OPTIONS_DICT)
        self.assertEqual(expected_ret, (opt_list, opt_dict))

    def test_parse_credentials(self):
        fake_smb_options = r'-o user=MyDomain\Administrator,noperm'
        expected_flags = '-o username=Administrator,noperm'
        flags = self._smbfs_driver.parse_credentials(fake_smb_options)
        self.assertEqual(expected_flags, flags)

    def test_get_volume_path(self):
        self._smbfs_driver.get_volume_format = mock.Mock(
            return_value='vhd')
        self._smbfs_driver._local_volume_dir = mock.Mock(
            return_value=self._FAKE_MNT_POINT)

        expected = self._FAKE_VOLUME_PATH + '.vhd'

        ret_val = self._smbfs_driver.local_path(self._FAKE_VOLUME)
        self.assertEqual(expected, ret_val)

    def test_initialize_connection(self):
        self._smbfs_driver.get_active_image_from_info = mock.Mock(
            return_value=self._FAKE_VOLUME_NAME)
        self._smbfs_driver._get_mount_point_base = mock.Mock(
            return_value=self._FAKE_MNT_BASE)
        self._smbfs_driver.shares = {self._FAKE_SHARE: self._FAKE_SHARE_OPTS}
        self._smbfs_driver._qemu_img_info = mock.Mock(
            return_value=mock.Mock(file_format='raw'))

        fake_data = {'export': self._FAKE_SHARE,
                     'format': 'raw',
                     'name': self._FAKE_VOLUME_NAME,
                     'options': self._FAKE_SHARE_OPTS}
        expected = {
            'driver_volume_type': 'smbfs',
            'data': fake_data,
            'mount_point_base': self._FAKE_MNT_BASE}
        ret_val = self._smbfs_driver.initialize_connection(
            self._FAKE_VOLUME, None)

        self.assertEqual(expected, ret_val)

    def _test_extend_volume(self, extend_failed=False, image_format='raw'):
        drv = self._smbfs_driver

        drv.local_path = mock.Mock(
            return_value=self._FAKE_VOLUME_PATH)
        drv._check_extend_volume_support = mock.Mock(
            return_value=True)
        drv._is_file_size_equal = mock.Mock(
            return_value=not extend_failed)
        drv._qemu_img_info = mock.Mock(
            return_value=mock.Mock(file_format=image_format))
        drv._delete = mock.Mock()

        with contextlib.nested(
                mock.patch.object(image_utils, 'resize_image'),
                mock.patch.object(image_utils, 'convert_image')) as (
                    fake_resize, fake_convert):
            if extend_failed:
                self.assertRaises(exception.ExtendVolumeError,
                                  drv._extend_volume,
                                  self._FAKE_VOLUME, mock.sentinel.new_size)
            else:
                drv._extend_volume(
                    self._FAKE_VOLUME,
                    mock.sentinel.new_size)
                if image_format in (drv._DISK_FORMAT_VHDX,
                                    drv._DISK_FORMAT_VHD_LEGACY):
                    fake_tmp_path = self._FAKE_VOLUME_PATH + '.tmp'
                    fake_convert.assert_any_call(self._FAKE_VOLUME_PATH,
                                                 fake_tmp_path, 'raw')
                    fake_resize.assert_called_once_with(
                        fake_tmp_path, mock.sentinel.new_size)
                    fake_convert.assert_any_call(fake_tmp_path,
                                                 self._FAKE_VOLUME_PATH,
                                                 image_format)
                else:
                    fake_resize.assert_called_once_with(
                        self._FAKE_VOLUME_PATH, mock.sentinel.new_size)

    def test_extend_volume(self):
        self._test_extend_volume()

    def test_extend_volume_failed(self):
        self._test_extend_volume(extend_failed=True)

    def test_extend_vhd_volume(self):
        self._test_extend_volume(image_format='vpc')

    def _test_check_extend_support(self, has_snapshots=False,
                                   is_eligible=True):
        self._smbfs_driver.local_path = mock.Mock(
            return_value=self._FAKE_VOLUME_PATH)

        if has_snapshots:
            active_file_path = self._FAKE_SNAPSHOT_PATH
        else:
            active_file_path = self._FAKE_VOLUME_PATH

        self._smbfs_driver.get_active_image_from_info = mock.Mock(
            return_value=active_file_path)
        self._smbfs_driver._is_share_eligible = mock.Mock(
            return_value=is_eligible)

        if has_snapshots:
            self.assertRaises(exception.InvalidVolume,
                              self._smbfs_driver._check_extend_volume_support,
                              self._FAKE_VOLUME, 2)
        elif not is_eligible:
            self.assertRaises(exception.ExtendVolumeError,
                              self._smbfs_driver._check_extend_volume_support,
                              self._FAKE_VOLUME, 2)
        else:
            self._smbfs_driver._check_extend_volume_support(
                self._FAKE_VOLUME, 2)
            self._smbfs_driver._is_share_eligible.assert_called_once_with(
                self._FAKE_SHARE, 1)

    def test_check_extend_support(self):
        self._test_check_extend_support()

    def test_check_extend_volume_with_snapshots(self):
        self._test_check_extend_support(has_snapshots=True)

    def test_check_extend_volume_uneligible_share(self):
        self._test_check_extend_support(is_eligible=False)

    def test_create_volume_from_in_use_snapshot(self):
        fake_snapshot = {'status': 'in-use'}
        self.assertRaises(
            exception.InvalidSnapshot,
            self._smbfs_driver.create_volume_from_snapshot,
            self._FAKE_VOLUME, fake_snapshot)

    def test_copy_volume_from_snapshot(self):
        drv = self._smbfs_driver

        fake_volume_info = {self._FAKE_SNAPSHOT_ID: 'fake_snapshot_file_name'}
        fake_img_info = mock.MagicMock()
        fake_img_info.backing_file = self._FAKE_VOLUME_NAME

        drv.get_volume_format = mock.Mock(
            return_value='raw')
        drv._local_path_volume_info = mock.Mock(
            return_value=self._FAKE_VOLUME_PATH + '.info')
        drv._local_volume_dir = mock.Mock(
            return_value=self._FAKE_MNT_POINT)
        drv._read_info_file = mock.Mock(
            return_value=fake_volume_info)
        drv._qemu_img_info = mock.Mock(
            return_value=fake_img_info)
        drv.local_path = mock.Mock(
            return_value=self._FAKE_VOLUME_PATH[:-1])
        drv._extend_volume = mock.Mock()
        drv._set_rw_permissions_for_all = mock.Mock()

        with mock.patch.object(image_utils, 'convert_image') as (
                fake_convert_image):
            drv._copy_volume_from_snapshot(
                self._FAKE_SNAPSHOT, self._FAKE_VOLUME,
                self._FAKE_VOLUME['size'])
            drv._extend_volume.assert_called_once_with(
                self._FAKE_VOLUME, self._FAKE_VOLUME['size'])
            fake_convert_image.assert_called_once_with(
                self._FAKE_VOLUME_PATH, self._FAKE_VOLUME_PATH[:-1], 'raw')

    def test_ensure_mounted(self):
        self._smbfs_driver.shares = {self._FAKE_SHARE: self._FAKE_SHARE_OPTS}

        self._smbfs_driver._ensure_share_mounted(self._FAKE_SHARE)
        self._smbfs_driver._remotefsclient.mount.assert_called_once_with(
            self._FAKE_SHARE, self._FAKE_SHARE_OPTS.split())

    def _test_copy_image_to_volume(self, unsupported_qemu_version=False,
                                   wrong_size_after_fetch=False):
        drv = self._smbfs_driver

        vol_size_bytes = self._FAKE_VOLUME['size'] << 30
        fake_image_service = mock.MagicMock()
        fake_image_service.show.return_value = (
            {'id': 'fake_image_id', 'disk_format': 'raw'})

        fake_img_info = mock.MagicMock()

        if wrong_size_after_fetch:
            fake_img_info.virtual_size = 2 * vol_size_bytes
        else:
            fake_img_info.virtual_size = vol_size_bytes

        if unsupported_qemu_version:
            qemu_version = [1, 5]
        else:
            qemu_version = [1, 7]

        drv.get_volume_format = mock.Mock(
            return_value=drv._DISK_FORMAT_VHDX)
        drv.local_path = mock.Mock(
            return_value=self._FAKE_VOLUME_PATH)
        drv.get_qemu_version = mock.Mock(
            return_value=qemu_version)
        drv._do_extend_volume = mock.Mock()
        drv.configuration = mock.MagicMock()
        drv.configuration.volume_dd_blocksize = (
            mock.sentinel.block_size)

        exc = None
        with contextlib.nested(
            mock.patch.object(image_utils,
                              'fetch_to_volume_format'),
            mock.patch.object(image_utils,
                              'qemu_img_info')) as (
                fake_fetch,
                fake_qemu_img_info):

            if wrong_size_after_fetch:
                exc = exception.ImageUnacceptable
            elif unsupported_qemu_version:
                exc = exception.InvalidVolume

            fake_qemu_img_info.return_value = fake_img_info

            if exc:
                self.assertRaises(
                    exc, drv.copy_image_to_volume,
                    mock.sentinel.context, self._FAKE_VOLUME,
                    fake_image_service,
                    mock.sentinel.image_id)
            else:
                drv.copy_image_to_volume(
                    mock.sentinel.context, self._FAKE_VOLUME,
                    fake_image_service,
                    mock.sentinel.image_id)
                fake_fetch.assert_called_once_with(
                    mock.sentinel.context, fake_image_service,
                    mock.sentinel.image_id, self._FAKE_VOLUME_PATH,
                    drv._DISK_FORMAT_VHDX,
                    mock.sentinel.block_size)
                drv._do_extend_volume.assert_called_once_with(
                    self._FAKE_VOLUME_PATH,
                    self._FAKE_VOLUME['size'],
                    self._FAKE_VOLUME['name'])

    def test_copy_image_to_volume(self):
        self._test_copy_image_to_volume()

    def test_copy_image_to_volume_wrong_size_after_fetch(self):
        self._test_copy_image_to_volume(wrong_size_after_fetch=True)

    def test_copy_image_to_volume_unsupported_qemu_version(self):
        self._test_copy_image_to_volume(unsupported_qemu_version=True)

    def test_get_capacity_info(self):
        fake_block_size = 4096.0
        fake_total_blocks = 1024
        fake_avail_blocks = 512
        fake_total_allocated = fake_total_blocks * fake_block_size

        fake_df = ('%s %s %s' % (fake_block_size, fake_total_blocks,
                                 fake_avail_blocks), None)
        fake_du = (str(fake_total_allocated), None)

        self._smbfs_driver._get_mount_point_for_share = mock.Mock(
            return_value=self._FAKE_MNT_POINT)
        self._smbfs_driver._execute = mock.Mock(
            side_effect=(fake_df, fake_du))

        ret_val = self._smbfs_driver._get_capacity_info(self._FAKE_SHARE)
        expected = (fake_block_size * fake_total_blocks,
                    fake_block_size * fake_avail_blocks,
                    fake_total_allocated)
        self.assertEqual(expected, ret_val)


text:
module AdAgency
  class PrintShop

    def self.get_version
      File.readlines("VERSION").first.chomp
    end

    def self.history_file?
      File.exist?("History.txt")
    end

    def self.history_lines
      File.readlines("History.txt")
    end

    def self.print_ad(spec, outfile=STDOUT)
      version = get_version
      maj_min = version[/^\d+\.\d+/]
      outfile.puts "Announcing #{spec.name} version #{version}"
      outfile.puts spec.summary
      outfile.puts
      outfile.puts spec.description
      outfile.puts
      if history_file?
        outfile.puts "Changes:"
        outfile.puts
        history_lines.each do |line|
          if line =~ /^=+\s+v?(\d+\.\d+)\./
            break unless $1 == maj_min
          end
          outfile.puts line
        end
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Blogger\UserBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
    /**
      * @Route("/user/new")
      * @Template()
      */
    public function createUserAction()
    {
        $factory = $this->get('security.encoder_factory');
        $user = new \Blogger\UserBundle\Entity\User();

        $encoder = $factory->getEncoder($user);
        $password = $encoder->encodePassword('lebowski', $user->getSalt());
        $user->setPassword($password);
var_dump($user);
    }

}


text:
import gevent, termcolor, time, argparse, sys, os, signal
import test
from tests import *

from conf.vehicle import VEHICLE_TYPE

parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose', help='Display verbose output (default: false)', action='store_true')
parser.add_argument('-c', '--continuous', help='Run in continuous mode (default: false)', action='store_true')
parser.add_argument('-e', '--environment', help='Ignore environment and run all (default: false)', action='store_true')
args = parser.parse_args()

def handler(signal, frame):
    sys.stdout.write('Caught Ctrl-C, terminating...')
    sys.exit(0)

signal.signal(signal.SIGINT, handler)

statuses = {
    test.OK: termcolor.colored('OK  ', 'green', attrs = ['bold']),
    test.WARN: termcolor.colored('WARN', 'yellow', attrs = ['bold']),
    test.ERR: termcolor.colored('ERR ', 'red', attrs = ['bold'])
}

def run(t, last_result = None):
    result = t.expr()
    show_result = args.verbose

    if last_result is None:
        # First run of test
        show_result |= not result
    else:
        show_result |= last_result != result

    if show_result:
        status = statuses[t.on_success if result else t.on_error]
        sys.stdout.write('[{timestamp}] {status} {testname} TEST:\n {source}'.format(
            timestamp=termcolor.colored(time.strftime('%d/%m/%Y %H:%M:%S', time.localtime()), 'cyan'),
            status=status,
            testname=termcolor.colored(t.name.ljust(40), 'blue'),
            source=termcolor.colored(t.raw.ljust(50), 'magenta')
        ))
        sys.stdout.flush()
    if args.continuous:
        gevent.sleep(0.5)
        run(t, result)
    else:
        return result

greenlets = []

if VEHICLE_TYPE == 'mainsub':
    vehicle_id = test.MAINSUB
elif VEHICLE_TYPE == 'minisub':
    vehicle_id = test.MINISUB
else:
    raise ValueError("CUAUV_VEHICLE_TYPE must be set to one of {mainsub, minisub}!")

environment_id = 2
if(not args.environment):
    LAND_DEPTHS = {
        test.MAINSUB: 0.01,
        test.MINISUB: 0.35,
    }

    if shm.kalman.depth.get() > LAND_DEPTHS[vehicle_id]:
        environment_id = test.WATER
    else:
        environment_id = test.LAND

sys.stdout.write('Running tests for vehicle: {} in environment {}\n'.format(vehicle_id,environment_id))
sys.stdout.flush()

# Run all tests for vehicle
for t in Test.active_tests(vehicle_id, environment_id):
    greenlets.append(gevent.spawn(run, t))

gevent.joinall(greenlets)

num_failed = sum(not x.get() for x in greenlets)

if num_failed == 0:
    sys.stdout.write('[{timestamp}] {ok_status} All systems are go!\n'.format(
        timestamp=termcolor.colored(time.strftime('%d/%m/%Y %H:%M:%S', time.localtime()), 'cyan'),
        ok_status=statuses[test.OK]
    ))
    sys.stdout.flush()

sys.exit(num_failed)


text:
import { module, test } from 'qunit';
import { visit } from '@ember/test-helpers';
import { setupApplicationTest } from 'ember-qunit';
import { a11yAudit } from 'ember-a11y-testing/test-support';
import percySnapshot from '@percy/ember';

module('Acceptance | Docs', function (hooks) {
  setupApplicationTest(hooks);

  test('accessibility check', async function (assert) {
    await visit('/docs');
    // Only audit usage-preview examples
    await a11yAudit({
      include: ['.FreestyleUsage-preview'],
      // https://github.com/dequelabs/axe-core/issues/3082
      // turn off the rule for aria-allowed-role for now until ember-a11y-testing is updated with bugfix from axe-core
      rules: {
        'aria-allowed-role': { enabled: false },
      },
    });
    assert.ok(true, 'no a11y errors found!');
  });

  test('percy visual diffs testing', async function (assert) {
    await visit('/docs');
    await percySnapshot('Boxel Docs');
    assert.ok(true, 'percy snapshot taken');
  });
});


text:
import Ember from 'ember';
import RouteMixin from 'ember-cli-pagination/remote/route-mixin';

export default Ember.Route.extend(RouteMixin, {
  model: function(params) {
    return Ember.RSVP.hash({
      model: this.findPaged('todo',params,{zeroBasedIndex: false})
    });
  },

  setupController: function(controller, models) {
    controller.setProperties(models);
  }
});


text:
package de.thomas.dreja.music.manager.data;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import de.thomas.dreja.music.manager.data.MusicCollection.Album;

public class UnionFind {

	int [] content;
	Vector<StringInteger> collectionIndexes;
	HashMap<String,Integer> collectionNames;

	public UnionFind(int size) {
		content = new int[size];
		collectionIndexes = new Vector<StringInteger>();
		collectionNames = new HashMap<String,Integer>();
	}

	public void Init(ArrayList<Album> albums, File albumsFile, File soundtracks, File podcasts) {
		for(int i = 0; i<content.length; i++) {
			if(albums.get(i).hasVariousArtists()) {
				checkForFileMatch(albums.get(i), albumsFile, soundtracks, podcasts);
				content[i] = i;
			} else {
				content[i] = -1;
			}
		}
	}

	private void checkForFileMatch(Album album, File albumsFile,
			File soundtracks, File podcasts) {

		String[] parts = album.getName().split(Constants.SPACE_STRING);
		String name = Constants.EMPTY_STRING;

		for(int i=0; i<parts.length-1; i++) {
			name = name + parts[i];

			File alb = new File(albumsFile, name);
			File ost = new File(soundtracks, name);
			File pod = new File(podcasts, name);

			if(alb.exists() && alb.isDirectory()) {
				album.setGroup(name);
				return;
			} else if(ost.exists() && ost.isDirectory()) {
				album.setGroup(name);
				album.setFolder(Folders.SOUNDTRACKS);
				return;
			} else if(pod.exists() && pod.isDirectory()) {
				album.setGroup(name);
				album.setFolder(Folders.PODCASTS);
				return;
			}

			name = name + Constants.SPACE_STRING;
		}
	}

	public int Find(int x) {
		if(content [x] == -1) {
			return -1;
		} else if(content [x] != content[content[x]] && content[content[x]] != x) {
			content[x] = Find(content[x]);
		}
		return content[x];
	}

	public void Union(int x, int y, String collName) {
		StringInteger xStr = new StringInteger(collName, x);
		StringInteger yStr = new StringInteger(collName, y);

		if(!collectionIndexes.contains(xStr)) {
			collectionIndexes.add(xStr);
		}
		if(!collectionIndexes.contains(yStr)){
			collectionIndexes.add(yStr);
		}
		if(collectionNames.containsKey(collName)) {
			collectionNames.put(collName, collectionNames.get(collName)+1);
		} else {
			collectionNames.put(collName, 2);
		}

		if(Math.random() > 0.5) {
			content[x] = y;
		} else {
			content[y] = x;
		}
	}

	public Vector<StringInteger> getCollectionIndexes() {
		return collectionIndexes;
	}

	public HashMap<String, Integer> getCollectionNames() {
		return collectionNames;
	}

	public static class StringInteger {

		private String string;
		private int integer;
		public String getString() {
			return string;
		}
		public void setString(String string) {
			this.string = string;
		}
		public int getInteger() {
			return integer;
		}
		public void setInteger(int integer) {
			this.integer = integer;
		}
		public StringInteger(String string, int integer) {
			super();
			this.string = string;
			this.integer = integer;
		}
		@Override
		public String toString() {
			return "StringInteger [string=" + string + ", integer=" + integer + "]";
		}

		@Override
		public boolean equals(Object obj) {
			if(obj.getClass() == StringInteger.class) {
				StringInteger strInt = (StringInteger) obj;
				return (integer == strInt.getInteger()) && (string.equals(strInt.getString()));
			} else {
				return super.equals(obj);
			}

		}
	}
}


text:
import random
from sympy import *

import fm.mathengine.problemTypes.problem as problem

class integTrig(problem.Problem):
	coefficients = [1,2,3,4,5,6,7,8,9]
	functions = [sin, cos]

	def generate_problem(self):
		coefficient = random.choice(self.coefficients)
		coefficient2 = random.choice(self.coefficients)
		function = random.choice(self.functions)
		x = self.x
		eqn = random.choice([1, -1]) * coefficient * function(coefficient2 * x)
		self.problem_statement = Integral(eqn, x)


text:
Title: Entenda tudo sobre Exceções em Java
Date: 2016-05-10 09:58
Author: gustavo.foa
Category: Iniciante, Java
Slug: entenda-tudo-sobre-excecoes-em-java
Status: draft

O **tratamento de erros na linguagem Java** é uma daquelas
características da linguagem que gera amantes e odiadores. Sempre tem
aquela turma que dá uma lida rápida em como funcionam as exceções em
Java e sai lançando ou tratando Exception em todo método que pode dar
algum erro, já que **Exception** é a superclasse de todas as exceções.
Ou seja, na cabeça do sujeito ele fica "imune" de qualquer erro. Mal
sabe ele que está criando um problema muito maior que um simples
NullPointerException.

Neste post explico tudo sobre exceções em java, como acontece e como
resolver da forma correta.

``` {.lang:java .decode:true}
try {
 ...
} catch (Exception e) {
 ...
}
```

O código acima da uma sensação de que qualquer erro que acontecer na
execução do código será "resolvido". Mas se você faz esse tipo de coisa,
isso só mostra que você não entende todas as possibilidades de execução
do seu código. Isso significa que você é um mau programador.

Então deixo aqui um pedido: Não faça isso! Para o bem da sua carreira.
Ao invés de tratar Exception, entenda o que o seu código faz,
identifique os erros que podem acontecer e trate especificamente os
erros identificados.

Exceções
--------

Uma **exceção**, como o próprio nome diz, é uma situação que normalmente
não ocorre. Embora seja uma situação anormal, as exceções podem
acontecer. Por isso nós, como bons programadores que somos, precisamos
prever o seu acontecimento e saber agir para tratar e, se possível,
corrigir o problema.

Em java, as exceções são trabalhadas com recursos de orientação a
objetos e o modelo de abstração para as exceções classifica os erros da
seguinte forma.

-   Todas as classes que representam erros implementam a interface
    **Throwable**.
-   Os erros relativos a Hardware ou um erro do sistema operacional, são
    classes filhas da classe **Error** (que implementa Throwable). Nós
    não temos muito a fazer quando acontece um erro desses. Por
    exemplo, o erro OutOfMemoryError que acontece quando acaba a memória
    do computador.
-   Todos os outros erros são filhos da classe **Exception**.
-   Dentre os erros filhos de Exception há um grupo de erros que o
    compilador nos obriga a tratar. Estes são os erros filhos
    de RuntimeException.
-   Todos os erros que não herdam de Error ou de RuntimeException,
    precisam ser tratados (try-catch) ou lançados (throws), caso
    contrário o código não compila. Vamos falar disso mais abaixo.

A figura abaixo mostra a hierarquia das classes de Erro de java e um
exemplo dos tipos de erros possíveis.

![exceptions em
java](http://www.dicasdeprogramacao.com.br/wp-content/uploads/exceptions1.png){.aligncenter
.size-full .wp-image-2673 width="583" height="312"}

Tratamento de Exceções em Java
------------------------------

Conhecendo a hierarquia dos erros, agora você já sabe que todo erro que
não seja filho de **Error** ou **RuntimeException** precisa ser
resolvido por você. Mas como?

Basicamente você precisa conhecer três coisas: as palavras-chave
**throw** e **throws** e a estrutura ****try-catch-finally** **.

A diferença entre **throw** e **throws** é exatamente o que estas
palavras significam em inglês. Se você não sabe, ou pelo menos não
estuda inglês, comece já! Escrevi um post isto, vale a pena a leitura.

**>> Quer ser programador? Aprenda inglês!**

Primeiro vamos falar do **throw**, que significa "lançar" ou "jogar" em
inglês. Quando acontece um erro, em qualquer lugar, é esta palavra que é
usada para "lançar" o erro. Depois da palavra throw, é necessário
informar o objeto de erro que será lançada. Para isso você pode criar um
objeto de erro ou informar um objeto de erro já existente.

O erro é lançado assim:

``` {.lang:java .decode:true}
throw <objeto do erro>
```

O objeto pode ser criado na hora (com o *new*) ou ser acessado através
de uma variável.

``` {.lang:default .decode:true}
throw new IOException();
```

Lembrando que o objeto que será lançado dever ser instância de uma
classe que está em algum ponto da hierarquia que falamos anteriormente.
Ou seja, este objeto implementa *Throwable,* pode ser um *Error *ou
uma *Exception*, e também pode ser uma *RuntimeException*.

Simples assim, o *throw* serve só para lançar um erro. Mas o que eu
quero dizer com lançar o erro? Lançar o erro significa que você está
enviando este problema para quem chamou o método. Por exemplo, no código
abaixo o método m1() está lançando o erro para o método m2().

``` {.lang:java .decode:true}
void m1() {
 throw new Exception();
}

void m2() {
 m1();
}
```

E a palavra-chave **throws** serve pra quê? Lembra que eu disse que as
exceções filhas de *Exception*, que não sejam filhas de
*RuntimeException*, precisam ser resolvidas? O seu código java será
compilado com sucesso enquanto você não resolver essas exceções. Para
resolver uma exceção você pode fazer duas coisas. Tratá-la usando o
try-catch (já vou falar sobre ele) ou lançar essa exceção para  quem
chamou o método. É para isso que serve a palavra-chave **throws**.

**Inglês \~> **Throws em inglês também significa lançar, mas
conjugado para a terceira pessoa do singular. Ele/ela **lança**.

Então significa que **o método ... "lança" tal exceção**.

Agora olhe para o código que escrevi acima. Ele não compila! Por que?
Você sabe? Olha o erro de compilação que acontece.

![Erro Exception não
tratada](http://www.dicasdeprogramacao.com.br/wp-content/uploads/Erro-Exception-não-tratada.png){.aligncenter
.size-full .wp-image-2677 width="500" height="155"}

Como eu estou lançando uma exceção **Exception** eu preciso resolver
essa exceção de alguma forma. Ela deve ser capturada (com *try-catch*)
ou lançada (com o throws) para o método que chamou o método que deu o
erro.

Vamos falar de Stack Trace
--------------------------

Este post não é para falar de tratamento de exceções. a **dica** acima
para os iniciantes de programação em Java.

, mas quero falar aos iniciantes em programação, especialmente em Java,
sobre aquele texto de fonte vermelha e tabulada que aparece no console e
dá um susto quando o pobre programador esperava um funcionamento bonito,
calmo e sereno do código que acabara de escrever. Isso, estou falando
do **Stack Trace Exception**!

Cá entre nós, eu sempre fiquei com pena do coitado do aluno iniciante
que esperava que o seu programinha funcionasse bunitinho, mas recebe o
tão angustiante erro na cara. Especialmente quando o malvado do
professor digita uma letra quando o programa esperava ler um número. É
comovente ver o semblante do aluno mudar de orgulho para decepção. Mas
faz parte do aprendizado, todo programador passa por isso,
principalmente os bons!

Voltemos ao **Stack Trace Exception**. O que, a princípio, dá um susto
pode se tornar o caminho para alcançar o caminho a luz no fim do tunel.
No Stack Trace Exception (ou pilha de exceções) está a notificação de um
problema, mas também está o que causou o problema, o nome da Classe, a
linha e a hierarquia das chamadas de métodos, deste o início da execução
do programa a té o ponto em que o erro aconteceu.


text:
package endtoend_test

import (
	"math"
	"math/rand"
	"os"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/kopia/kopia/internal/testutil"
	"github.com/kopia/kopia/tests/clitestutil"
	"github.com/kopia/kopia/tests/testenv"
)

func (s *formatSpecificTestSuite) TestNoECC(t *testing.T) {
	t.Parallel()

	const mb = 1024 * 1024

	runner := testenv.NewInProcRunner(t)
	e := testenv.NewCLITest(t, s.formatFlags, runner)

	defer e.RunAndExpectSuccess(t, "repo", "disconnect")

	e.RunAndExpectSuccess(t, "repo", "create", "filesystem", "--flat", "--path", e.RepoDir)

	dataDir := testutil.TempDirectory(t)

	var data [mb]byte
	for i := range data {
		data[i] = byte(i%254) + 1
	}

	require.NoError(t, os.WriteFile(filepath.Join(dataDir, "some-file1"), data[:], 0o600))

	e.RunAndExpectSuccess(t, "snapshot", "create", dataDir)

	repoSize, err := dirSize(e.RepoDir)
	require.NoError(t, err)

	require.True(t, repoSize < int64(math.Round(1.1*mb)))
}

func (s *formatSpecificTestSuite) TestECC(t *testing.T) {
	t.Parallel()

	const mb = 1024 * 1024

	runner := testenv.NewInProcRunner(t)
	e := testenv.NewCLITest(t, s.formatFlags, runner)

	defer e.RunAndExpectSuccess(t, "repo", "disconnect")

	e.RunAndExpectSuccess(t, "repo", "create", "filesystem", "--flat", "--path", e.RepoDir, "--ecc-overhead-percent=50")

	dataDir := testutil.TempDirectory(t)

	var data [mb]byte
	for i := range data {
		data[i] = byte(i%254) + 1
	}

	fileName := "some-file1"

	require.NoError(t, os.WriteFile(filepath.Join(dataDir, fileName), data[:], 0o600))

	e.RunAndExpectSuccess(t, "snapshot", "create", dataDir)

	repoSize, err := dirSize(e.RepoDir)
	require.NoError(t, err)

	// ECC is not supported in version 1
	if s.formatVersion == 1 {
		require.True(t, repoSize < int64(math.Round(1.1*mb)))
		return
	}

	require.True(t, repoSize >= int64(math.Round(1.5*mb)))

	err = s.flipOneByteFromEachFile(e)
	require.NoError(t, err)

	si := clitestutil.ListSnapshotsAndExpectSuccess(t, e, dataDir)

	snapID := si[0].Snapshots[0].SnapshotID

	restoreDir := testutil.TempDirectory(t)
	e.RunAndExpectSuccess(t, "restore", snapID, restoreDir)

	restoreData, err := os.ReadFile(filepath.Join(restoreDir, fileName))
	require.NoError(t, err)

	require.Equal(t, data[:], restoreData)
}

func (s *formatSpecificTestSuite) flipOneByteFromEachFile(e *testenv.CLITest) error {
	return filepath.Walk(e.RepoDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if info.IsDir() {
			return nil
		}
		if info.Name() == "kopia.repository.f" || info.Name() == ".shards" {
			return nil
		}

		bytes, err := os.ReadFile(path)
		if err != nil {
			return err
		}

		c := rand.Intn(len(bytes))
		if bytes[c] >= 128 {
			bytes[c] = 0
		} else {
			bytes[c] = 255
		}

		err = os.WriteFile(path, bytes, info.Mode())
		if err != nil {
			return err
		}

		return nil
	})
}

func dirSize(path string) (int64, error) {
	var size int64

	err := filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
		if err != nil {
			return err
		}
		if !info.IsDir() {
			size += info.Size()
		}
		return nil
	})

	return size, err
}


text:
use criterion::{black_box, Criterion, ParameterizedBenchmark, Throughput};
use ratelimit_meter::test_utilities::variants::Variant;
use std::time::{Duration, Instant};

pub fn bench_all(c: &mut Criterion) {
    bench_plain_algorithm_1elem(c);
    bench_plain_algorithm_multi(c);
}

fn bench_plain_algorithm_1elem(c: &mut Criterion) {
    let id = "algorithm/1";
    let bm = ParameterizedBenchmark::new(
        id,
        move |b, ref v| {
            bench_with_algorithm_variants!(v, algo, {
                let now = Instant::now();
                let ms = Duration::from_millis(20);
                let state = algo.state();

                let mut i = 0;
                b.iter(|| {
                    i += 1;
                    black_box(algo.check(&state, now + (ms * i)).is_ok());
                });
            });
        },
        Variant::ALL,
    )
    .throughput(|_s| Throughput::Elements(1));
    c.bench(id, bm);
}

fn bench_plain_algorithm_multi(c: &mut Criterion) {
    let id = "algorithm/multi";
    let elements: u32 = 10;
    let bm = ParameterizedBenchmark::new(
        id,
        move |b, ref v| {
            bench_with_algorithm_variants!(v, algo, {
                let now = Instant::now();
                let ms = Duration::from_millis(20);
                let state = algo.state();

                let mut i = 0;
                b.iter(|| {
                    i += 1;
                    black_box(algo.check_n(&state, elements, now + (ms * i)).is_ok());
                });
            });
        },
        Variant::ALL,
    )
    .throughput(|_s| Throughput::Elements(1));
    c.bench(id, bm);
}


text:
// PARSER_WEEDER
// JOOS1:PARSER_EXCEPTION
// JOOS2:PARSER_EXCEPTION
// JAVAC:
/**
 * Parser/weeder:
 * - Multiple variable in same declaration not allowed.
 */
public class Je_1_Declarations_MultipleVars {

    public Je_1_Declarations_MultipleVars() {}

    public static int test() {
	int i=0, j=10;
	return 123;
    }

}


text:
"""
    SARSOPSimulator

simulate a sarsop policy from the xml files
* `sim_len`  number of steps to use in simulation (default 10)
* `sim_num` number of simulations
* `fast` use fast (but very picky) alternate parser for .pomdp files
* `srand` set the random seed for the simulation
* `output_file` where to write the results
* `policy_filename` policy file location
* `pomdp_filename` pomdpx file location
"""
@with_kw struct SARSOPSimulator
    sim_len::Int = 10
    sim_num::Int = 10
    fast::Bool = false
    srand::Union{Int64, Nothing} = nothing
    output_file::AbstractString = ""
    policy_filename::AbstractString = "policy.out"
    pomdp_filename::AbstractString = "model.pomdpx"
end

function get_simulator_options(sim::SARSOPSimulator)
    options = String[]
    push!(options, "--simLen")
    push!(options, string(sim.sim_len))
    push!(options, "--simNum")
    push!(options, string(sim.sim_num))
    if sim.fast
        push!(options, "--fast")
    end
    if sim.srand != nothing
        push!(options, "--srand")
        push!(options, string(sim.srand))
    end
    push!(options, "--output-file")
    push!(options, sim.output_file)
    return options
end

"""
    POMDPs.simulate(sim::SARSOPSimulator)

Simulate a SARSOP policy according to the config specified by `sim::SARSOPSimulator`
"""
function POMDPs.simulate(sim::SARSOPSimulator)
    options_list = get_simulator_options(sim)
    pomdpsim() do pomdpsim_path
        run(`$pomdpsim_path $(sim.pomdp_filename) --policy-file $(sim.policy_filename) $options_list`)
    end
end

"""
    SARSOPEvaluator

simulate a sarsop policy from the xml files
* `sim_len`  number of steps to use in simulation (default 10)
* `sim_num` number of simulations
* `fast` use fast (but very picky) alternate parser for .pomdp files
* `srand` set the random seed for the simulation
* `memory` [MB] No memory limit by default. If memory usage exceeds the specified value, the evaluator will switch back
to a more conservative (and slow) methods.
* `output_file` where to write the results
* `policy_filename` policy file location
* `pomdp_filename` pomdpx file location
"""
@with_kw struct SARSOPEvaluator
    sim_len::Int = 10
    sim_num::Int = 10
    fast::Bool = false
    srand::Union{Int64, Nothing} = nothing
    memory::Union{Float64, Nothing} = nothing
    output_file::AbstractString = ""
    policy_filename::AbstractString = "policy.out"
    pomdp_filename::AbstractString = "model.pomdpx"
end

function get_evaluator_options(ev::SARSOPEvaluator)
    options = String[]
    push!(options, "--simLen")
    push!(options, string(ev.sim_len))
    push!(options, "--simNum")
    push!(options, string(ev.sim_num))
    if ev.fast
        push!(options, "--fast")
    end
    if ev.srand != nothing
        push!(options, "--srand")
        push!(options, string(ev.srand))
    end
    if ev.memory != nothing
        push!(options, "--memory")
        push!(options, string(ev.memory))
    end
    push!(options, "--output-file")
    push!(options, ev.output_file)
    return options
end

"""
    evaluate(ev::SARSOPEvaluator)

simulate a SARSOP policy according to the configuration specified by `ev::SARSOPEvaluator`
"""
function evaluate(ev::SARSOPEvaluator)
    options_list = get_evaluator_options(ev)
    pomdpeval() do pomdpeval_path
        run(`$pomdpeval_path $(ev.pomdp_filename) --policy-file $(ev.policy_filename) $options_list`)
    end
end


text:
import Vue from 'vue/dist/vue.common';
import Plugin from '~/index';
import { autoregister } from '~/index';

describe('plugin', () => {
    it('should add $intro variable to vue prototype', () => {
        Vue.use(Plugin);
        const vm = new Vue();
        expect(vm.$intro.constructor).toEqual(Function);
    });

    it('$intro() should return new introJs instance', () => {
        Vue.use(Plugin);
        const vm = new Vue();
        expect(vm.$intro()).toBeTruthy();
    });

    it('should autoregister in window has Vue', () => {
        window.Vue = Vue;
        autoregister();
        const vm = new Vue();
        expect(vm.$intro.constructor).toEqual(Function);
    });

    it('should autoregister discovery service', () => {
        Vue.use(Plugin);
        expect(window.__introjsDiscovery).toBeTruthy;
    });
});


text:
Orders

          <?php  if($this->session->userdata('userdetails')){?>

<a href="<?php echo site_url('user/dashboard'); ?>">Home

		<?php } else{ ?>

<a href="<?php echo site_url('user/login'); ?>">Home

	  <?php } ?>

<a href="<?php echo site_url('user/orders'); ?>">Orders

Orders List

        <button type="button" class="btn btn-sm btn-icon btn-inverse btn-round" data-toggle="tooltip" data-original-title="Export to CSV">

        </button>
        <button type="button" class="btn btn-sm btn-icon btn-inverse btn-round" data-toggle="tooltip" data-original-title="Export to PDF">

        </button>
        <button type="button" class="btn btn-sm btn-icon btn-inverse btn-round" data-toggle="tooltip" data-original-title="Export to Word">

        </button>

                Order #
                Employee
				Group Name
                Purchased on
                Order Total

                Order #
                Employee
				Group Name
                Purchased on
                Order Total

				<?php
			if(count($groupallorders) > 0){
			foreach ($groupallorders as $orders){
				//echo '
';print_r($orders);exit;?>

                <a href="<?php echo site_url('user/orderview'); ?>?id=<?php echo  base64_encode($orders['order_id']);?>"><?php echo htmlentities($orders['order_id']);?>
                <?php echo htmlentities($orders['lastname']);?><?php echo htmlentities($orders['firstname']);?>
                <?php echo htmlentities($orders['group_name']);?>
                <?php echo htmlentities($orders['purchase_date']);?>
                <?php echo htmlentities($orders['order_total']);?>

                   <a href="<?php echo site_url('user/orderview'); ?>?id=<?php echo  base64_encode($orders['order_id']);?>"  class="btn btn-sm btn-icon btn-pure btn-primary"
                  data-toggle="tooltip" data-original-title="View Order">
                   <a href="<?php echo site_url('user/printview'); ?>?id=<?php echo  base64_encode($orders['order_id']);?>"  target="_blank" class="btn btn-sm btn-icon btn-pure btn-danger"
                  data-toggle="tooltip" data-original-title="Print Order">

			  <?php } } else { echo '
No Orders
';} ?>


text:
<?php
namespace JYPS\RegisterBundle\Controller;

use Endroid\QrCode\QrCode;
use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelLow;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use JYPS\RegisterBundle\Entity\Member;
use Endroid\QrCode\Writer\PngWriter;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\Color\Color;

class MemberCardGenerator
{

    public static function generateMembershipCard(Member $member, $base_image_path, $font, $image_path)
    {
        $writer = new PngWriter();
        $base_image = imagecreatefrompng($base_image_path);
        $output_image = $image_path . 'MemberCard_' . hash("sha256", $member->getMemberCardHash()) . '.png';
        /* member data to image */
        $black = imagecolorallocate($base_image, 0, 0, 0);
        $memberid = $member->getMemberId();
        imagettftext($base_image, 38, 0, 190, 500, $black, $font, $member->getFullName());
        imagettftext($base_image, 38, 0, 390, 555, $black, $font, $memberid);
        imagettftext($base_image, 38, 0, 390, 610, $black, $font, date('Y'));
        /*qr code to image & serialize json for qr code*/
        $member_data = array('member_id' => $member->getMemberId(),
            'join_year' => $member->getMembershipStartDate()->format('Y'),
            'name' => $member->getFullName());
        $member_qr_data = json_encode($member_data);
        $qrCode = QrCode::create($member_qr_data)
            ->setEncoding(new Encoding('UTF-8'))
            ->setErrorCorrectionLevel(new ErrorCorrectionLevelLow())
            ->setSize(380)
            ->setMargin(10)
            ->setRoundBlockSizeMode(new RoundBlockSizeModeMargin())
            ->setForegroundColor(new Color(0, 0, 0))
            ->setBackgroundColor(new Color(255, 255, 255));

        $result = $writer->write($qrCode);
        $qr_image = imagecreatefromstring($result->getString());
        imagecopy($base_image, $qr_image, 550, 22, 0, 0, imagesx($qr_image), imagesy($qr_image));
        /*write image to disk */
        imagepng($base_image, $output_image);
        return $output_image;
    }
}


text:
class PhoneField extends Field {
}
window.QForms.PhoneField = PhoneField;


text:
package cli

import (
	"strings"
	"errors"
)

type Request struct {
	raw string
	vars map[string]string
}

func NewRequest(raw string, pattern Pattern) (Request, error) {
	request := Request{
		raw: raw,
		vars: make(map[string]string),
	}
	keys := strings.Fields(pattern.Template())
	values := strings.Fields(raw)
	units := strings.Fields(strings.TrimSuffix(strings.TrimPrefix(pattern.RE(), "^"), "$"))
	if len(keys) != len(values) || len(keys) != len(units) {
		return request, errors.New("Wrong command line arguments")
	}
	for i, v := range units {
		if v == "([./0-z]+)" {
			request.vars[strings.TrimSuffix(strings.TrimPrefix(keys[i], "{"), "}")] = values[i]
		}
	}
	return request, nil
}

func (r Request) Vars() map[string]string {
	return r.vars
}

func (r Request) Raw() string {
	return r.raw
}


text:
.markdown-body {
    font-size: 13px;
    line-height: 1.6;
}
.markdown-body>*:first-child { margin-top: 0!important }
.markdown-body>*:last-child { margin-bottom: 0!important }

.markdown-body a {
    cursor: pointer;
    color: #4183C4;
    text-decoration: none;
}

.markdown-body a:hover {
    text-decoration: underline;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
    margin: 20px 0 10px;
    padding: 0;
    font-weight: bold;
    -webkit-font-smoothing: antialiased;
    cursor: text;
    position: relative;
}
.markdown-body h1 .mini-icon-link,
.markdown-body h2 .mini-icon-link,
.markdown-body h3 .mini-icon-link,
.markdown-body h4 .mini-icon-link,
.markdown-body h5 .mini-icon-link,
.markdown-body h6 .mini-icon-link {
    display: none;
    color: #000;
}
.markdown-body h1:hover a.anchor,
.markdown-body h2:hover a.anchor,
.markdown-body h3:hover a.anchor,
.markdown-body h4:hover a.anchor,
.markdown-body h5:hover a.anchor,
.markdown-body h6:hover a.anchor {
    text-decoration: none;
    line-height: 1;
    padding-left: 0;
    margin-left: -22px;
    top: 15%;
}
.markdown-body h1:hover a.anchor .mini-icon-link,
.markdown-body h2:hover a.anchor .mini-icon-link,
.markdown-body h3:hover a.anchor .mini-icon-link,
.markdown-body h4:hover a.anchor .mini-icon-link,
.markdown-body h5:hover a.anchor .mini-icon-link,
.markdown-body h6:hover a.anchor .mini-icon-link { display: inline-block }
.markdown-body h1 tt,
.markdown-body h1 code,
.markdown-body h2 tt,
.markdown-body h2 code,
.markdown-body h3 tt,
.markdown-body h3 code,
.markdown-body h4 tt,
.markdown-body h4 code,
.markdown-body h5 tt,
.markdown-body h5 code,
.markdown-body h6 tt,
.markdown-body h6 code { font-size: inherit }
.markdown-body h1 {
    font-size: 28px;
    color: #000;
}
.markdown-body h2 {
    font-size: 24px;
    border-bottom: 1px solid #ccc;
    color: #000;
}
.markdown-body h3 { font-size: 18px }
.markdown-body h4 { font-size: 16px }
.markdown-body h5 { font-size: 14px }
.markdown-body h6 {
    color: #777;
    font-size: 14px;
}
.markdown-body p,
.markdown-body blockquote,
.markdown-body ul,
.markdown-body ol,
.markdown-body dl,
.markdown-body table,
.markdown-body pre { margin: 15px 0 }
.markdown-body hr {
    background: transparent url("https://a248.e.akamai.net/assets.github.com/images/modules/pulls/dirty-shade.png?643ff063") repeat-x 0 0;
    border: 0 none;
    color: #ccc;
    height: 1px;
    padding: 0;
    margin: 0;
}
.markdown-body>h2:first-child,
.markdown-body>h1:first-child,
.markdown-body>h1:first-child+h2,
.markdown-body>h3:first-child,
.markdown-body>h4:first-child,
.markdown-body>h5:first-child,
.markdown-body>h6:first-child {
    margin-top: 0;
    padding-top: 0;
}
.markdown-body a:first-child h1,
.markdown-body a:first-child h2,
.markdown-body a:first-child h3,
.markdown-body a:first-child h4,
.markdown-body a:first-child h5,
.markdown-body a:first-child h6 {
    margin-top: 0;
    padding-top: 0;
}
.markdown-body h1+p,
.markdown-body h2+p,
.markdown-body h3+p,
.markdown-body h4+p,
.markdown-body h5+p,
.markdown-body h6+p { margin-top: 0 }
.markdown-body li p.first { display: inline-block }
.markdown-body ul,
.markdown-body ol { padding-left: 30px }
.markdown-body ul.no-list,
.markdown-body ol.no-list {
    list-style-type: none;
    padding: 0;
}
.markdown-body ul li>:first-child,
.markdown-body ol li>:first-child { margin-top: 0 }
.markdown-body dl { padding: 0 }
.markdown-body dl dt {
    font-size: 14px;
    font-weight: bold;
    font-style: italic;
    padding: 0;
    margin: 15px 0 5px;
}
.markdown-body dl dt:first-child { padding: 0 }
.markdown-body dl dt>:first-child { margin-top: 0 }
.markdown-body dl dt>:last-child { margin-bottom: 0 }
.markdown-body dl dd {
    margin: 0 0 15px;
    padding: 0 15px;
}
.markdown-body dl dd>:first-child { margin-top: 0 }
.markdown-body dl dd>:last-child { margin-bottom: 0 }
.markdown-body blockquote {
    border-left: 4px solid #DDD;
    padding: 0 15px;
    color: #777;
}
.markdown-body blockquote>:first-child { margin-top: 0 }
.markdown-body blockquote>:last-child { margin-bottom: 0 }
.markdown-body table { padding: 0 }
.markdown-body table tr {
    border-top: 1px solid #ccc;
    background-color: #fff;
    margin: 0;
    padding: 0;
}
.markdown-body table tr:nth-child(2n) { background-color: #f8f8f8 }
.markdown-body table tr th { font-weight: bold }
.markdown-body table tr th,
.markdown-body table tr td {
    border: 1px solid #ccc;
    text-align: left;
    margin: 0;
    padding: 6px 13px;
}
.markdown-body table tr th>:first-child,
.markdown-body table tr td>:first-child { margin-top: 0 }
.markdown-body table tr th>:last-child,
.markdown-body table tr td>:last-child { margin-bottom: 0 }
.markdown-body img { max-width: 100% }
.markdown-body span.frame {
    display: block;
    overflow: hidden;
}
.markdown-body span.frame>span {
    border: 1px solid #ddd;
    display: block;
    float: left;
    overflow: hidden;
    margin: 13px 0 0;
    padding: 7px;
    width: auto;
}
.markdown-body span.frame span img {
    display: block;
    float: left;
}
.markdown-body span.frame span span {
    clear: both;
    color: #333;
    display: block;
    padding: 5px 0 0;
}
.markdown-body span.align-center {
    display: block;
    overflow: hidden;
    clear: both;
}
.markdown-body span.align-center>span {
    display: block;
    overflow: hidden;
    margin: 13px auto 0;
    text-align: center;
}
.markdown-body span.align-center span img {
    margin: 0 auto;
    text-align: center;
}
.markdown-body span.align-right {
    display: block;
    overflow: hidden;
    clear: both;
}
.markdown-body span.align-right>span {
    display: block;
    overflow: hidden;
    margin: 13px 0 0;
    text-align: right;
}
.markdown-body span.align-right span img {
    margin: 0;
    text-align: right;
}
.markdown-body span.float-left {
    display: block;
    margin-right: 13px;
    overflow: hidden;
    float: left;
}
.markdown-body span.float-left span { margin: 13px 0 0 }
.markdown-body span.float-right {
    display: block;
    margin-left: 13px;
    overflow: hidden;
    float: right;
}
.markdown-body span.float-right>span {
    display: block;
    overflow: hidden;
    margin: 13px auto 0;
    text-align: right;
}
.markdown-body code,
.markdown-body tt {
    margin: 0 2px;
    padding: 0 5px;
    white-space: pre-line;
    word-wrap: break-word;
    border: 1px solid #eaeaea;
    background-color: #f8f8f8;
    border-radius: 3px;
    color: #333;
    font-size: 8pt;
}
.markdown-body pre>code {
    margin: 0;
    padding: 0;
    white-space: pre;
    border: none;
    background: transparent;
}
.markdown-body .highlight pre,
.markdown-body pre {
    background-color: #fff;
    border: 1px solid #ccc;
    font-size: 13px;
    line-height: 14px;
    overflow: auto;
    padding: 6px 10px;
    border-radius: 3px;
    display: inline-block;
    margin: 0;
    width: 100%;
}
.markdown-body pre code,
.markdown-body pre tt {
    background-color: transparent;
    border: none;
    white-space: pre-wrap;
    white-space: -moz-pre-wrap;
    white-space: -pre-wrap;
    white-space: -o-pre-wrap;
    word-wrap: break-word;
}


text:
@interface RYFormPickerCell : RYFormBaseCell

@end


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI.Windows.Plugins.Flow;
using UnityEditor.UI.Windows.Plugins.Flow;
using System.Linq;
using System.IO;
using System.Collections.Generic;
using ME;
using UnityEngine.UI.Windows.Plugins.FlowCompiler;
using FD = UnityEngine.UI.Windows.Plugins.Flow.Data;

namespace UnityEditor.UI.Windows.Plugins.Functions {

	public static class FlowFunctionsTemplateGenerator {

		public static string GenerateReturnMethod(FlowSystemEditorWindow flowEditor, FD.FlowWindow exitWindow) {

			var file = Resources.Load("UI.Windows/Functions/Templates/TemplateReturnMethod") as TextAsset;
			if (file == null) {

				Debug.LogError("Functions Template Loading Error: Could not load template 'TemplateReturnMethod'");

				return string.Empty;

			}

			var data = FlowSystem.GetData();
			if (data == null) return string.Empty;

			var result = string.Empty;
			var part = file.text;

			var functionContainer = exitWindow.GetFunctionContainer();

			var functionName = functionContainer.title;
			var functionCallName = functionContainer.directory;
			var classNameWithNamespace = Tpl.GetNamespace(exitWindow) + "." + Tpl.GetDerivedClassName(exitWindow);

			result +=
				part.Replace("{FUNCTION_NAME}", functionName)
					.Replace("{FUNCTION_CALL_NAME}", functionCallName)
					.Replace("{CLASS_NAME_WITH_NAMESPACE}", classNameWithNamespace);

			return result;

		}

		public static string GenerateTransitionMethod(FlowSystemEditorWindow flowEditor, FD.FlowWindow windowFrom, FD.FlowWindow windowTo) {

			var file = Resources.Load("UI.Windows/Functions/Templates/TemplateTransitionMethod") as TextAsset;
			if (file == null) {

				Debug.LogError("Functions Template Loading Error: Could not load template 'TemplateTransitionMethod'");

				return string.Empty;

			}

			var data = FlowSystem.GetData();
			if (data == null) return string.Empty;

			var result = string.Empty;
			var part = file.text;

			// Function link
			var functionId = windowTo.GetFunctionId();

			// Find function container
			var functionContainer = data.GetWindow(functionId);
			if (functionContainer == null) {

				// Function not found
				return string.Empty;

			}

			// Get function root window
			var root = data.GetWindow(functionContainer.functionRootId);
			//var exit = data.GetWindow(functionContainer.functionExitId);

			var functionName = functionContainer.title;
			var functionCallName = functionContainer.directory;
			var classNameWithNamespace = Tpl.GetNamespace(root) + "." + Tpl.GetDerivedClassName(root);
			var transitionMethods = Tpl.GenerateTransitionMethods(windowTo);
			transitionMethods = transitionMethods.Replace("\r\n", "\r\n\t")
				.Replace("\n", "\n\t");

			result +=
				part.Replace("{TRANSITION_METHODS}", transitionMethods)
					.Replace("{FUNCTION_NAME}", functionName)
					.Replace("{FUNCTION_CALL_NAME}", functionCallName)
					.Replace("{FLOW_FROM_ID}", windowFrom.id.ToString())
					.Replace("{FLOW_TO_ID}", windowTo.id.ToString())
					.Replace("{CLASS_NAME_WITH_NAMESPACE}", classNameWithNamespace);

			return result;

		}

		public static string GenerateTransitionTypedMethod(FlowSystemEditorWindow flowEditor, FD.FlowWindow windowFrom, FD.FlowWindow windowTo, System.Type[] parameters, string[] parameterNames) {

			var file = Resources.Load("UI.Windows/Functions/Templates/TemplateTransitionTypedMethod") as TextAsset;
			if (file == null) {

				Debug.LogError("Functions Template Loading Error: Could not load template 'TemplateTransitionTypedMethod'");

				return string.Empty;

			}

			var data = FlowSystem.GetData();
			if (data == null) return string.Empty;

			var result = string.Empty;
			var part = file.text;

			// Function link
			var functionId = windowTo.GetFunctionId();

			// Find function container
			var functionContainer = data.GetWindow(functionId);
			if (functionContainer == null) {

				// Function not found
				return string.Empty;

			}

			// Get function root window
			var root = data.GetWindow(functionContainer.functionRootId);
			//var exit = data.GetWindow(functionContainer.functionExitId);

			var functionName = functionContainer.title;
			var functionCallName = functionContainer.directory;
			var classNameWithNamespace = Tpl.GetNamespace(root) + "." + Tpl.GetDerivedClassName(root);
			var transitionMethods = Tpl.GenerateTransitionMethods(windowTo);
			transitionMethods = transitionMethods.Replace("\r\n", "\r\n\t")
				.Replace("\n", "\n\t");

			var definition = parameters.Select((x, i) => ME.Utilities.FormatParameter(x) + " " + parameterNames[i]).ToArray();
			var call = parameterNames;
			var description = parameters.Select((x, i) => "/// <param name=\"" + parameterNames[i] + "\">" + parameterNames[i] + " to OnParametersPass</param>").ToArray();

			result +=
				part.Replace("{TRANSITION_METHODS}", transitionMethods)
					.Replace("{FUNCTION_NAME}", functionName)
					.Replace("{FUNCTION_CALL_NAME}", functionCallName)
					.Replace("{FLOW_FROM_ID}", windowFrom.id.ToString())
					.Replace("{FLOW_TO_ID}", windowTo.id.ToString())
					.Replace("{CLASS_NAME_WITH_NAMESPACE}", classNameWithNamespace)
					.Replace("{PARAMETERS_DEFINITION}", string.Join(", ", definition))
					.Replace("{PARAMETERS_CALL}", string.Join(", ", call))
					.Replace("{PARAMETERS_DESCRIPTION}", string.Join(System.Environment.NewLine, description));

			return result;

		}

	}

	public class Functions : FlowAddon {

		private Editor editor;

		private List<FD.FlowWindow> functions = new List<FD.FlowWindow>();

		public override void OnFlowSettingsGUI() {

			GUILayout.Label(FlowAddon.MODULE_INSTALLED, EditorStyles.centeredGreyMiniLabel);

			GUILayout.Label("Functions", EditorStyles.boldLabel);

			var data = FlowSystem.GetData();
			if (data == null) return;

			this.functions.Clear();
			foreach (var window in data.windowAssets) {

				if (window.IsFunction() == true &&
				    window.IsContainer() == true) {

					this.functions.Add(window);

				}

			}

			if (this.functions.Count == 0) {

				var style = new GUIStyle(GUI.skin.label);
				style.wordWrap = true;
				GUILayout.Label("No functions ware found in the current project. Add new one by clicking on `Create->Functions` menu.", style);

			} else {

				foreach (var function in this.functions) {

					if (GUILayoutExt.LargeButton(function.title, 20f, FlowSystemEditorWindow.SETTINGS_WIDTH) == true) {

						this.flowEditor.SetCenterTo(function);

					}

				}

			}

		}

		public override void OnFlowCreateMenuGUI(string prefix, GenericMenu menu) {

			if (this.InstallationNeeded() == false) {

				menu.AddSeparator(prefix);

				menu.AddItem(new GUIContent(prefix + "Functions/Definition"), on: false, func: () => {

					this.flowEditor.CreateNewItem(() => {

						var window = FlowSystem.CreateWindow(flags: FD.FlowWindow.Flags.IsContainer | FD.FlowWindow.Flags.IsFunction);
						window.title = "Function Definition";

						return window;

					});

				});

				menu.AddItem(new GUIContent(prefix + "Functions/Call"), on: false, func: () => {

					this.flowEditor.CreateNewItem(() => {

						var window = FlowSystem.CreateWindow(flags: FD.FlowWindow.Flags.IsFunction | FD.FlowWindow.Flags.IsSmall | FD.FlowWindow.Flags.CantCompiled);
						window.smallStyleDefault = "flow node 3";
						window.smallStyleSelected = "flow node 3 on";
						window.title = "Function Call";

						window.rect.width = 150f;
						window.rect.height = 100f;

						return window;

					});

				});

			}

		}

		public override bool IsCompilerTransitionAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo) {

			return windowTo.IsFunction() == true &&
					windowTo.IsSmall() == true &&
					windowTo.IsContainer() == false &&
					windowTo.GetFunctionId() > 0;

		}

		public override string OnCompilerTransitionGeneration(FD.FlowWindow window) {

			var functionContainer = window.GetFunctionContainer();
			if (functionContainer != null) {

				var exit = FlowSystem.GetWindow(functionContainer.functionExitId);
				if (exit != null && exit.id == window.id) {

					return FlowFunctionsTemplateGenerator.GenerateReturnMethod(this.flowEditor, exit);

				}

			}

			return base.OnCompilerTransitionGeneration(window);

		}

		public override string OnCompilerTransitionAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo, bool everyPlatformHasUniqueName) {

			if (windowTo.IsFunction() == true &&
			    windowTo.IsSmall() == true &&
			    windowTo.IsContainer() == false &&
			    windowTo.GetFunctionId() > 0) {

				return FlowFunctionsTemplateGenerator.GenerateTransitionMethod(this.flowEditor, windowFrom, windowTo);

			}

			return base.OnCompilerTransitionAttachedGeneration(windowFrom, windowTo, everyPlatformHasUniqueName);

		}

		public override string OnCompilerTransitionTypedAttachedGeneration(FD.FlowWindow windowFrom, FD.FlowWindow windowTo, bool everyPlatformHasUniqueName, System.Type[] types, string[] names) {

			if (windowTo.IsFunction() == true &&
			    windowTo.IsSmall() == true &&
			    windowTo.IsContainer() == false &&
			    windowTo.GetFunctionId() > 0) {

				return FlowFunctionsTemplateGenerator.GenerateTransitionTypedMethod(this.flowEditor, windowFrom, windowTo, types, names);

			}

			return base.OnCompilerTransitionTypedAttachedGeneration(windowFrom, windowTo, everyPlatformHasUniqueName, types, names);

		}

		public override void OnFlowWindowGUI(FD.FlowWindow window) {

			var data = FlowSystem.GetData();
			if (data == null) return;

			var flag = (window.IsFunction() == true &&
					window.IsSmall() == true &&
					window.IsContainer() == false);

			if (flag == true) {

				var alreadyConnectedFunctionIds = new List<int>();

				// Find caller window
				var windowFrom = data.windowAssets.FirstOrDefault((item) => item.HasAttach(window.id));
				if (windowFrom != null) {

					var attaches = windowFrom.GetAttachedWindows();
					foreach (var attachWindow in attaches) {

						if (attachWindow.IsFunction() == true) {

							alreadyConnectedFunctionIds.Add(attachWindow.GetFunctionId());

						}

					}

				}

				foreach (var win in data.windowAssets) {

					if (win.IsFunction() == true &&
					    win.IsContainer() == true) {

						var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
						if ((window.GetFunctionId() == win.id && count == 1) || count == 0) {

						} else {

							if (win.id == window.functionId) window.functionId = 0;
							alreadyConnectedFunctionIds.Remove(win.id);

						}

					}

				}

				var functionId = window.GetFunctionId();
				var functionContainer = functionId == 0 ? null : data.GetWindow(functionId);
				var isActiveSelected = true;

				var oldColor = GUI.color;
				GUI.color = isActiveSelected ? Color.white : Color.grey;
				var result = GUILayoutExt.LargeButton(functionContainer != null ? functionContainer.title : "None", GUILayout.MaxHeight(60f), GUILayout.MaxWidth(150f));
				GUI.color = oldColor;
				var rect = GUILayoutUtility.GetLastRect();
				rect.y += rect.height;

				if (result == true) {

					var menu = new GenericMenu();
					menu.AddItem(new GUIContent("None"), window.functionId == 0, () => {

						window.functionId = 0;

					});

					if (windowFrom != null) {

						alreadyConnectedFunctionIds.Clear();
						var attaches = windowFrom.GetAttachedWindows();
						foreach (var attachWindow in attaches) {

							if (attachWindow.IsFunction() == true) {

								alreadyConnectedFunctionIds.Add(attachWindow.GetFunctionId());

							}

						}

					}
					foreach (var win in data.windowAssets) {

						if (win.IsFunction() == true &&
						    win.IsContainer() == true) {

							var count = alreadyConnectedFunctionIds.Count((e) => e == win.id);
							if ((window.GetFunctionId() == win.id && count == 1) || count == 0) {

								var id = win.id;
								menu.AddItem(new GUIContent(win.title), win.id == window.functionId, () => {

									window.functionId = id;

								});

							} else {

								if (win.id == window.functionId) window.functionId = 0;

								alreadyConnectedFunctionIds.Remove(win.id);
								menu.AddDisabledItem(new GUIContent(win.title));

							}

						}

					}

					menu.DropDown(rect);

				}

			}

		}

		public override bool InstallationNeeded() {

			return false;

		}

	}

}


text:
<?php

namespace Tkgl\CoreBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class AppointmentType extends AbstractType
{
        /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('attendees', 'text', array('required' => false, 'label' => 'Attendees',  'attr' => array('class' => 'input-block-level attendees')))
            ->add('subject', 'text', array('required' => false
                                                          ,'attr' => array('class' => 'input-block-level')))
            ->add('location', 'text', array('required' => false, 'attr' => array('class' => 'input-block-level')))
            ->add('appointmentDescription', 'textarea', array('label' =>'Description', 'required' => false , 'attr' => array('class' => 'input-block-level')))
            ->add('startTime', 'datetime', array('label' => 'Start time',
                                        'required' => false,
                                        'widget' => 'single_text',
                                        'attr' => array('class' => 'appendDateTime ',
                                                                  'data-format'=>"yyyy-MM-dd hh:mm")
                                        ,
                                        'label_attr' => array(
                                            'class' => 'control-label'
                                        )
                                        ))
            ->add('endTime')
            ->add('duration', 'choice', array(
                'choices' => array(
                    '30' => '30min',
                    '60' => '1hr',
                    '90' => '1.5hr',
                    '120' => '2hrs',
                    '180' => '3hrs',
                    '240' => '4hrs',
                    '300' => '5hrs',
                ),
                    'label_attr' => array(
                        'class' => 'control-label'
                    )
               ))
            ->add('appointmentStatus')
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Tkgl\CoreBundle\Entity\Appointment'
        ));
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'tkgl_corebundle_appointment';
    }
}


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using Newtonsoft.Json;

namespace osu.Game.Users
{
    public class CountryStatistics
    {
        [JsonProperty]
        public Country Country;

        [JsonProperty(@"code")]
        public string FlagName;

        [JsonProperty(@"active_users")]
        public long ActiveUsers;

        [JsonProperty(@"play_count")]
        public long PlayCount;

        [JsonProperty(@"ranked_score")]
        public long RankedScore;

        [JsonProperty(@"performance")]
        public long Performance;
    }
}


text:
To build docker image with a specific version of OpenRASP agent, use the `--build-arg` arguments, e.g

```
docker build . --build-arg version_testcase=v1.0.8 --build-arg version_rasp=v0.40
```


text:
package 'cairo-dock'
package 'cairo-dock-plug-ins'

execute "configure-cairo-dock" do
	command "cp -r /vagrant/cookbooks/bootstrap/files/cairo-dock/.config ~/"
end


text:
<?php
/**
 * Global parameters
 * Do NOT use global variables, it makes baby Jesus cry. Use Config!
 *
 * @author Christophe Gosiau <christophe@tigron.be>
 * @author Gerry Demaret <gerry@tigron.be>
 * @author David Vandemaele <david@tigron.be>
 */

require_once dirname(__FILE__) . '/../lib/base/Bootstrap.php';
Bootstrap::boot();