text:
from pyHMI.Colors import *
from pyHMI.DS_ModbusTCP import ModbusTCPDevice
from pyHMI.Tag import Tag
from pyHMI.Dialog import SetIntValueDialog
import time
import tkinter as tk
from tkinter import ttk

class Devices(object):
    # init datasource
    # PLC TBox
    plc = ModbusTCPDevice('localhost', port=502, timeout=2.0, refresh=1.0)
    # init modbus tables
    plc.add_longs_table(0, 1)

class Tags(object):
    # tags list
    # from PLC
    R_LONG_0 = Tag(False, src=Devices.plc, ref={'type': 'long', 'addr': 0})
    # to PLC
    W_WORD_0 = Tag(False, src=Devices.plc, ref={'type': 'w_word', 'addr': 0})
    W_WORD_1 = Tag(False, src=Devices.plc, ref={'type': 'w_word', 'addr': 1})

    @classmethod
    def update_tags(cls):
        # update tags
        pass

class HMITab(tk.Frame):
    def __init__(self, notebook, update_ms=500, *args, **kwargs):
        tk.Frame.__init__(self, notebook, *args, **kwargs)
        # global tk app shortcut
        self.notebook = notebook
        self.app = notebook.master
        # frame auto-refresh delay (in ms)
        self.update_ms = update_ms
        # setup auto-refresh of notebook tab (on-visibility and every update_ms)
        self.bind('<Visibility>', lambda evt: self.tab_update())
        self._tab_update()

    def _tab_update(self):
        if self.winfo_ismapped():
            self.tab_update()
        self.master.after(self.update_ms, self._tab_update)

    def tab_update(self):
        pass

class TabMisc(HMITab):
    def __init__(self, notebook, update_ms=500, *args, **kwargs):
        HMITab.__init__(self, notebook, update_ms, *args, **kwargs)
        # Long
        self.frmState = tk.LabelFrame(self, text='Long value', padx=10, pady=10)
        self.frmState.grid(row=0, column=0, padx=5, pady=5, sticky=tk.NSEW)
        self.longs_list = HMIAnalogList(self.frmState, lbl_args={'width': 15})
        self.longs_list.add('Long @0', Tags.R_LONG_0)
        self.longs_list.build()
        self.frmCmd = tk.LabelFrame(self, text='Set/Reset', padx=10, pady=10)
        self.frmCmd.grid(row=0, column=1, padx=5, pady=5, sticky=tk.NSEW)
        self.cmd_list = HMIButtonList(self.frmCmd, dim=2, btn_args={'width': 15})
        c = ('light salmon', 'OliveDrab1')
        self.cmd_list.add('Word @0 = 0xffff', cmd=lambda: Tags.W_WORD_0.set(0xffff), btn_args={'bg': c[0]})
        self.cmd_list.add('Word @0 = 0x0000', cmd=lambda: Tags.W_WORD_0.set(0x0), btn_args={'bg': c[1]})
        self.cmd_list.add('Word @1= 0xffff', cmd=lambda: Tags.W_WORD_1.set(0xffff), btn_args={'bg': c[0]})
        self.cmd_list.add('Word @1 = 0x0000', cmd=lambda: Tags.W_WORD_1.set(0x0), btn_args={'bg': c[1]})
        self.cmd_list.build()
        # frame "set value of word"
        self.frmEntry = tk.LabelFrame(self, text='Set value of words', padx=10, pady=10)
        self.frmEntry.grid(row=1, column=1, padx=5, pady=5, sticky=tk.NSEW)
        self.button1 = tk.Button(self.frmEntry, text='Write @0',
                                 command=lambda: SetIntValueDialog(self, title='Saisie de valeur',
                                                                   text='Valeur du mot @0',
                                                                   valid_command=Tags.W_WORD_0.set))
        self.button1.grid(row=0, column=0, padx=5, pady=5, sticky=tk.NSEW)
        self.button2 = tk.Button(self.frmEntry, text='Write @1',
                                 command=lambda: SetIntValueDialog(self, title='Saisie de valeur',
                                                                   text='Valeur du mot @1',
                                                                   valid_command=Tags.W_WORD_1.set))
        self.button2.grid(row=0, column=1, padx=5, pady=5, sticky=tk.NSEW)

    def tab_update(self):
        self.longs_list.update()

class HMIToolbar(tk.Frame):
    def __init__(self, tk_app, update_ms=500, *args, **kwargs):
        tk.Frame.__init__(self, tk_app, *args, **kwargs)
        self.tk_app = tk_app
        self.update_ms = update_ms
        # build toolbar
        self.butTbox = tk.Button(self, text='PLC', relief=tk.SUNKEN,
                                 state='disabled', disabledforeground='black')
        self.butTbox.pack(side=tk.LEFT)
        self.lblDate = tk.Label(self, text='', font=('TkDefaultFont', 12))
        self.lblDate.pack(side=tk.RIGHT)
        self.pack(side=tk.BOTTOM, fill=tk.X)
        # setup auto-refresh of notebook tab (on-visibility and every update_ms)
        self.bind('<Visibility>', lambda evt: self.tab_update())
        self._tab_update()

    def _tab_update(self):
        self.tab_update()
        self.master.after(self.update_ms, self._tab_update)

    def tab_update(self):
        self.butTbox.configure(background=GREEN if Devices.plc.connected else PINK)
        self.lblDate.configure(text=time.strftime('%H:%M:%S %d/%m/%Y'))

class HMIApp(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        # configure main window
        self.wm_title('HMI nano test')
        # self.attributes('-fullscreen', True)
        self.geometry("800x600")
        # periodic tags update
        self.do_every(Tags.update_tags, every_ms=500)
        # build a notebook with tabs
        self.note = ttk.Notebook(self)
        self.tab_misc = TabMisc(self.note)
        self.note.add(self.tab_misc, text='Misc (F1)')
        # defaut selected tab
        self.note.select(self.tab_misc)
        self.note.pack(fill=tk.BOTH, expand=True)
        # bind function keys to tabs
        self.bind('<F1>', lambda evt: self.note.select(self.tab_misc))
        # build toolbar
        self.toolbar = HMIToolbar(self, update_ms=500)

    def do_every(self, do_cmd, every_ms=1000):
        do_cmd()
        self.after(every_ms, lambda: self.do_every(do_cmd, every_ms=every_ms))

if __name__ == '__main__':
    # main Tk App
    app = HMIApp()
    app.mainloop()


text:
<?php

namespace App\Http\Requests;

use App\Http\Requests\Request;

class CategoryStoreRequest extends Request
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|unique:categories|max:255',
            'slug' => 'required|unique:categories|max:255',
        ];
    }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Psswrd = function () {
    function Psswrd() {
        var args = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};

        _classCallCheck(this, Psswrd);

        /**
         * Force to generate cryptographically random values
         * @type {boolean}
         */
        this.strict = typeof args.strict === 'undefined' ? true : args.strict;

        /**
         * Default password length
         * @type {number}
         */
        this.length = typeof args.length === 'undefined' ? 12 : args.length;

        /**
         * Default alphabetic characters
         * @type {string}
         */
        this.letters = typeof args.letters === 'undefined' ? 'AaBaCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz' : args.letters;

        /**
         * Default numeric characters
         * @type {string}
         */
        this.numbers = typeof args.numbers === 'undefined' ? '0123456789' : args.numbers;

        /**
         * Default special characters
         * @type {string}
         */
        this.special = typeof args.special === 'undefined' ? '!$%@#' : args.special;
    }

    /**
     * getRandomPassword - Generate a (by default cryptographically) secure random password
     *
     * @param  {number} length the length of password being generated
     * @return {string}        generated password
     */

    _createClass(Psswrd, [{
        key: 'getRandomPassword',
        value: function getRandomPassword() {
            var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.length;

            if (!Number.isInteger(length)) {
                throw new Error("Length must be an integer.");
                return;
            }

            var characters = this._getCharacters();

            var password = '';
            for (var i = 0; i < length; i++) {
                password += characters.charAt(this._getRandomInt(0, characters.length - 1));
            }

            return password;
        }

        /**
         * _getRandomInt - Generate and return a random generated integer
         *
         * @param  {number} min minimum interger being returned
         * @param  {number} max maximum interger being returned
         * @return {number}     random integer
         */

    }, {
        key: '_getRandomInt',
        value: function _getRandomInt(min, max) {
            var array = new Uint8Array(1);
            array = this._getRandomValues(array);

            if (!(array[0] >= min && array[0] <= max)) {
                return this._getRandomInt(min, max);
            }

            return array[0];
        }

        /**
         * _getCharacters - Combine numbers, alphabetic- and special characters
         *
         * @return {string}  the full string of characters
         */

    }, {
        key: '_getCharacters',
        value: function _getCharacters() {
            return this.letters + this.numbers + this.special;
        }

        /**
         * _getRandomValues - Create an array with (by default cryptographically) random values
         *
         * @param  {type} array an empty typed array
         * @return {type}       array with (by default cryptographically) random values
         */

    }, {
        key: '_getRandomValues',
        value: function _getRandomValues(array) {
            if (window.crypto && window.crypto.getRandomValues) {
                window.crypto.getRandomValues(array);
            } else if (_typeof(window.msCrypto) === "object" && typeof window.msCrypto.getRandomValues === 'function') {
                window.msCrypto.getRandomValues(array);
            } else if (this.strict === false) {
                array[0] = Math.floor(Math.random() * 256) + 1;
            } else {
                throw new Error("There was a problem with generating cryptographically random values.");
            }

            return array;
        }
    }]);

    return Psswrd;
}();


text:
namespace docdbwebservice.Areas.HelpPage.ModelDescriptions
{
    public class DictionaryModelDescription : KeyValuePairModelDescription
    {
    }
}


text:
import React from 'react';
import LinearProgress from 'material-ui/Progress/LinearProgress';

export default function DeterminateLinearProgress() {
  return (
    <LinearProgress
      mode="buffer"
      value={60}
      valueBuffer={80}
      style={{
        width: 150,
      }}
    />
  );
}


text:
layout: base
title: Projects
---

Here you can check most of our projects!

If the information that we share here doesn't satisfy your curiosity, please email us and we'll provide you what is lacking.

      {% for project in page.projects %}

          {{ project[1].title }}
          {% if project[1].image %}

          {% endif %}

{{ project[1].short }}

      {% endfor %}


text:
class TemplateVideo < ApplicationRecord
  has_one :message, as: :templatable, dependent: :destroy
end


text:
import logging
logging.root.setLevel(logging.INFO)

# TODO: https://www.hanshq.net/zip.html

import six, ptypes
from ptypes import *

import datetime, time

## General structures
class MSTime(pbinary.struct):
    _fields_ = [
        (5, 'Hour'),
        (6, 'Minute'),
        (5, '2Seconds'),
    ]
    def time(self):
        h, m, ds = (self[fld] for fld in ['Hour', 'Minute', '2Seconds'])
        return datetime.time(h % 24, m % 60, (2 * ds) % 60)

    def summary(self):
        if self['Hour'] < 24 and self['Minute'] < 60 and 2 * self['2Seconds'] < 60:
            res = self.time()
            return res.isoformat()
        return super(MSTime, self).summary()

class MSDate(pbinary.struct):
    _fields_ = [
        (7, 'Year'),
        (4, 'Month'),
        (5, 'Day'),
    ]
    def date(self):
        y, m, d = (self[fld] for fld in ['Year', 'Month', 'Day'])
        return datetime.date(1980 + y, m, d)

    def summary(self):
        res = self.date()
        return res.isoformat()

class VersionMadeBy(pint.enum, pint.uint16_t):
    _values_ = [(n, i) for i, n in enumerate(('MSDOS', 'Amiga', 'OpenVMS', 'Unix', 'VM/CMS', 'Atari ST', 'OS/2', 'Macintosh', 'Z-System', 'CP/M', 'Windows', 'MVS', 'VSE', 'Acorn', 'VFAT', 'Alternate MVS', 'BeOS', 'Tandem', 'Os/400', 'OSX'))]
class VersionNeeded(pint.enum, pint.uint16_t):
    _values_ = []

class DataDescriptor(pstruct.type):
    _fields_ = [
        (pint.uint32_t, 'crc-32'),
        (pint.uint32_t, 'compressed size'),
        (pint.uint32_t, 'uncompressed size'),
    ]

    def summary(self):
        return 'crc-32={:08X} compressed-size={:d} uncompressed-size={:d}'.format(self['crc-32'].int(), self['compressed size'].int(), self['uncompressed size'].int())

class ZipDataDescriptor(pstruct.type):
    Signature = 0x08074b50
    class _SignatureScan(parray.terminated):
        _object_ = pint.uint8_t
        def isTerminator(self, value):
            if len(self.value) > 3:
                octets = pint.uint32_t().set(ZipDataDescriptor.Signature)
                return self[-4:].serialize() == octets.serialize()
            return False
        def int(self):
            return self[-4:].cast(pint.uint32_t).int()
        def data(self):
            return self.serialize()[:-4]

    _fields_ = [
        (_SignatureScan, 'data'),
        (DataDescriptor, 'descriptor'),
    ]

    def summary(self):
        return 'descriptor={{{:s}}} data={{...}}'.format(self['descriptor'].summary())

    def data(self, **kwds):
        return self['data'].data()

@pbinary.littleendian
class BitFlags(pbinary.flags):
    _fields_ = [
        (2, 'Reserved'),
        (1, 'MaskedDirectory'),
        (1, 'PKEnhanced'),
        (1, 'UTF8'),
        (4, 'unused'),
        (1, 'StrongEncryption'),
        (1, 'CompressedPatchData'),
        (1, 'EnhancedDeflating'),
        (1, 'PostDescriptor'),
        (2, 'Compression'),
        (1, 'Encrypted'),
    ]

## Compression methods
class CompressionMethod(pint.enum, pint.uint16_t):
    _values_ = [
        ('Stored', 0),
        ('Shrunk', 1),      # LZW
        ('Reduced(1)', 2),  # Expanding
        ('Reduced(2)', 3),
        ('Reduced(3)', 4),
        ('Reduced(4)', 5),
        ('Imploded', 6),    # Shannon-Fano
        ('Tokenized', 7),
        ('Deflated', 8),    # zlib?
        ('Deflate64', 9),   # zlib64
        ('PKImplode', 10),  # old IBM TERSE
        ('BZIP2', 12),      # bz2
        ('LZMA', 14),       # lzma
        ('Terse', 18),      # IBM TERSE
        ('LZ77', 19),
        ('WavPack', 97),    # audio
        ('PPMd', 98),
    ]

class CompressionMethodFlags(ptype.definition):
    cache = {}
    class unknown(pbinary.struct):
        _fields_ = [(2, 'unknown')]
    default = unknown

@CompressionMethodFlags.define
class MethodImplodingFlags(pbinary.flags):
    type = 6
    _fields_ = [(1, '8kDictionary'), (1, '3Shannon-FanoTrees')]

class MethodDeflatingFlags(pbinary.struct):
    _fields_ = [(2, 'Quality')]
@CompressionMethodFlags.define
class MethodDeflatingFlags8(MethodDeflatingFlags):
    type = 8
@CompressionMethodFlags.define
class MethodDeflatingFlags9(MethodDeflatingFlags):
    type = 9

@CompressionMethodFlags.define
class MethodLZMAFlags(pbinary.flags):
    type = 14
    _fields_ = [(1, 'EOS'), (1, 'unused')]

## Extra data field mappings
class ExtraField(ptype.definition):
    cache = {}

class Extra_NTFS_TagType(ptype.definition):
    attribute, cache = 'tag', {}

class Extra_NTFS_Tag(pstruct.type):
    _fields_ = [
        (pint.uint16_t, 'Tag'),
        (pint.uint16_t, 'Size'),
        (lambda self: Extra_NTFS_TagType.get(self['Tag'].li.int(), length=self['Size'].li.int()), 'Attribute'),
    ]

    def summary(self):
        return "({:+#x}) {:s}".format(self['Size'].int(), self['Attribute'].summary())

@Extra_NTFS_TagType.define
class NTFS_Attributes(pstruct.type):
    tag = 1
    class TenthOfAMicrosecond(pint.uint64_t):
        def datetime(self):
            res, epoch = self.int(), datetime.datetime(1601, 1, 1, tzinfo=datetime.timezone.utc)
            return epoch + datetime.timedelta(microseconds=res * 1e-1)
        def summary(self):
            tzinfo = datetime.timezone(datetime.timedelta(seconds=-(time.altzone if time.daylight else time.timezone)))
            res = self.datetime().astimezone(tzinfo)
            return res.isoformat()

    _fields_ = [
        (TenthOfAMicrosecond, 'Mtime'),
        (TenthOfAMicrosecond, 'Atime'),
        (TenthOfAMicrosecond, 'Ctime'),
    ]

    def summary(self):
        mtime, atime, ctime = (self[fld].datetime() for fld in ['Mtime', 'Atime', 'Ctime'])
        return "Mtime={:s} Atime={:s} Ctime={:s}".format(mtime.isoformat(), atime.isoformat(), ctime.isoformat())

@ExtraField.define
class Extra_NTFS(pstruct.type):
    type = 0x000a
    _fields_ = [
        (pint.uint32_t, 'Reserved'),
        (lambda self: dyn.blockarray(Extra_NTFS_Tag, self.blocksize() - self['Reserved'].li.size()), 'Tags'),
    ]

    def summary(self):
        return "Reserved={:#x} [{:s}]".format(self['Reserved'].int(), ', '.join(item.summary() for item in self['Tags']))

# FIXME: Add these from section 4.6
class Extensible_data_field(pstruct.type):
    def __unknown(self):
        cb = sum(self[k].li.size() for k in ('id','size','data'))
        return dyn.block(self.blocksize() - cb)

    def __data(self):
        id, size = (self[item].li for item in ['id', 'size'])
        return ExtraField.get(id.int(), blocksize=lambda self, bs=size.int(): bs)

    _fields_ = [
        (pint.uint16_t, 'id'),
        (pint.uint16_t, 'size'),
        (__data, 'data'),
        (__unknown, 'unknown'),
    ]

    def summary(self):
        return "{:s} {:s}".format(self['data'].classname(), self['data'].summary())

## File records
class ZipRecord(ptype.definition):
    cache = {}
    attribute = 'signature'

class LocalFileHeader(pstruct.type):
    signature = 0, 0x04034b50

@ZipRecord.define
class LocalFileHeader32(LocalFileHeader):
    signature = 32, 0x04034b50

    def __extra_field(self):
        cb = self['extra field length'].li
        return dyn.clone(Extensible_data_field, blocksize=lambda s, bs=cb.int(): bs)

    def __file_data(self):
        desc = self.p.DirectoryRecord['data descriptor'] if hasattr(self.p, 'DirectoryRecord') else self['data descriptor'].li
        bs = desc['compressed size'].int()

        # FIXME: this should be returning a ptype.encoded_t for the compression method
        return dyn.block(bs)

    def __post_data_descriptor(self):
        if hasattr(self.p, 'DirectoryRecord'):
            flags = self.p.DirectoryRecord['general purpose bit flag']
            return DataDescriptor if flags['PostDescriptor'] else ptype.undefined
        flags = self['general purpose bit flag'].li
        return ZipDataDescriptor if flags['PostDescriptor'] else ptype.undefined

    _fields_ = [
        (pint.uint16_t, 'version needed to extract'),
        (BitFlags, 'general purpose bit flag'),
        (CompressionMethod, 'compression method'),
        (pbinary.littleendian(MSTime), 'last mod file time'),
        (pbinary.littleendian(MSDate), 'last mod file date'),
        (DataDescriptor, 'data descriptor'),
        (pint.uint16_t, 'file name length'),
        (pint.uint16_t, 'extra field length'),
        (lambda self: dyn.clone(pstr.string, length=self['file name length'].li.int()), 'file name'),
        (__extra_field, 'extra field'),
        # XXX: if encrypted, include encryption header here
        (__file_data, 'file data'),
        # XXX: i think this record is actually encoded within the file data
        (__post_data_descriptor, 'post data descriptor'),
    ]

    def summary(self):
        needed = self['version needed to extract']
        method, desc = self.Method(), self.Descriptor()
        dt = datetime.datetime.combine(self['last mod file date'].date(), self['last mod file time'].time())
        return "{:s} (version {:d}) {!r} datetime={:s} compressed={:#x} uncompressed={:#x} crc32={:#x}{:s}".format(method.str(), needed.int(), self.Name(), dt.isoformat(), desc['compressed size'].int(), desc['uncompressed size'].int(), desc['crc-32'].int(), " {:s}".format(self['general purpose bit flag'].summary()) if self['general purpose bit flag'].int() > 0 else '')

    def Name(self):
        return self['file name'].str()
    def Method(self):
        return self['compression method']
    def Descriptor(self):
        PostDescriptorQ = self['general purpose bit flag'].o['PostDescriptor']
        return self['post data descriptor']['descriptor'] if PostDescriptorQ else self['data descriptor']
    def Data(self):
        PostDescriptorQ = self['general purpose bit flag'].o['PostDescriptor']
        return self['post data descriptor'].data() if PostDescriptorQ else self['file data'].serialize()

    def extract(self, **kwds):
        res = self.Data()
        if not kwds.get('decompress', False):
            logging.debug('Extracting {:d} bytes of compressed content'.format(len(res)))
            return res

        method = self['compression method']
        if method['Stored']:
            logging.debug('Decompressing ({:s}) {:d} bytes of content.'.format('Uncompressed', len(res)))
            return res
        elif method['Deflated']:
            import zlib
            logging.debug('Decompressing ({:s}) {:d} bytes of content.'.format('Zlib', len(res)))
            return zlib.decompress(res, -zlib.MAX_WBITS)
        elif method['BZIP2']:
            import bz2
            logging.debug('Decompressing ({:s}) {:d} bytes of content.'.format('BZip2', len(res)))
            return bz2.decompress(res)
        elif method['LZMA']:
            import lzma
            logging.debug('Decompressing ({:s}) {:d} bytes of content.'.format('Lzma', len(res)))
            return lzma.decompress(res)
        raise ValueError(method)

    def listing(self):
        cls, index, ofs, bs = self.classname(), int(self.getparent(Record).name()), self.getparent(Record).getoffset(), self.getparent(Record).size()
        filename, meth, descr = self.Name(), self.Method(), self.Descriptor()
        dt = datetime.datetime.combine(self['last mod file date'].date(), self['last mod file time'].time())
        return '{{{:d}}} {:s} ({:x}{:+x}) {!r} method={:s} {:s} timestamp={:s}'.format(index, cls, ofs, bs, filename, meth.str(), descr.summary(), dt.isoformat())

class CentralDirectoryEntry(pstruct.type):
    signature = 0, 0x02014b50

@ZipRecord.define
class CentralDirectoryEntry32(CentralDirectoryEntry):
    signature = 32, 0x02014b50

    def __relative_offset_of_local_header(self):
        t = dyn.clone(Record, DirectoryRecord=self)
        return dyn.pointer(t, pint.uint32_t)

    def __file_name(self):
        res = self['file name length'].li
        return dyn.clone(pstr.string, length=res.int())

    def __extra_field(self):
        cb = self['extra field length'].li
        return dyn.clone(Extensible_data_field, blocksize=lambda s, bs=cb.int(): bs)

    def __file_comment(self):
        res = self['file comment length'].li
        return dyn.clone(pstr.string, length=res.int())

    _fields_ = [
        (VersionMadeBy, 'version made by'),
        (VersionNeeded, 'version needed to extract'),
        (BitFlags, 'general purpose bit flag'),
        (CompressionMethod, 'compression method'),
        (pbinary.littleendian(MSTime), 'last mod file time'),
        (pbinary.littleendian(MSDate), 'last mod file date'),
        (DataDescriptor, 'data descriptor'),
        (pint.uint16_t, 'file name length'),
        (pint.uint16_t, 'extra field length'),
        (pint.uint16_t, 'file comment length'),
        (pint.uint16_t, 'disk number start'),
        (pint.uint16_t, 'internal file attributes'),
        (pint.uint32_t, 'external file attributes'),
        (__relative_offset_of_local_header, 'relative offset of local header'),
        (__file_name, 'file name'),
        (__extra_field, 'extra field'),
        (__file_comment, 'file comment'),
    ]

    def summary(self):
        disk, offset = (self[item] for item in ['disk number start', 'relative offset of local header'])
        version, needed = (self[item] for item in ['version made by', 'version needed to extract'])
        method, desc = self.Method(), self.Descriptor()
        dt = datetime.datetime.combine(self['last mod file date'].date(), self['last mod file time'].time())
        return "disk#{:d} {:s} (version={:d}<{:d}) offset={:+#x} {!r}{:s} datetime={:s} compressed={:#x} uncompressed={:#x} crc32={:#x}{:s}".format(disk.int(), method.str(), needed.int(), version.int(), offset.int(), self.Name(), " ({:s})".format(self['file comment'].str()) if self['file comment length'].int() else '', dt.isoformat(), desc['compressed size'].int(), desc['uncompressed size'].int(), desc['crc-32'].int(), " {:s}".format(self['general purpose bit flag'].summary()) if self['general purpose bit flag'].int() > 0 else '')

    def Name(self):
        return self['file name'].str()
    def Method(self):
        return self['compression method']
    def Descriptor(self):
        return self['data descriptor']
    def Comment(self):
        return self['file comment'].str()
    def Record(self):
        header = self['relative offset of local header'].d
        return header.li

    def extract(self, **kwds):
        return self.serialize()

    def listing(self):
        cls, index, ofs, bs = self.classname(), int(self.getparent(Record).name()), self.getparent(Record).getoffset(), self.getparent(Record).size()
        filename, meth, descr = self.Name(), self.Method(), self.Descriptor()
        dt = datetime.datetime.combine(self['last mod file date'].date(), self['last mod file time'].time())
        return '{{{:d}}} {:s} ({:x}{:+x}) {!r} version-made-by={:s} version-needed-to-extract={:s} compression-method={:s} {:s} timestamp={:s} disk-number-start={:d} internal-file-attributes={:#x} external-file-attributes={:#x}'.format(index, cls, ofs, bs, filename, self['version made by'].str(), self['version needed to extract'].str(), meth.str(), descr.summary(), dt.isoformat(), self['disk number start'].int(), self['internal file attributes'].int(), self['external file attributes'].int()) + ('// {:s}'.format(self.Comment()) if self['file comment length'].int() > 0 else '')

class EndOfCentralDirectory(pstruct.type):
    signature = 0, 0x06054b50

@ZipRecord.define
class EndOfCentralDirectory32(EndOfCentralDirectory):
    signature = 32, 0x06054b50
    _fields_ = [
        (pint.uint16_t, 'number of this disk'),
        (pint.uint16_t, 'number of the disk with the start of the central directory'),
        (pint.uint16_t, 'total number of entries in the central directory on this disk'),
        (pint.uint16_t, 'total number of entries in the central directory'),
        (pint.uint32_t, 'size of the central directory'),
        (lambda self: dyn.pointer(Record, pint.uint32_t), 'offset of start of central directory with respect to the starting disk number'),
        (pint.uint16_t, '.ZIP file comment length'),
        (lambda s: dyn.clone(pstr.string, length=s['.ZIP file comment length'].li.int()), '.ZIP file comment'),
    ]

    def summary(self):
        disk = self['number of this disk']
        socdisk = self['number of the disk with the start of the central directory']
        offset = self['offset of start of central directory with respect to the starting disk number']
        length = self['total number of entries in the central directory on this disk']
        total = self['total number of entries in the central directory']
        size = self['size of the central directory']
        return "disk#{:d} soc-disk#{:d} soc-offset={:#x} soc-length={:d}/{:d} soc-size={:+d}{:s}".format(disk.int(), socdisk.int(), offset.int(), length.int(), total.int(), size.int(), " ({:s})".format(self['.ZIP file comment'].str()) if self['.ZIP file comment length'].int() else '')

    def Record(self):
        directory = self['offset of start of central directory with respect to the starting disk number'].d
        return directory.li

    def Comment(self):
        return self['.ZIP file comment'].str()

    def extract(self, **kwds):
        return self.serialize()

    def listing(self):
        cls, index, ofs, bs = self.classname(), int(self.getparent(Record).name()), self.getparent(Record).getoffset(), self.getparent(Record).size()
        return '{{{:d}}} {:s} ({:x}{:+x}) number-of-this-disk={:d} number-of-this-disk-with-the-start-of-the-central-directory={:d} total-number-of-entries-in-the-central-directory={:d} size-of-the-central-directory={:d} offset-of-the-start-of-central-directory-with-respect-to-the-starting-disk-number={:d}'.format(index, cls, ofs, bs, self['number of this disk'].int(), self['number of the disk with the start of the central directory'].int(), self['total number of entries in the central directory on this disk'].int(), self['total number of entries in the central directory'].int(), self['size of the central directory'].int(), self['offset of start of central directory with respect to the starting disk number']) + ('// {:s}'.format(self.Comment()) if self['.ZIP file comment length'].int() > 0 else '')

@ZipRecord.define
class EndOfCentralDirectory64(EndOfCentralDirectory):
    signature = 64, 0x06054b50

    def __ExtensibleDataSector(self):
        size = EndOfCentralDirectory().a.size()
        expectedSize = self['size of zip64 end of central directory record'].li.int()
        if expectedSize < size:
            ptypes.Config.log.warning('size of zip64 end of central directory record is less than the minimum size: {:#x} < {:#x}'.format(expectedSize, size))
        return dyn.block(expectedSize - size)

    _fields_ = [
        (pint.uint64_t, 'size of zip64 end of central directory record'),

        (VersionMadeBy, 'version made by'),
        (VersionNeeded, 'version needed to extract'),
        (pint.uint32_t, 'number of the disk with the start of the zip64 end of central directory'),

        (pint.uint32_t, 'number of the disk with the start of the central directory'),
        (pint.uint64_t, 'total number of entries in the central directory on this disk'),

        (pint.uint64_t, 'total number of entries in the central directory'),
        (pint.uint64_t, 'size of the central directory'),
        (pint.uint64_t, 'offset of start of central directory with respect to the starting disk number'),
        (__ExtensibleDataSector, 'zip64 extensible data sector'),
    ]

    def summary(self):
        offset = self['offset of start of central directory with respect to the starting disk number']
        length = self['total number of entries in the central directory on this disk']
        size = self['size of the central directory']
        return "(version {:d}>{:d} index {:d}) offset={:#x} length={:d} size={:+d}{:s}".format(self['version made by'].int(), self['version needed to extract'].int(), self['number of this disk'].int(), offset.int(), length.int(), size.int(), " ({:s})".format(self['.ZIP file comment'].str()) if self['.ZIP file comment length'].int() else '')

    def extract(self, **kwds):
        return self.serialize()

    def listing(self):
        cls, index, ofs, bs = self.classname(), int(self.getparent(Record).name()), self.getparent(Record).getoffset(), self.getparent(Record).size()
        data = self['zip64 extensible data sector'].summary()
        return '{{{:d}}} {:s} ({:x}{:+x}) version-made-by={:s} version-needed-to-extract={:s} number-of-the-disk-with-the-start-of-the-zip64-end-of-central-directory={:d} number-of-the-disk-with-the-start-of-the-central-directory={:d} total-number-of-entires-in-the-central-directory-on-this-disk={:d} total-number-of-entries-in-the-central-directory={:d} size-of-the-central-directory={:#x} offset-of-start-of-central-directory-with-respect-to-the-starting-disk-number={:d}'.format(index, cls, ofs, bs, self['number of the disk with the start of the zip64 end of central directory'].int(), self['number of the disk with the start of the central directory'].int(), self['total number of entries in the central directory on this disk'].int(), self['total number of entries in the central directory'].int(), self['size of the central directory'].int(), self['offset of start of central directory with respect to the starting disk number'].int(), datasector)

class EndOfCentralDirectoryLocator(pstruct.type):
    signature = 0, 0x07054b50

@ZipRecord.define
class EndOfCentralDirectoryLocator64(EndOfCentralDirectoryLocator):
    signature = 64, 0x07054b50
    _fields_ = [
        (pint.uint32_t, 'number of the disk with the start of the zip64 end of central directory'),
        (pint.uint64_t, 'relative offset of the zip64 end of central directory record'),
        (pint.uint32_t, 'total number of disks'),
    ]

    def summary(self):
        disk = self['number of the disk with the start of the zip64 end of central directory']
        offset = self['relative offset of the zip64 end of central directory record']
        return "disk#={:d} eoc={:#0{:d}x} disks={:d}".format(disk.int(), offset.int(), 2 + 2 * offset.size(), self['total number of disks'].int())

    def extract(self, **kwds):
        return self.serialize()

    def listing(self):
        cls, index, ofs, bs = self.classname(), int(self.getparent(Record).name()), self.getparent(Record).getoffset(), self.getparent(Record).size()
        return '{{{:d}}} {:s} ({:x}{:+x}) number-of-the-disk-with-the-start-of-the-zip64-end-of-central-directory={:d} relative-offset-of-the-zip64-end-of-central-directory-record={:#x} total-number-of-disks={:d}'.format(index, cls, ofs, bs, self['number of the disk with the start of the zip64 end of central directory'].int(), self['relative offset of the zip64 end of central directory record'].int(), self['total number of disks'].int())

class ArchiveExtraData(pstruct.type):
    signature = 0, 0x08064b50

@ZipRecord.define
class ArchiveExtraData32(ArchiveExtraData):
    signature = 32, 0x08064b50

    _fields_ = [
        (pint.uint32_t, 'extra field length'),
        (lambda s: dyn.block(s['extra field length'].li.int()), 'extra field data'),
    ]

    def extract(self, **kwds):
        return self['extra field data'].serialize()

    def listing(self):
        cls, index, ofs, bs = self.classname(), int(self.getparent(Record).name()), self.getparent(Record).getoffset(), self.getparent(Record).size()
        return '{{{:d}}} {:s} ({:x}{:+x}) extra-field-length={:d} extra-field={:s}'.format(index, cls, ofs, bs, self['extra field length'].int(), self['extra field data'].summary())

class DigitalSignature(pstruct.type):
    signature = 0, 0x05054b50

@ZipRecord.define
class DigitalSignature32(DigitalSignature):
    signature = 32, 0x05054b50

    _fields_ = [
        (pint.uint16_t, 'size of data'),
        (lambda s: dyn.block(s['size of data'].li.int()), 'signature data'),
    ]

    def extract(self, **kwds):
        return self['signature data'].serialize()

    def listing(self):
        cls, index, ofs, bs = self.classname(), int(self.getparent(Record).name()), self.getparent(Record).getoffset(), self.getparent(Record).size()
        return '{{{:d}}} {:s} ({:x}{:+x}) size-of-data={:d} signature-data={:s}'.format(index, cls, ofs, bs, self['size of data'].int(), self['signature data'].summary())

## File records
class Record(pstruct.type):
    def __Record(self):
        bits, sig = 32, self['Signature'].li.int()
        try:
            p = self.getparent(Directory)
        except ptypes.error.ItemNotFoundError:
            return ZipRecord.lookup((bits, sig))

        t = ZipRecord.lookup((bits, sig))
        if isinstance(p, File) and hasattr(p, 'Directory'):
            cd = p.Directory
            return dyn.clone(t, DirectoryRecord=cd.member(self.getoffset()))
        return t

    # FIXME: Signature should be a parray.terminated which seeks for a valid signature
    #        and has a method which returns the correct code for __Record to be correct.
    _fields_ = [
        (pint.uint32_t, 'Signature'),
        (__Record, 'Record'),
    ]

    def summary(self):
        return "{:0{:d}x}".format(self['Signature'].int(), 2 * self['Signature'].size(), self['Record'].summary())

# Central Directory
class Directory(parray.terminated):
    _object_ = Record

    def isTerminator(self, value):
        if isinstance(value['record'], EndOfCentralDirectory):
            return True
        return isinstance(self.length, six.integer_types) and len(self.value) >= self.length

    def member(self, offset):
        for item in self:
            rec = item['record']
            if isinstance(rec, CentralDirectoryEntry) and offset == rec['relative offset of local header'].int():
                return rec
            continue
        raise IndexError(offset)

class File(Directory):
    _object_ = Record

    def isTerminator(self, value):
        return isinstance(value['record'], EndOfCentralDirectory)

if __name__ == '__main__':
    import sys, os, os.path
    import zlib, logging, argparse
    import ptypes, archive.zip
    if sys.platform == 'win32': import msvcrt

    arg_p = argparse.ArgumentParser(prog=sys.argv[0] if len(sys.argv) > 0 else 'zip.py', description='List or extract information out of a .zip file', add_help=False)
    arg_p.add_argument('FILE', nargs='*', action='append', type=str, help='list of filenames to extract')
    arg_p.add_argument('-v', '--verbose', action='store_true', help='output verbose logging information', dest='verbose')
    arg_commands_gr = arg_p.add_argument_group('main operation mode')
    arg_commands_gr.add_argument('-h', '--help', action='store_const', help='show this help message and exit', dest='mode', const='help')
    arg_commands_gr.add_argument('-l', '--list', action='store_const', help='list the contents of an archive', dest='mode', const='list')
    arg_commands_gr.add_argument('-la', '--list-all', action='store_const', help='list the entire contents of an archive', dest='mode', const='list-all')
    arg_commands_gr.add_argument('-x', '--extract', '--get', action='store_const', help='extract the specified file records', dest='mode', const='extract')
    arg_commands_gr.add_argument('-d', '--dump', action='store_const', help='dump the specified file records', dest='mode', const='dump')
    arg_device_gr = arg_p.add_argument_group('device selection and switching')
    arg_device_gr.add_argument('-F', action='store_false', default=True, dest='use_eoc', help='use entire file instead of central directory')
    arg_device_gr.add_argument('-f', '--file', action='store', type=argparse.FileType('rb'), default='-', metavar='ARCHIVE', help='use archive file or device ARCHIVE', dest='source')
    arg_device_gr.add_argument('-o', '--output', action='store', type=str, metavar='DEVICE', help='extract files to specified DEVICE or FORMAT', dest='target', default='-')
    arg_info_gr = arg_p.add_argument_group('format output')
    arg_info_gr.add_argument('-j', '--compressed', action='store_true', help='extract data from archive in its compressed form', dest='compress', default=False)

    if len(sys.argv) <= 1:
        six.print_(arg_p.format_usage(), file=sys.stdout)
        sys.exit(0)

    args = arg_p.parse_args(sys.argv[1:])
    if args.mode == 'help':
        six.print_(arg_p.format_help(), file=sys.stdout)
        sys.exit(0)

    # fix up arguments
    source_a, target_a = args.source.buffer if hasattr(args.source, 'buffer') else args.source, args.target.buffer if hasattr(args.target, 'buffer') else args.target
    if args.use_eoc:
        if source_a.name == '<stdin>':
            if sys.platform == 'win32': msvcrt.setmode(source_a.fileno(), os.O_BINARY)
            source_data = source_a.read()
        else:
            source_data = source_a.read()
        source = ptypes.prov.bytes(source_data)
    else:
        source = ptypes.prov.fileobj(source_a)

    if target_a == '-':
        if sys.platform == 'win32': msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
        target = sys.stdout
    else:
        target = target_a

    filelist, = args.FILE
    filelookup = set(filelist)
    indexlookup = set((int(n) for n in filelist if n.isdigit()))

    isMatchedName = lambda r: (not filelookup) or ('file name' in r['Record'].keys() and r['Record']['file name'].str() in filelookup)
    isMatchedIndex = lambda r: int(r.name()) in indexlookup
    isMatched = lambda r: isMatchedName(r) or isMatchedIndex(r)

    # some useful functions
    def iterate_file(root):
        for rec in root:
            if args.mode == 'list-all' and isMatched(rec):
                yield rec
            elif isMatchedIndex(rec):
                yield rec
            elif isMatchedName(rec) and isinstance(rec['Record'], archive.zip.LocalFileHeader):
                yield rec
            continue
        return

    def iterate_directory(root):
        for rec in root:
            if args.mode == 'list-all' and isMatched(rec):
                yield rec
            elif isMatchedIndex(rec):
                yield rec
            elif isMatchedName(rec) and isinstance(rec['Record'], archive.zip.CentralDirectoryEntry):
                yield rec
            continue
        return

    def dictionary(root):
        res = {}
        for k in root.keys():
            v = root[k]
            if isinstance(v, pint.type):
                res[k] = v.int()
            elif isinstance(v, pstr.type):
                try:
                    res[k] = v.str()
                except UnicodeDecodeError:
                    res[k] = v.serialize()
            else:
                res[k] = v.summary()
            continue
        return res

    # set the verbosity
    if args.verbose:
        logging.root.setLevel(logging.DEBUG)

    # first locate the EndOfCentralDirectory
    eoc = None
    if args.use_eoc:
        logging.debug("Locating EndOfCentralDirectory in {:#x} bytes...".format(len(source_data)))
        signature = pint.uint32_t().set(EndOfCentralDirectory.signature[1])
        idx = signature.size() + source_data[::-1].index(signature.serialize()[::-1])
        rec = archive.zip.Record(source=ptypes.prov.bytes(source_data[-idx:])).l

        # validate it
        if rec['Signature'].int() == signature.int():
            eoc = rec['Record']
        else:
            logging.fatal("Unable to locate end of central directory")

    # now we can read the central directory
    if eoc is None:
        logging.debug("Reading zip file without CentralDirectory...")
        z = archive.zip.File(source=source)
        iterate = iterate_file

    else:
        offset_f, length_f = (eoc[item] for item in ['offset of start of central directory with respect to the starting disk number', 'total number of entries in the central directory on this disk'])
        logging.debug("Reading {:d} elements from CentralDirectory at offset {:#x}...".format(length_f.int(), offset_f.int()))
        z = archive.zip.Directory(source=source, offset=offset_f.int())
        iterate = iterate_directory

    # handle the mode that the user specified
    if args.mode == 'list':
        z = z.l
        for rec in iterate(z[:-1]):
            print(rec['Record'].listing())
        sys.exit(0)

    elif args.mode == 'list-all':
        z = z.l
        for rec in iterate(z[:-1]):
            print(rec['Record'].listing())
        sys.exit(0)

    elif args.mode == 'extract':
        target = target or os.path.join('.', '{path:s}', '{name:s}')

    elif args.mode == 'dump':
        target = target or sys.stdout

    # help
    else:
        six.print_(arg_p.format_help(), file=sys.stdout)
        sys.exit(1)

    # for each record...
    z = z.l
    for rec in iterate(z[:-1]):

        # assign what data we're writing
        if args.mode == 'extract':
            if isinstance(rec['Record'], archive.zip.CentralDirectoryEntry):
                drec = rec['Record']['relative offset of local header'].d.li
                data = drec['Record'].extract(decompress=not args.compress)
            else:
                data = rec['Record'].extract(decompress=not args.decompress)

            data = rec['Record']['relative offset of local header'].d.li['Record'].extract(decompress=not args.compress) if isinstance(rec['Record'], archive.zip.CentralDirectoryEntry) else rec['Record'].extract(decompress=not args.decompress)
        elif args.mode == 'dump':
            data = '\n'.join((' '.join((ptypes.utils.repr_class(rec.classname()), rec.name())), ptypes.utils.indent('{!r}'.format(rec['Record']))))
        else:
            raise NotImplementedError(args.mode)

        # set some reasonable defaults for formatting
        res = dictionary(rec['Record'])
        res['index'] = int(rec.name())
        res['path'], res['name'] = os.path.split(res['file name'] if 'file name' in res.keys() else rec.name())

        # write to a generated filename
        if isinstance(target, six.string_types):
            outname = target.format(**res)

            dirpath, name = os.path.split(outname)
            dirpath and not os.path.isdir(dirpath) and os.makedirs(dirpath)

            res = os.path.join(dirpath, name)
            if res.endswith(os.path.sep):
                if os.path.isdir(res):
                    logging.warning('Refusing to overwrite already existing subdirectory for record({:d}): {:s}'.format(int(rec.name()), res))
                else:
                    logging.info('Creating subdirectory for record({:d}): {:s}'.format(int(rec.name()), res))
                    os.makedirs(res)
                continue

            if os.path.exists(res):
                logging.warning('Overwriting already existing file with record({:d}): {:s}'.format(int(rec.name()), res))
            else:
                logging.info('Creating new file for record({:d}): {:s}'.format(int(rec.name()), res))

            logging.debug('{:s}ing {:d} bytes from record({:d}) to file: {:s}'.format(args.mode.title(), len(data), int(rec.name()), res))
            with open(res, 'wb') as out: out.write(data)

        # fall-back to writing to already open target
        else:
            logging.debug('{:s}ing {:d} bytes from record({:d}) to stream: {:s}'.format(args.mode.title(), len(data), int(rec.name()), target.name))
            six.print_(data.decode('latin1'), file=target)
        continue

    sys.exit(0)


text:
package com.mcoding.base.product.persistence.product;

import com.mcoding.base.core.PageView;
import com.mcoding.base.product.bean.product.Product;
import com.mcoding.base.product.bean.product.ProductExample;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;

public interface ProductMapper {
    int countByExample(ProductExample example);

    int deleteByExample(ProductExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(Product record);

    int insertSelective(Product record);

    List<Product> selectByExampleWithBLOBs(ProductExample example);

    List<Product> selectByExample(ProductExample example);

    Product selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") Product record, @Param("example") ProductExample example);

    int updateByExampleWithBLOBs(@Param("record") Product record, @Param("example") ProductExample example);

    int updateByExample(@Param("record") Product record, @Param("example") ProductExample example);

    int updateByPrimaryKeySelective(Product record);

    int updateByPrimaryKeyWithBLOBs(Product record);

    int updateByPrimaryKey(Product record);

	List<Product> selectByExampleByPage(ProductExample example);

    List<Product> findConditionByPage(@Param("example")ProductExample example, @Param("categoryId") Integer categoryId);
}


text:
package net.openhft.chronicle.tcp;

import net.openhft.chronicle.*;
import net.openhft.chronicle.tools.ResizableDirectByteBufferBytes;
import net.openhft.lang.io.Bytes;
import net.openhft.lang.io.DirectByteBufferBytes;
import net.openhft.lang.model.constraints.NotNull;
import net.openhft.lang.thread.LightPauser;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Closeable;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.Set;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicBoolean;

public abstract class SourceTcp {
    protected final Logger logger;
    protected final String name;
    protected final AtomicBoolean running;
    protected final ChronicleQueueBuilder.ReplicaChronicleQueueBuilder builder;
    protected final ThreadPoolExecutor executor;
    protected final LightPauser pauser;

    protected SourceTcp(String name, final ChronicleQueueBuilder.ReplicaChronicleQueueBuilder builder, ThreadPoolExecutor executor) {
        this.builder = builder;
        this.name = ChronicleTcp.connectionName(name, this.builder.bindAddress(), this.builder.connectAddress());
        this.logger = LoggerFactory.getLogger(this.name);
        this.running = new AtomicBoolean(false);
        this.executor = executor;
        this.pauser = new LightPauser(builder.busyPeriodTimeNanos(), builder.parkPeriodTimeNanos());
    }

    public SourceTcp open() {
        this.running.set(true);
        this.executor.execute(createHandler());

        return this;
    }

    public boolean close() {
        running.set(false);
        executor.shutdown();

        try {
            executor.awaitTermination(
                    builder.selectTimeout() * 2,
                    builder.selectTimeoutUnit());
        } catch (InterruptedException ignored) {
        }

        return !running.get();
    }

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

    public void dataNotification() {
        pauser.unpause();
    }

    public abstract boolean isLocalhost();

    protected abstract Runnable createHandler();

    /**
     * Creates a session handler according to the Chronicle the sources is connected to.
     *
     * @param socketChannel The {@link java.nio.channels.SocketChannel}
     * @return The Runnable
     */
    protected Runnable createSessionHandler(final @NotNull SocketChannel socketChannel) {
        final Chronicle chronicle = builder.chronicle();
        if (chronicle != null) {
            if (chronicle instanceof IndexedChronicle) {
                builder.connectionListener().onConnect(socketChannel);
                return new IndexedSessionHandler(socketChannel);

            } else if (chronicle instanceof VanillaChronicle) {
                builder.connectionListener().onConnect(socketChannel);
                return new VanillaSessionHandler(socketChannel);

            } else {
                throw new IllegalStateException("Chronicle must be Indexed or Vanilla");
            }
        }

        throw new IllegalStateException("Chronicle can't be null");
    }

    // *************************************************************************
    //
    // *************************************************************************

    /**
     * Abstract class for Indexed and Vanilla chronicle replication
     */
    private abstract class SessionHandler implements Runnable, Closeable {
        private final SocketChannel socketChannel;
        protected final TcpConnection connection;

        protected ExcerptTailer tailer;
        protected ExcerptAppender appender;
        protected long lastHeartbeat;
        private long lastUnPausedNS;

        protected final ByteBuffer writeBuffer;
        protected final ResizableDirectByteBufferBytes readBuffer;

        private ResizableDirectByteBufferBytes withMappedBuffer;

        private SessionHandler(final @NotNull SocketChannel socketChannel) {
            this.socketChannel = socketChannel;
            this.connection = new TcpConnection(socketChannel);
            this.tailer = null;
            this.appender = null;
            this.lastHeartbeat = 0;
            this.lastUnPausedNS = 0;

            this.readBuffer = new ResizableDirectByteBufferBytes(16);
            this.readBuffer.clearThreadAssociation();
            this.writeBuffer = ChronicleTcp.createBuffer(builder.minBufferSize());
            this.writeBuffer.limit(0);

            this.withMappedBuffer = new ResizableDirectByteBufferBytes(1024);
        }

        @Override
        public void close() throws IOException {
            if (this.tailer != null) {
                this.tailer.close();
                this.tailer = null;
            }

            if (this.appender != null) {
                this.appender.close();
                this.appender = null;
            }

            if (this.socketChannel.isOpen()) {
                this.socketChannel.close();
            }
        }

        @Override
        public void run() {
            VanillaSelectionKeySet selectionKeys = null;

            try {
                socketChannel.configureBlocking(false);
                socketChannel.socket().setTcpNoDelay(true);
                socketChannel.socket().setSoTimeout(0);
                socketChannel.socket().setSoLinger(false, 0);

                if(builder.receiveBufferSize() > 0) {
                    socketChannel.socket().setReceiveBufferSize(builder.receiveBufferSize());
                }
                if(builder.sendBufferSize() > 0) {
                    socketChannel.socket().setSendBufferSize(builder.sendBufferSize());
                }

                final VanillaSelector selector = new VanillaSelector()
                        .open()
                        .register(socketChannel, SelectionKey.OP_READ, new Attached());

                tailer   = builder.chronicle().createTailer();
                appender = builder.chronicle().createAppender();

                selectionKeys = selector.vanillaSelectionKeys();

                if (selectionKeys != null) {
                    vanillaNioLoop(selector, selectionKeys);

                } else {
                    nioLoop(selector);
                }
            } catch (EOFException e) {
                if (running.get()) {
                    logger.info("Connection {} died", socketChannel);
                }
            } catch (Exception e) {
                if (running.get()) {
                    String msg = e.getMessage();
                    if (msg != null &&
                            (msg.contains("reset by peer")
                                    || msg.contains("Broken pipe")
                                    || msg.contains("was aborted by"))) {
                        logger.info("Connection {} closed from the other end: ", socketChannel, e.getMessage());

                    } else {
                        logger.info("Connection {} died", socketChannel, e);
                    }
                }
            } finally {
                if (selectionKeys != null) {
                    selectionKeys.clear();
                }
            }

            try {
                close();
            } catch (IOException e) {
                logger.warn("", e);
            }
        }

        private void vanillaNioLoop(final VanillaSelector selector, final VanillaSelectionKeySet selectionKeys) throws IOException {
            final int  spinLoopCount = builder.selectorSpinLoopCount();
            final long selectTimeout = builder.selectTimeout();

            while (running.get()) {
                int nbKeys = selector.select(spinLoopCount, selectTimeout);

                if (nbKeys > 0) {
                    final SelectionKey[] keys = selectionKeys.keys();
                    final int size = selectionKeys.size();

                    for (int k = 0; k < size; k++) {
                        final SelectionKey key = keys[k];
                        if (key != null) {
                            if (!onSelectionKey(key)) {
                                break;
                            }
                        }
                    }

                    selectionKeys.clear();
                }
            }
        }

        private void nioLoop(final VanillaSelector selector) throws IOException {
            final int  spinLoopCount = builder.selectorSpinLoopCount();
            final long selectTimeout = builder.selectTimeout();

            while (running.get()) {
                int nbKeys = selector.select(spinLoopCount, selectTimeout);

                if (nbKeys > 0) {
                    final Set<SelectionKey> keys = selector.selectionKeys();
                    for (final SelectionKey key : keys) {
                        if (!onSelectionKey(key)) {
                            break;
                        }
                    }

                    keys.clear();
                }
            }
        }

        protected boolean hasRoomForExcerpt(ByteBuffer buffer, Bytes tailer) {
            return hasRoomFor(buffer, tailer.remaining() + ChronicleTcp.HEADER_SIZE);
        }

        protected boolean hasRoomFor(ByteBuffer buffer, long size) {
            return buffer.remaining() >= size;
        }

        protected void pauseReset() {
            lastUnPausedNS = System.nanoTime();
            pauser.reset();
        }

        protected void pause() {
            if (lastUnPausedNS + ChronicleTcp.BUSY_WAIT_TIME_NS > System.nanoTime()) {
                return;
            }

            pauser.pause();
        }

        protected void setLastHeartbeat() {
            this.lastHeartbeat = System.currentTimeMillis() + builder.heartbeatIntervalMillis();
        }

        protected void setLastHeartbeat(long from) {
            this.lastHeartbeat = from + builder.heartbeatIntervalMillis();
        }

        protected void sendSizeAndIndex(int size, long index) throws IOException {
            connection.writeSizeAndIndex(writeBuffer, size, index);
            setLastHeartbeat();
        }

        protected DirectByteBufferBytes readUpTo(int size) throws IOException {
            readBuffer.resetToSize(size);
            connection.readFullyOrEOF(readBuffer.buffer());
            readBuffer.buffer().flip();
            readBuffer.position(0);
            readBuffer.limit(readBuffer.limit());

            return readBuffer;
        }

        protected boolean onSelectionKey(final SelectionKey key) throws IOException {
            if (key != null) {
                if (key.isReadable()) {
                    if (!onRead(key)) {
                        return false;
                    }
                } else if (key.isWritable()) {
                    if (!onWrite(key)) {
                        return false;
                    }
                }
            }

            return true;
        }

        protected boolean onRead(final SelectionKey key) throws IOException {
            try {
                final long action = readUpTo(8).readLong();
                switch ((int) action) {
                    case (int) ChronicleTcp.ACTION_WITH_MAPPING:
                        return onMapping(key, readUpTo(4).readInt());
                    case (int) ChronicleTcp.ACTION_SUBSCRIBE:
                        return onSubscribe(key, readUpTo(8).readLong());
                    case (int) ChronicleTcp.ACTION_UNSUBSCRIBE:
                        return onUnsubscribe(key, readUpTo(8).readLong());
                    case (int) ChronicleTcp.ACTION_QUERY:
                        return onQuery(key, readUpTo(8).readLong());
                    case (int) ChronicleTcp.ACTION_SUBMIT:
                        return onSubmit(key, readUpTo(8).readLong(), true);
                    case (int) ChronicleTcp.ACTION_SUBMIT_NOACK:
                        return onSubmit(key, readUpTo(8).readLong(), false);
                    default:
                        throw new IOException("Unknown action received (" + action + ")");
                }
            } catch (IOException e) {
                key.selector().close();
                throw e;
            }
        }
        protected boolean onWrite(final SelectionKey key) throws IOException {
            final long now = System.currentTimeMillis();
            final Object attachment = key.attachment();

            if (running.get() && !write(attachment)) {
                if (lastHeartbeat <= now) {
                    sendSizeAndIndex(ChronicleTcp.IN_SYNC_LEN, ChronicleTcp.IDX_NONE);
                }
            }

            return true;
        }

        protected boolean onMapping(final SelectionKey key, int size) throws IOException {
            MappingProvider mappingProvider = (MappingProvider)key.attachment();
            if (mappingProvider != null) {
                MappingFunction mappingFunction = readUpTo(size).readObject(MappingFunction.class);
                mappingProvider.withMapping(mappingFunction);
            }

            return true;
        }

        protected boolean onQuery(final SelectionKey key, long data) throws IOException {
            if (tailer.index(data)) {
                final long now = System.currentTimeMillis();
                setLastHeartbeat(now);

                while (true) {
                    if (tailer.nextIndex()) {
                        sendSizeAndIndex(ChronicleTcp.SYNC_IDX_LEN, tailer.index());
                        tailer.finish();
                        break;

                    } else {
                        if (lastHeartbeat <= now) {
                            sendSizeAndIndex(ChronicleTcp.IN_SYNC_LEN, ChronicleTcp.IDX_NONE);
                            break;
                        }
                    }
                }
            } else {
                sendSizeAndIndex(ChronicleTcp.IN_SYNC_LEN, 0L);
            }

            return true;
        }

        protected boolean onUnsubscribe(final SelectionKey key, long data) throws IOException {
            key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
            return true;
        }

        protected abstract boolean onSubscribe(final SelectionKey key, long data) throws IOException ;
        protected abstract boolean onSubmit(final SelectionKey key, long size, boolean ack) throws IOException ;
        protected abstract boolean write(Object attachment) throws IOException;

        /**
         * applies a mapping if the mapping is not set to {@code}null{code}
         *
         * @param source the tailer for the mapping to be applied to
         * @param attached the key attachment
         * @return returns the tailer or the mapped bytes
         * @see
         */
        protected Bytes applyMapping(@NotNull final ExcerptTailer source,
                                     @Nullable Object attached) {
            if (attached == null) {
                return source;
            }

            final MappingProvider mappingProvider = (MappingProvider) attached;
            final MappingFunction mappingFunction = mappingProvider.withMapping();
            if (mappingFunction == null) {
                return source;
            }

            withMappedBuffer.clear();
            if (withMappedBuffer.capacity() < source.limit()) {
                withMappedBuffer.resetToSize((int)source.capacity());
            }

            try {
                mappingFunction.apply(source, withMappedBuffer);
            } catch (IllegalArgumentException e) {
                // lets try to resize
                if (e.getMessage().contains("Attempt to write")) {
                    if (withMappedBuffer.capacity() == Integer.MAX_VALUE) {
                        throw e;
                    }

                    withMappedBuffer.resetToSize(
                        Math.min(
                            Integer.MAX_VALUE,
                            (int) (withMappedBuffer.capacity() * 1.5))
                    );

                } else {
                    throw e;
                }
            }

            return withMappedBuffer.flip();
        }
    }

    // *************************************************************************
    // SessionHandler - implementations
    // *************************************************************************

    /**
     * IndexedChronicle session handler
     */
    private class IndexedSessionHandler extends SessionHandler {
        private long index;

        private IndexedSessionHandler(final @NotNull SocketChannel socketChannel) {
            super(socketChannel);
            this.index = -1;
        }

        @Override
        protected boolean onSubscribe(final SelectionKey key, long data) throws IOException {
            this.index = data;
            if (this.index == ChronicleTcp.IDX_TO_START) {
                this.index = -1;

            } else if (this.index == ChronicleTcp.IDX_TO_END) {
                this.index = tailer.toEnd().index();
            }

            sendSizeAndIndex(ChronicleTcp.SYNC_IDX_LEN, this.index);

            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            return true;
        }

        @Override
        protected boolean onSubmit(final SelectionKey key, long size, boolean ack) throws IOException {
            if(ack) {
                sendSizeAndIndex(ChronicleTcp.NACK_LEN, ChronicleTcp.IDX_NOT_SUPPORTED);
            }

            return true;
        }

        @Override
        protected boolean write(Object attached) throws IOException {
            if (!tailer.index(index)) {
                if (tailer.wasPadding()) {
                    if (index >= 0) {
                        sendSizeAndIndex(ChronicleTcp.PADDED_LEN, tailer.index());
                    }

                    index++;
                }

                pause();

                if (running.get() && !tailer.index(index)) {
                    return false;
                }
            }

            pauseReset();

            Bytes bytes = applyMapping(tailer, attached);
            int size = (int)bytes.limit();

            writeBuffer.clear();
            writeBuffer.putInt(size);
            writeBuffer.putLong(tailer.index());

            // for large objects send one at a time.
            if (size > writeBuffer.capacity() / 2) {
                while (size > 0) {
                    int minSize = Math.min(size, writeBuffer.remaining());
                    bytes.read(writeBuffer, minSize);
                    writeBuffer.flip();
                    connection.writeAll(writeBuffer);

                    size -= minSize;
                    if(size > 0) {
                        writeBuffer.clear();
                    }
                }
            } else {
                bytes.read(writeBuffer, size);
                for (int count = builder.maxExcerptsPerMessage(); (count > 0) && tailer.index(index + 1); ) {
                    if (!tailer.wasPadding()) {
                        bytes = applyMapping(tailer, attached);
                        // if there is free space, copy another one.
                        if (hasRoomForExcerpt(writeBuffer, bytes)) {
                            size = (int) bytes.limit();
                            writeBuffer.putInt(size);
                            writeBuffer.putLong(tailer.index());
                            bytes.read(writeBuffer, size);

                            index++;
                            count--;

                            tailer.finish();

                        } else {
                            break;
                        }
                    } else {
                        if(hasRoomFor(writeBuffer, ChronicleTcp.HEADER_SIZE)) {
                            writeBuffer.putInt(ChronicleTcp.PADDED_LEN);
                            writeBuffer.putLong(index);

                        } else {
                            break;
                        }

                        index++;
                    }
                }

                writeBuffer.flip();
                connection.writeAll(writeBuffer);
            }

            if (writeBuffer.remaining() > 0) {
                throw new EOFException("Failed to send index=" + index);
            }

            index++;
            return true;
        }
    }

    /**
     * VanillaChronicle session handler
     */
    private class VanillaSessionHandler extends SessionHandler {
        private boolean nextIndex;
        private long index;

        private VanillaSessionHandler(final @NotNull SocketChannel socketChannel) {
            super(socketChannel);

            this.nextIndex = true;
            this.index = -1;
        }

        @Override
        protected boolean onSubscribe(final SelectionKey key, long data) throws IOException {
            this.index = data;
            if (this.index == ChronicleTcp.IDX_TO_START) {
                this.nextIndex = true;
                this.tailer = tailer.toStart();
                this.index = -1;

            } else if (this.index == ChronicleTcp.IDX_TO_END) {
                this.nextIndex = false;
                this.tailer = tailer.toEnd();
                this.index = tailer.index();

                if (this.index == -1) {
                    this.nextIndex = true;
                    this.tailer = tailer.toStart();
                    this.index = -1;
                }
            } else {
                this.nextIndex = false;
            }

            sendSizeAndIndex(ChronicleTcp.SYNC_IDX_LEN, this.index);

            key.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
            return false;
        }

        @Override
        protected boolean onSubmit(final SelectionKey key, long size, boolean ack) throws IOException {
            readUpTo((int) size);

            appender.startExcerpt((int) size);
            appender.write(readBuffer);
            appender.finish();

            pauser.unpause();

            if(ack) {
                sendSizeAndIndex(ChronicleTcp.ACK_LEN, appender.lastWrittenIndex());
            }

            return true;
        }

        @Override
        protected boolean write(Object attached) throws IOException {
            if (nextIndex) {
                if (!tailer.nextIndex()) {
                    pause();
                    if (running.get() && !tailer.nextIndex()) {
                        return false;
                    }
                }
            } else {
                if (!tailer.index(this.index)) {
                    return false;

                } else {
                    this.nextIndex = true;
                }
            }

            pauseReset();

            Bytes bytes = applyMapping(tailer, attached);
            int size = (int)bytes.limit();

            writeBuffer.clear();
            writeBuffer.putInt(size);
            writeBuffer.putLong(tailer.index());

            // for large objects send one at a time.
            if (size > writeBuffer.limit() / 2) {
                while (size > 0) {
                    int minSize = Math.min(size, writeBuffer.remaining());
                    bytes.read(writeBuffer, size);
                    writeBuffer.flip();
                    connection.writeAll(writeBuffer);
                    writeBuffer.clear();

                    size -= minSize;
                    if(size > 0) {
                        writeBuffer.clear();
                    }
                }
            } else {
                bytes.read(writeBuffer, size);

                long previousIndex = tailer.index();
                long currentIndex = previousIndex;
                for (int count = builder.maxExcerptsPerMessage(); (count > 0) && tailer.nextIndex(); ) {
                    currentIndex = tailer.index();
                    bytes = applyMapping(tailer, attached);

                    // if there is free space, copy another one.
                    if (hasRoomForExcerpt(writeBuffer, bytes)) {
                        size = (int)bytes.limit();
                        previousIndex = currentIndex;
                        writeBuffer.putInt(size);
                        writeBuffer.putLong(currentIndex);

                        bytes.read(writeBuffer, size);
                        count--;

                        tailer.finish();

                    } else {
                        tailer.finish();
                        // if there is no space, go back to the previous index
                        tailer.index(previousIndex);
                        break;
                    }
                }

                writeBuffer.flip();
                connection.writeAll(writeBuffer);
            }

            if (writeBuffer.remaining() > 0) {
                throw new EOFException("Failed to send index=" + tailer.index());
            }

            return true;
        }
    }
}


text:
(function($){
  'use strict';

  $.fn.ftTransitionWith = function(opts){
    opts = opts || {};

    var $this = $(this),
        deferred = $.Deferred(),
        endEvent = opts.endEvent,
        addClass = opts.addClass,
        removeClass = opts.removeClass,
        dataAttr = opts.dataAttr,
        callback = opts.callback,
        existing = $this.data('ftTransitionWith'),
        transitionClass;

    if(existing) {
      existing.reject('Initiated another ftTransitionWith');
    }

    transitionClass = $this.data(dataAttr);

    if(transitionClass){
      $this.addClass(transitionClass + ' ' + addClass)
           .waitForAnimation()
           .then(function(){
             if(deferred.state() !== 'rejected'){
               $this.removeClass(transitionClass);
               if(addClass)    { $this.addClass(addClass); }
               if(removeClass) { $this.removeClass(removeClass); }
               if(endEvent)    { $this.trigger(endEvent); }
               deferred.resolveWith($this);
             }
           });

      deferred.fail(function(){
        $this.removeClass(transitionClass);
      });

    } else {

      // 1ms timeout so we can keep the promise interface
      setTimeout(function(){
        if(deferred.state() !== 'rejected'){
          if(addClass)    { $this.addClass(addClass); }
          if(removeClass) { $this.removeClass(removeClass); }
          if(endEvent)    { $this.trigger(endEvent); }
          deferred.resolveWith($this);
        }
      }, 1);
    }

    $this.data('ftTransitionWith', deferred);
    return deferred.promise();
  };

})(jQuery);


text:
module.exports = {
  bulletsBar: require('./bulletsBar'),
  flowControl: require('./flowControl'),
  iconBar: require('./iconBar'),
  selectionBar: require('./selectionBar')
}


text:
from __future__ import absolute_import, unicode_literals
from google.appengine.api import users
from config.template_middleware import TemplateResponse
from gaecookie.decorator import no_csrf
from gaepermission import facade
from gaepermission.decorator import login_not_required
from tekton import router
from tekton.gae.middleware.redirect import RedirectResponse
import settings
from routes.login import pending

@login_not_required
@no_csrf
def index(_resp, ret_path='/'):
    user = users.get_current_user()
    if user:
        cmd = facade.login_google(user, _resp).execute()
        if cmd.pending_link:
            pending_path = router.to_path(pending.index, cmd.pending_link.key.id())
            facade.send_passwordless_login_link(user.email(),
                                                settings.APP_URL + pending_path).execute()
            return TemplateResponse({'provider': 'Google', 'email': user.email()}, 'login/pending.html')
    return RedirectResponse(ret_path)


text:
package org.gradle.api.internal;

import org.gradle.api.Action;
import org.gradle.api.Task;
import org.gradle.api.internal.tasks.ContextAwareTaskAction;
import org.gradle.api.internal.tasks.TaskExecuter;
import org.gradle.api.internal.tasks.TaskStateInternal;
import org.gradle.api.internal.tasks.execution.TaskValidator;
import org.gradle.api.specs.Spec;
import org.gradle.api.tasks.Internal;
import org.gradle.internal.Factory;
import org.gradle.logging.StandardOutputCapture;
import org.gradle.util.Configurable;
import org.gradle.util.Path;

import java.io.File;
import java.util.List;

public interface TaskInternal extends Task, Configurable<Task> {

    /**
     * A more efficient version of {@link #getActions()}, which circumvents the
     * validating change listener that normally prevents users from changing tasks
     * once they start executing.
     */
    @Internal
    List<ContextAwareTaskAction> getTaskActions();

    @Internal
    Spec<? super TaskInternal> getOnlyIf();

    @Deprecated
    void execute();

    @Internal
    @SuppressWarnings("deprecation")
    StandardOutputCapture getStandardOutputCapture();

    @Deprecated
    @Internal
    TaskExecuter getExecuter();

    @Deprecated
    void setExecuter(TaskExecuter executer);

    @Override
    TaskInputsInternal getInputs();

    @Override
    TaskOutputsInternal getOutputs();

    @Deprecated
    @Internal
    List<TaskValidator> getValidators();

    @Deprecated
    void addValidator(TaskValidator validator);

    @Override
    TaskStateInternal getState();

    @Internal
    boolean getImpliesSubProjects();

    void setImpliesSubProjects(boolean impliesSubProjects);

    /**
     * The returned factory is expected to return the same file each time.
     * <p>
     * The getTemporaryDir() method creates the directory which can be problematic. Use this to delay that creation.
     */
    @Internal
    Factory<File> getTemporaryDirFactory();

    void prependParallelSafeAction(Action<? super Task> action);

    void appendParallelSafeAction(Action<? super Task> action);

    @Internal
    boolean isHasCustomActions();

    @Internal
    Path getIdentityPath();
}


text:
#ifndef _QCAR_SMARTTERRAIN_BUILDER_H_
#define _QCAR_SMARTTERRAIN_BUILDER_H_

// Include files
#include "Tracker.h"
#include "Trackable.h"
#include "Vectors.h"
#include "Reconstruction.h"

namespace QCAR
{

/// SmartTerrainBuilder class
/**
 *  The SmartTerrainBuilder controls the smart terrain generation system of Vuforia.
 *  If the SmartTerrainTracker is enabled and the builder is initialized.
 *  SmartTerrainTrackables (Surface, Prop) will be generated once an appropriate
 *  Reconstruction object is registered.
 */
class QCAR_API SmartTerrainBuilder : private NonCopyable
{
public:

    /// Returns the Tracker class' type
    static Type getClassType();

    /// Returns the Trackable instance's type
    virtual Type getType() const = 0;

    /// Checks whether the builder instance's type equals or has been
    /// derived from a give type
    virtual bool isOfType(Type type) const = 0;

    // Factory method for creating an instance of a reconstruction
    /*
     * Valid types are ReconstructionFromEnvironment and ReconstructionFromTarget.
     * Passing in any other type will cause NULL to be returned.
     */
    virtual Reconstruction* createReconstruction(Type type) = 0;

    /// Method for cleaning up a previously created reconstruction object
    virtual bool destroyReconstruction(Reconstruction* reco) = 0;

    /// Returns the number of reconstructions registered with the builder.
    virtual unsigned int getNumReconstructions() const = 0;

    /// Adds a reconstruction to the builder and starts it.
    virtual bool addReconstruction(Reconstruction* obj) = 0;

    /// Removes a reconstruction from the builder and cleans up any generated
    /// trackables as well.
    virtual bool removeReconstruction(unsigned int index) = 0;

    /// Gets the reconstruction at the given index.
    virtual Reconstruction* getReconstruction(unsigned int index) const = 0;

    /// Initializes the builder, returning true if able to.
    virtual bool init() = 0;

    /// Deinitializes the builder, return true if able to do so.
    virtual bool deinit() = 0;
};

} // namespace QCAR

#endif //_QCAR_SMARTTERRAIN_BUILDER_H_


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2015 Square, Inc.
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->
<resources>
  <string name="app_name">LeakCanary Sample</string>
  <string name="start_async_task">Start new AsyncTask</string>
  <string name="helper_text">Start the async task, <b>rotate the screen</b> and wait for a bit. A
    wild notification appears.
  </string>
  <string name="__leak_canary_display_activity_label">Leaks Sample</string>
</resources>


text:
<?php

phutil_register_library('phpstan', __FILE__);


text:
import {
    graphql,
    GraphQLSchema,
    GraphQLObjectType,
    GraphQLString
} from 'graphql';

export const schema = new GraphQLSchema({
    query: new GraphQLObjectType({
        name: 'RootQueryType',
        fields: {
            hello: {
                type: GraphQLString,
                resolve() {
                    return 'world';
                }
            }
        }
    })
});


text:
const expect = require('unexpected');
const td = require('testdouble');
require('../../lib')(td);

describe('td.verifyOnce', () => {

  /** **************************************************************************
   */
  it('works as expected when the call was made', () => {
    const fn = td.function();
    td.when(fn(td.matchers.anything())).thenReturn('yay');

    fn('something');

    td.verifyOnce(fn('something'));
  });

  /** **************************************************************************
   */
  it('throws as normal when call was not made', () => {
    const fn = td.function();
    td.when(fn(td.matchers.anything())).thenReturn('yay');

    fn('something else');

    try {
      td.verifyOnce(fn('something'));
    } catch (err) {
      expect(err.message, 'to begin with', 'Unsatisfied verification on test double.\n\n');
    }
  });
});


text:
"""
Test the default styles, to guarantee consistency.
"""

from sqlobject import *
from sqlobject.tests.dbtest import *
from sqlobject.styles import Style, MixedCaseUnderscoreStyle, MixedCaseStyle

#hash of styles versus the database names resulting from 'columns' below
columns = ["ABCUpper", "abc_lower", "ABCamelCaseColumn"]
styles = {Style:columns,
          MixedCaseUnderscoreStyle:["abc_upper", "abc_lower", "ab_camel_case_column"],
          MixedCaseStyle:["ABCUpper", "Abc_lower", "ABCamelCaseColumn"],
        }

#hash of styles versus the database names resulting from a foreign key named 'FKey'
fkey = ForeignKey("DefaultStyleTest", name="FKey")
fkeys = {Style:"FKeyID",
          MixedCaseUnderscoreStyle:"f_key_id",
          MixedCaseStyle:"FKeyID",
        }

def make_columns():
    global columns
    columns = []
    for col_name in columns:
        columns.append(StringCol(name=col_name, length=10))

def do_col_test(DefaultStyleTest, style, dbnames):
    DefaultStyleTest.sqlmeta.style = style()
    for col, old_dbname in zip(columns, dbnames):
        DefaultStyleTest.sqlmeta.addColumn(col)
        try:
            new_dbname = DefaultStyleTest.sqlmeta.columns[col.name].dbName
            assert new_dbname == old_dbname
        finally:
            if col.name in DefaultStyleTest.sqlmeta.columns:
                DefaultStyleTest.sqlmeta.delColumn(col)

def do_fkey_test(DefaultStyleTest, style, dbname):
    DefaultStyleTest.sqlmeta.style = style()
    DefaultStyleTest.sqlmeta.addColumn(fkey)
    try:
        assert DefaultStyleTest.sqlmeta.columns.keys()[0] == "FKeyID"
        assert DefaultStyleTest.sqlmeta.columns.values()[0].dbName == dbname
    finally:
        DefaultStyleTest.sqlmeta.delColumn(fkey)

class DefaultStyleTest(SQLObject):
    pass

def test_default_styles():
    make_columns()
    for style in styles:
        yield do_col_test, DefaultStyleTest, style, styles[style]
        yield do_fkey_test, DefaultStyleTest, style, fkeys[style]


text: This is file A.


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
	<string name="app_name">Ft App</string>
  <string name="app_version">Version 1.2.2</string>

  <string name="AboutActivity_developedBy">Entwickelt von Bennik2000</string>
  <string name="AboutActivity_moreInformation">Den Quellcode und weitere Informationen gibt es hier: GitHub</string>

  <string name="SelectDeviceActivity_toolbarTitle">FtApp</string>
  <string name="SelectDeviceActivity_connectToTxtController">Mit dem ROBOTICS TXT Controller verbinden</string>
  <string name="SelectDeviceActivity_ipaddress_Hint">Ip addresse</string>
  <string name="SelectDeviceActivity_wifi">WLAN</string>
  <string name="SelectDeviceActivity_bluetooth">Bluetooth</string>
  <string name="SelectDeviceActivity_custom">Andere Ip</string>
  <string name="SelectDeviceActivity_connect">Verbinden</string>
  <string name="SelectDeviceActivity_notValidIp">"%1$s" Ist keine gültige Ip addresse</string>
  <string name="SelectDeviceActivity_noIp">Keine Ip addresse ist abgegeben</string>
  <string name="SelectDeviceActivity_notInterfaceFound">Kein fischertechnik Interface wurde gefunden</string>

  <string name="SelectDeviceActivity_bluetoothHasToBeEnabled">Bluetooth muss aktiviert sein um nach TX Controllern zu suchen!</string>
  <string name="SelectDeviceActivity_noBluetooth">Dieses Gerät hat kein Bluetooth</string>

  <string name="SelectDeviceOptionsMenu_simulate">Simulieren</string>
  <string name="SelectDeviceOptionsMenu_about">Über</string>
  <string name="SelectDeviceOptionsMenu_help">Hilfe</string>

  <string name="ControlInterfaceActivity_toolbarTitle">ROBOTICS TXT Controller</string>

  <string name="ControlInterfaceActivity_simulatedInterfaceName">Simuliertes Interface</string>

  <string name="ControlInterfaceActivity_tabStatusTitle">Status</string>
  <string name="ControlInterfaceActivity_tabInputTitle">Eingänge</string>
  <string name="ControlInterfaceActivity_tabOutputTitle">Ausgänge</string>
  <string name="ControlInterfaceActivity_tabCameraTitle">Kamera</string>

  <string name="ControlInterfaceActivity_interfaceNotAvaliableTitle">Interface ist nicht verfügbar</string>
  <string name="ControlInterfaceActivity_interfaceNotAvaliable">Das Interface ist nich verfügbar. Bitte überprüfe die Verbindung</string>
  <string name="ControlInterfaceActivity_interfaceNotAvaliablePositive">Ok</string>

  <string name="ControlInterfaceActivity_interfaceConnecting">Verbinden...</string>
  <string name="ControlInterfaceActivity_interfaceConnectingTitle">Bitte warten...</string>

  <string name="ControlInterfaceActivity_interfaceDisconnecting">Verbindung trennen...</string>
  <string name="ControlInterfaceActivity_interfaceDisconnectingTitle">Bitte warten...</string>

  <string name="ControlInterfaceActivity_interfaceConnectionLostMessage">Die Verbindung zum Interface wurde unterbrochen</string>
  <string name="ControlInterfaceActivity_interfaceConnectionLostTitle">Verbindung underbrochen</string>
  <string name="ControlInterfaceActivity_interfaceConnectionLostPositive">Ok</string>

  <string name="ControlInterfaceActivity_inputDigitalOne">Gedrückt</string>
  <string name="ControlInterfaceActivity_inputDigitalZero">Nicht gedrückt</string>

  <string name="ControlInterfaceActivity_inputDigitalTrail">Spur</string>
  <string name="ControlInterfaceActivity_inputDigitalNoTrail">Keine Spur</string>

  <string name="ControlInterfaceActivity_inputModeSwitch">Taster</string>
  <string name="ControlInterfaceActivity_inputModeNtc">NTC</string>
  <string name="ControlInterfaceActivity_inputModeTrailSensor">Spursensor</string>
  <string name="ControlInterfaceActivity_inputModeUltrasonic">Ultraschallsensor</string>
  <string name="ControlInterfaceActivity_inputModeDigitalR">Digital 5kΩ</string>
  <string name="ControlInterfaceActivity_inputModeAnalogR">Analog 5kΩ</string>
  <string name="ControlInterfaceActivity_inputModeDigitalU">Digital 10V</string>
  <string name="ControlInterfaceActivity_inputModeAnalogU">Analog 10V</string>

  <string name="ControlInterfaceActivity_outputModeMotor">Motor</string>
  <string name="ControlInterfaceActivity_outputModeOutuput">Einzelne Ausgänge</string>

  <string name="ControlInterfaceActivity_pictureTakenToast">Bild gespeichert!</string>
  <string name="ControlInterfaceActivity_noCamera">Kamera ist nicht verfügbar</string>

  <string name="ControlInterfaceActivity_joystickModeSingle">Einzelner Motor</string>
  <string name="ControlInterfaceActivity_joystickModeSyncron">Syncron</string>

  <string name="ControlInterfaceActivity_configureJoystickOptionsMenuMode">Modus</string>
  <string name="ControlInterfaceActivity_configureJoystickOptionsMenuMotors">Motoren</string>

  <string name="ControlInterfaceActivity_configureJoystickModeDialogTitle">Joystick Modus</string>
  <string name="ControlInterfaceActivity_configureJoystickModeDialogPositive">Ok</string>

  <string name="ControlInterfaceActivity_configureJoystickMotor1DialogTitle">Motor 1</string>
  <string name="ControlInterfaceActivity_configureJoystickMotor1DialogPositive">Ok</string>

  <string name="ControlInterfaceActivity_configureJoystickMotor2DialogTitle">Motor 2</string>

  <string name="ControlInterfaceOptionsMenu_joystick">Joystick</string>

  <string name="RateReminderDialog_title">FtApp Bewerten</string>
  <string name="RateReminderDialog_message">Wenn dir diese App gefällt, nimm dir einen Moment Zeit und bewerte sie.</string>
  <string name="RateReminderDialog_positive">Bewerten</string>
  <string name="RateReminderDialog_neutral">Später</string>
  <string name="RateReminderDialog_negative">Nein, danke!</string>

  <string name="RateReminderDialog_doNotShowAgainKey">DoNotShowAgain</string>
  <string name="RateReminderDialog_launchCountKey">LaunchCount</string>
</resources>


text:
/*
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

#pragma once

#include "rplidar_protocol.h"

// Commands
//-----------------------------------------

// Commands without payload and response
#define RPLIDAR_CMD_STOP               0x25
#define RPLIDAR_CMD_SCAN               0x20
#define RPLIDAR_CMD_FORCE_SCAN         0x21
#define RPLIDAR_CMD_RESET              0x40

// Commands without payload but have response
#define RPLIDAR_CMD_GET_DEVICE_INFO    0x50
#define RPLIDAR_CMD_GET_DEVICE_HEALTH  0x52

#define RPLIDAR_CMD_GET_SAMPLERATE     0x59 //added in fw 1.17

// Commands with payload and have response
#define RPLIDAR_CMD_EXPRESS_SCAN       0x82 //added in fw 1.17

//add for A2 to set RPLIDAR motor pwm when using accessory board
#define RPLIDAR_CMD_SET_MOTOR_PWM      0xF0
#define RPLIDAR_CMD_GET_ACC_BOARD_FLAG 0xFF

#if defined(_WIN32)
#pragma pack(1)
#endif

// Payloads
// ------------------------------------------
#define RPLIDAR_EXPRESS_SCAN_MODE_NORMAL      0
#define RPLIDAR_EXPRESS_SCAN_MODE_FIXANGLE    1
typedef struct _rplidar_payload_express_scan_t {
    _u8   working_mode;
    _u32  reserved;
} __attribute__((packed)) rplidar_payload_express_scan_t;

#define MAX_MOTOR_PWM               1023
#define DEFAULT_MOTOR_PWM           660
typedef struct _rplidar_payload_motor_pwm_t {
    _u16 pwm_value;
} __attribute__((packed)) rplidar_payload_motor_pwm_t;

typedef struct _rplidar_payload_acc_board_flag_t {
    _u32 reserved;
} __attribute__((packed)) rplidar_payload_acc_board_flag_t;

// Response
// ------------------------------------------
#define RPLIDAR_ANS_TYPE_DEVINFO          0x4
#define RPLIDAR_ANS_TYPE_DEVHEALTH        0x6

#define RPLIDAR_ANS_TYPE_MEASUREMENT                0x81
// Added in FW ver 1.17
#define RPLIDAR_ANS_TYPE_MEASUREMENT_CAPSULED       0x82

// Added in FW ver 1.17
#define RPLIDAR_ANS_TYPE_SAMPLE_RATE      0x15

#define RPLIDAR_ANS_TYPE_ACC_BOARD_FLAG   0xFF

#define RPLIDAR_RESP_ACC_BOARD_FLAG_MOTOR_CTRL_SUPPORT_MASK      (0x1)
typedef struct _rplidar_response_acc_board_flag_t {
    _u32 support_flag;
} __attribute__((packed)) rplidar_response_acc_board_flag_t;

#define RPLIDAR_STATUS_OK                 0x0
#define RPLIDAR_STATUS_WARNING            0x1
#define RPLIDAR_STATUS_ERROR              0x2

#define RPLIDAR_RESP_MEASUREMENT_SYNCBIT        (0x1<<0)
#define RPLIDAR_RESP_MEASUREMENT_QUALITY_SHIFT  2
#define RPLIDAR_RESP_MEASUREMENT_CHECKBIT       (0x1<<0)
#define RPLIDAR_RESP_MEASUREMENT_ANGLE_SHIFT    1

typedef struct _rplidar_response_sample_rate_t {
    _u16  std_sample_duration_us;
    _u16  express_sample_duration_us;
} __attribute__((packed)) rplidar_response_sample_rate_t;

typedef struct _rplidar_response_measurement_node_t {
    _u8    sync_quality;      // syncbit:1;syncbit_inverse:1;quality:6;
    _u16   angle_q6_checkbit; // check_bit:1;angle_q6:15;
    _u16   distance_q2;
} __attribute__((packed)) rplidar_response_measurement_node_t;

//[distance_sync flags]
#define RPLIDAR_RESP_MEASUREMENT_EXP_ANGLE_MASK           (0x3)
#define RPLIDAR_RESP_MEASUREMENT_EXP_DISTANCE_MASK        (0xFC)

typedef struct _rplidar_response_cabin_nodes_t {
    _u16   distance_angle_1; // see [distance_sync flags]
    _u16   distance_angle_2; // see [distance_sync flags]
    _u8    offset_angles_q3;
} __attribute__((packed)) rplidar_response_cabin_nodes_t;

#define RPLIDAR_RESP_MEASUREMENT_EXP_SYNC_1               0xA
#define RPLIDAR_RESP_MEASUREMENT_EXP_SYNC_2               0x5

#define RPLIDAR_RESP_MEASUREMENT_EXP_SYNCBIT              (0x1<<15)

typedef struct _rplidar_response_capsule_measurement_nodes_t {
    _u8                             s_checksum_1; // see [s_checksum_1]
    _u8                             s_checksum_2; // see [s_checksum_1]
    _u16                            start_angle_sync_q6;
    rplidar_response_cabin_nodes_t  cabins[16];
} __attribute__((packed)) rplidar_response_capsule_measurement_nodes_t;

typedef struct _rplidar_response_device_info_t {
    _u8   model;
    _u16  firmware_version;
    _u8   hardware_version;
    _u8   serialnum[16];
} __attribute__((packed)) rplidar_response_device_info_t;

typedef struct _rplidar_response_device_health_t {
    _u8   status;
    _u16  error_code;
} __attribute__((packed)) rplidar_response_device_health_t;

#if defined(_WIN32)
#pragma pack()
#endif