text:
import os
import cv2
import math
import time
import shutil
import imghdr
import numpy as np
import tensorflow as tf
from tensorflow.python.platform import gfile

from Util.ProgressBar import ProgressBar

class Config:
    n_class = 19
    extractors_path = "Models/Extractors/"
    predictors_path = "Models/Predictors/"
    image_paths = ["sources/{:04d}".format(i) for i in range(n_class)]

    @staticmethod
    def get_image_paths():
        new_paths = []
        for i, path in enumerate(Config.image_paths):
            files = [path + "/" + file for file in os.listdir(path)]
            new_paths += files
        return new_paths

    @staticmethod
    def get_labels():
        labels = []
        for i in range(Config.n_class):
            labels += [[0 if j != i else 1 for j in range(
                Config.n_class)] for _ in range(len(os.listdir("sources/{:04d}".format(i))))]
        np.save("sources/labels", labels)

    @staticmethod
    def shuffle(folder):
        _features = np.load(folder + "/features.npy")
        _labels = np.load(folder + "/labels.npy")
        _indices = np.random.permutation(len(_features))
        _features, _labels = _features[_indices], _labels[_indices]
        np.save(folder + "/features", _features)
        np.save(folder + "/labels", _labels)

    @staticmethod
    def split(folder):
        _features = np.load(folder + "/features.npy")
        _labels = np.load(folder + "/labels.npy")
        _indices = np.random.permutation(len(_features))
        _features, _labels = _features[_indices], _labels[_indices]
        train_len = int(0.9 * len(_features))
        x_train, x_test = _features[:train_len], _features[train_len:]
        y_train, y_test = _labels[:train_len], _labels[train_len:]
        np.save(folder + "/x_train", x_train)
        np.save(folder + "/x_test", x_test)
        np.save(folder + "/y_train", y_train)
        np.save(folder + "/y_test", y_test)

class Extractor:
    def __init__(self, extractor="v3", image_paths=None, labels=None, mat_dir=None):
        self._extractor = extractor if "v3" not in extractor else "v3"
        self._image_paths = Config.get_image_paths() if image_paths is None else image_paths
        self._labels, self._mat_dir = labels, mat_dir

    def _create_graph(self):
        tf.reset_default_graph()
        with gfile.FastGFile(Config.extractors_path+self._extractor+"/Model.pb", "rb") as file:
            graph_def = tf.GraphDef()
            graph_def.ParseFromString(file.read())
            if "cnn" in self._extractor:
                # Fix nodes
                for node in graph_def.node:
                    if node.op == 'RefSwitch':
                        node.op = 'Switch'
                        for index in range(len(node.input)):
                            if 'moving_' in node.input[index]:
                                node.input[index] += '/read'
                    elif node.op == 'Assign':
                        node.op = 'Sub'
                        if 'use_locking' in node.attr:
                            del node.attr['use_locking']
            tf.import_graph_def(graph_def, name="")

    def _extract(self, verbose):
        features = []
        with tf.Session() as sess:
            if self._extractor == "v3":
                _output = "pool_3:0"
            elif self._extractor == "ResNet-v2":
                _output = "InceptionResnetV2/Logits/Flatten/Reshape:0"
            elif self._extractor == "cnn":
                _output = "final_result/Reshape:0"
            else:
                _output = "OutputFlow/Reshape:0"
            flattened_tensor = sess.graph.get_tensor_by_name(_output)
            if self._extractor == "v3":
                _entry = "DecodeJpeg/contents:0"
            elif self._extractor == "ResNet-v2":
                _entry = "Placeholder:0"
            else:
                _entry = "Entry/Placeholder:0"
            pop_lst = []
            if "cnn" in self._extractor or "ResNet" in self._extractor and self._mat_dir is not None:
                features = np.load(self._mat_dir)
            else:
                def process(img_path):
                    img_data = gfile.FastGFile(img_path, "rb").read()
                    feature = sess.run(flattened_tensor, {
                        _entry: img_data
                    })
                    features.append(np.squeeze(feature))
                for i, image_path in enumerate(self._image_paths):
                    if not os.path.isfile(image_path):
                        continue
                    if "v3" in self._extractor:
                        if verbose:
                            print("Processing {}...".format(image_path))
                        try:
                            process(image_path)
                        except Exception as err:
                            if verbose:
                                print(err)
                            name, extension = os.path.splitext(image_path)
                            base = os.path.basename(image_path)
                            if extension.lower() in (".jpg", ".jpeg"):
                                new_name = name[:image_path.rfind(base)] + "{:06d}{}".format(i, extension)
                                print("Renaming {} to {}...".format(image_path, new_name))
                                os.rename(image_path, new_name)
                                process(new_name)
                            else:
                                new_name_base = name[:image_path.rfind(base)] + "{:06d}".format(i)
                                new_name = new_name_base + ".jpg"
                                print("Transforming {} to {}...".format(image_path, new_name))
                                try:
                                    if imghdr.what(image_path) is None:
                                        raise ValueError("{} is not an image".format(image_path))
                                    os.rename(image_path, new_name_base + extension)
                                    cv2.imwrite(new_name, cv2.imread(new_name_base + extension))
                                    os.remove(new_name_base + extension)
                                    process(new_name)
                                except Exception as err:
                                    print(err)
                                    print("Moving {} to '_err' folder...".format(image_path))
                                    if not os.path.isdir("_err"):
                                        os.makedirs("_err")
                                    shutil.move(image_path, os.path.join("_err", os.path.basename(image_path)))
                                    pop_lst.append(i)
                    else:
                        if verbose:
                            print("Reading {}...".format(image_path))
                        image_data = cv2.imread(image_path)
                        if self._extractor == "ResNet-v2":
                            features.append(cv2.resize(image_data, (299, 299)))
                        else:
                            features.append(cv2.resize(image_data, (64, 64)))
            if "v3" not in self._extractor:
                features = np.array(features)
                print("Extracting features...")
                rs = []
                batch_size = math.floor(1e6 / np.prod(features.shape[1:]))
                epoch = int(math.ceil(len(features) / batch_size))
                bar = ProgressBar(max_value=epoch, name="Extract")
                for i in range(epoch):
                    if i == epoch - 1:
                        rs.append(sess.run(flattened_tensor, {
                            _entry: features[i*batch_size:]
                        }))
                    else:
                        rs.append(sess.run(flattened_tensor, {
                            _entry: features[i*batch_size:(i+1)*batch_size]
                        }))
                    bar.update()
                return np.vstack(rs).astype(np.float32)
            if pop_lst:
                labels = []
                pop_cursor, pop_idx = 0, pop_lst[0]
                for i, label in enumerate(self._labels):
                    if i == pop_idx:
                        pop_cursor += 1
                        if pop_cursor < len(pop_lst):
                            pop_idx = pop_lst[pop_cursor]
                        else:
                            pop_idx = -1
                        continue
                    labels.append(label)
                labels = np.array(labels, dtype=np.float32)
            elif self._labels is None:
                labels = None
            else:
                labels = np.array(self._labels, dtype=np.float32)
            return np.array(features, dtype=np.float32), labels

    def run(self, verbose=True):
        self._create_graph()
        return self._extract(verbose)

class Predictor:
    def __init__(self, predictor="v3"):
        self._predictor = predictor
        self._entry, self._output = "Entry/Placeholder:0", "OutputFlow/add_9:0"

    def _create_graph(self):
        tf.reset_default_graph()
        with gfile.FastGFile(Config.predictors_path+self._predictor+"/Model.pb", "rb") as file:
            graph_def = tf.GraphDef()
            graph_def.ParseFromString(file.read())
            if "cnn" in self._predictor:
                # Fix nodes
                for node in graph_def.node:
                    if node.op == 'RefSwitch':
                        node.op = 'Switch'
                        for index in range(len(node.input)):
                            if 'moving_' in node.input[index]:
                                node.input[index] += '/read'
                    elif node.op == 'Assign':
                        node.op = 'Sub'
                        if 'use_locking' in node.attr:
                            del node.attr['use_locking']
            tf.import_graph_def(graph_def, name="")

    def predict(self, x):
        self._create_graph()
        x, rs = np.atleast_2d(x).astype(np.float32), []
        with tf.Session() as sess:
            flattened_tensor = sess.graph.get_tensor_by_name(self._output)
            print("Predicting...")
            batch_size = math.floor(1e6 / np.prod(x.shape[1:]))
            epoch = math.ceil(len(x) / batch_size)  # type: int
            bar = ProgressBar(max_value=epoch, name="Predict")
            for i in range(epoch):
                if i == epoch - 1:
                    rs.append(sess.run(flattened_tensor, {
                        self._entry: x[i*batch_size:]
                    }))
                else:
                    rs.append(sess.run(flattened_tensor, {
                        self._entry: x[i*batch_size:(i+1)*batch_size]
                    }))
                bar.update()
            return np.vstack(rs).astype(np.float32)

class Pipeline:
    shape = (1440, 576)

    def __init__(self):
        self._image_paths = []
        self._img_dir = self._rs_dir = None

        self._n_row = self._n_col = None
        self._results = []
        self._ans = self._pred = self._prob = None

    @staticmethod
    def get_image_paths(img_dir, pre_process=False):
        image_paths = [img_dir + "/" + file for file in os.listdir(img_dir)]
        if not pre_process:
            return [img for img in image_paths if os.path.isfile(img)]
        return [img for img in image_paths if os.path.isfile(img) and imghdr.what(img) is not None]

    def _get_results(self, ans, img_dir=None, rs_dir=None):
        if img_dir is None:
            img_dir = self._img_dir
        if rs_dir is None:
            rs_dir = self._rs_dir
        y_pred = np.exp(np.load(rs_dir + "/prediction.npy"))
        y_pred /= np.sum(y_pred, axis=1, keepdims=True)
        pred_classes = np.argmax(y_pred, axis=1)
        if ans is not None:
            true_classes = np.argmax(ans, axis=1)
            true_prob = y_pred[range(len(y_pred)), true_classes]
        else:
            true_classes = None
            true_prob = y_pred[range(len(y_pred)), pred_classes]
        self._ans, self._pred, self._prob = true_classes, pred_classes, true_prob
        images = []
        c_base = 60
        for i, img in enumerate(Pipeline.get_image_paths(img_dir, True)):
            _pred = y_pred[i]
            _indices = np.argsort(_pred)[-3:][::-1]
            label_dic = np.load(os.path.join("_Data", "_Cache", "LABEL_DIC.npy"))
            _ps, _labels = _pred[_indices], label_dic[_indices]
            _img = cv2.imread(img)
            if true_classes is None:
                color = np.array([255, 255, 255], dtype=np.uint8)
            else:
                _p = _ps[0]
                if _p <= 1 / 2:
                    _l, _r = 2 * c_base + (255 - 2 * c_base) * 2 * _p, c_base + (255 - c_base) * 2 * _p
                else:
                    _l, _r = 255, 510 * (1 - _p)
                if true_classes[i] == pred_classes[i]:
                    color = np.array([0, _l, _r], dtype=np.uint8)
                else:
                    color = np.array([0, _r, _l], dtype=np.uint8)
            canvas = np.zeros((256, 640, 3), dtype=np.uint8)
            _img = cv2.resize(_img, (256, 256))
            canvas[:, :256] = _img
            canvas[:, 256:] = color
            bar_len = 180
            for j, (_p, _label) in enumerate(zip(_ps, _labels)):
                cv2.putText(canvas, _label, (288, 64 + 64 * j), cv2.LINE_AA, 0.6, (0, 0, 0), 1)
                cv2.rectangle(canvas, (420, 49 + 64 * j), (420 + int(bar_len * _p), 69 + 64 * j), (125, 0, 125), -1)
            images.append(canvas)
        return images

    def _get_detail(self, event, x, y, *_):
        label_dic = np.load(os.path.join("_Data", "_Cache", "LABEL_DIC.npy"))
        if event == cv2.EVENT_LBUTTONDBLCLK:
            _w, _h = Pipeline.shape
            _pw, _ph = _w / self._n_col, _h / self._n_row
            _idx = int(x // _pw + self._n_col * (y // _ph))
            _prob = self._prob[_idx]
            if self._ans is None or self._ans[_idx] == self._pred[_idx]:
                title = "Detail (prob: {:6.4})".format(_prob)
            else:
                title = "True label: {} (prob: {:6.4})".format(
                    label_dic[self._ans[_idx]], _prob)
            while 1:
                cv2.imshow(title, self._results[_idx])
                if cv2.waitKey(20) & 0xFF == 27:
                    break
            cv2.destroyWindow(title)

    def run(self, images_dir="Test", image_shape=(64, 64), model="v3",
            delete_cache=True, extract_only=False, visualize_only=False, overview=True, verbose=True):
        _t = time.time()
        y_pred = None
        if not visualize_only:
            if model != "v3":
                print("=" * 30)
                print("Resizing images...")
                print("=" * 30)
            else:
                print("=" * 30)
                print("Reading images...")
                print("=" * 30)
            if extract_only:
                self._image_paths = Pipeline.get_image_paths(images_dir)
            else:
                self._image_paths = Pipeline.get_image_paths(images_dir, True)
            rs = []
            _new_path, _mat_dir = images_dir + "/_cache", None
            if not os.path.isdir(_new_path):
                os.makedirs(_new_path)
            if model != "v3":
                for i, img in enumerate(self._image_paths):
                    _img = cv2.imread(img)
                    if model != "ResNet-v2":
                        _img = cv2.resize(_img, image_shape)
                    else:
                        image_shape = (299, 299)
                        _img = cv2.resize(_img, image_shape)/127.5-1
                    if model == "v3(64)":
                        _slash_idx = img.rfind("/")
                        _new_img = _new_path + "/" + img[_slash_idx+1:]
                        cv2.imwrite(_new_img, _img)
                        print("{} transformed to {} with shape {}".format(img, _new_img, image_shape))
                        self._image_paths[i] = _new_img
                    else:
                        print("{} transformed to shape {}".format(img, image_shape))
                        rs.append(_img.astype(np.float32))
                _mat_dir = _new_path + "/_mat.npy"
                np.save(_mat_dir, rs)
            print("Done")
            print("=" * 30)
            print("Using {} to extract features...".format(model))
            print("=" * 30)
            features, _ = Extractor(model, self._image_paths, _mat_dir).run(verbose)
            if extract_only:
                np.save("features", features)
                Pipeline._delete_cache(images_dir)
                return
            print("-" * 30)
            print("Loading predictor...")
            y_pred = Predictor(model).predict(features)
            print("-" * 30)
        self._img_dir = images_dir
        self._rs_dir = images_dir + "/_Result"
        label_dic = np.load(os.path.join("_Data", "_Cache", "LABEL_DIC.npy"))
        if not visualize_only:
            if not os.path.isdir(images_dir + "/_Result"):
                os.makedirs(self._rs_dir)
            np.save(self._rs_dir + "/prediction", y_pred)
            labels = label_dic[np.argmax(y_pred, axis=1)]
            with open(self._rs_dir + "/labels.txt", "w") as file:
                file.write("\n".join(labels))
            print("Done; results saved to '{}' folder".format(self._rs_dir))
            if delete_cache:
                Pipeline._delete_cache(images_dir)
            print("-" * 30)
            print("Done")
        print("(Test) Time cost: {:8.6} s".format(time.time() - _t))
        if overview:
            print("-" * 30)
            print("Visualizing results...")
            if os.path.isfile(images_dir + "/_answer.npy"):
                _ans = np.load(images_dir + "/_answer.npy")
            else:
                _ans = None
            images = self._get_results(_ans)
            n_row = math.ceil(math.sqrt(len(images)))  # type: int
            n_col = math.ceil(len(images) / n_row)
            pictures = []
            for i in range(n_row):
                if i == n_row - 1:
                    pictures.append(np.hstack(
                        [*images[i*n_col:], np.zeros((256, 640*(n_row*n_col-len(images)), 3)) + 255]).astype(np.uint8))
                else:
                    pictures.append(np.hstack(
                        images[i*n_col:(i+1)*n_col]).astype(np.uint8))
            self._results = images
            self._n_row, self._n_col = n_row, n_col
            big_canvas = np.vstack(pictures).astype(np.uint8)
            overview = cv2.resize(big_canvas, Pipeline.shape)

            cv2.namedWindow("Overview")
            cv2.setMouseCallback("Overview", self._get_detail)
            cv2.imshow("Overview", overview)
            cv2.waitKey(0)
            cv2.destroyAllWindows()

            print("-" * 30)
            print("Done")

    @staticmethod
    def _delete_cache(images_dir):
        print("-" * 30)
        print("Deleting '_cache' folder...")
        shutil.rmtree(images_dir + "/_cache")


text:
#if !defined(CLIPBOARD_FILE_H)
#define CLIPBOARD_FILE_H

#include "arch.h"
#include "parse.h"

int
clipboard_send_data_response_for_file(const char *data, int data_size);
int
clipboard_process_file_request(struct stream *s, int clip_msg_status,
                               int clip_msg_len);
int
clipboard_process_file_response(struct stream *s, int clip_msg_status,
                                int clip_msg_len);
int
clipboard_c2s_in_files(struct stream *s, char *file_list);

int
clipboard_request_file_size(int stream_id, int lindex);
int
clipboard_request_file_data(int stream_id, int lindex, int offset,
                            int request_bytes);

#endif

redpajama_set_name: RedPajamaGithub


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

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace BamlTools
{
    public class HexDumper
    {
        static string Symbols = "0123456789ABCDEF";

        Stream _reader;
        bool _showAddresses;
        bool _showText;

        public HexDumper(Stream stream)
        {
            _reader = stream;
            _showText = true;
        }

        public string DumpOneBigString()
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                foreach (string line in GetLines())
                {
                    sb.AppendLine(line);
                }
            }
            catch (Exception ex)
            {
                sb.AppendLine(ex.ToString());
            }

            return sb.ToString();
        }

        public IEnumerable<String> GetLines()
        {
            string hexString;
            byte[] inputBuffer = new byte[FullHexByteLength];

            while (_reader.Position < _reader.Length)
            {
                int count = _reader.Read(inputBuffer, 0, inputBuffer.Length);
                hexString = HexStringConvert(inputBuffer, count);
                if (ShowText)
                {
                    string textString = TextConvert(inputBuffer, count);
                    hexString = Pad(hexString, FullHexStringLength, ' ');
                    hexString += "  " + textString;
                }

                if (ShowAddresses)
                {
                    hexString = String.Format("{0:x5}: {1}", _reader.Position, hexString);
                }
                yield return hexString;
            }
        }

        public bool ShowAddresses
        {
            get { return _showAddresses; }
            set { _showAddresses = value; }
        }

        public bool ShowText
        {
            get { return _showText; }
            set { _showText = value; }
        }

        private const int FullHexByteLength = 16;

        private int FullHexStringLength
        {
            get { return FullHexByteLength * 3; }
        }

        private string HexStringConvert(byte[] input, int count)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < count; i++)
            {
                int high = (input[i] >> 4) & 0xF;
                int low = input[i] & 0xF;
                sb.AppendFormat("{0}{1} ", Symbols[high], Symbols[low]);
            }
            return sb.ToString();
        }

        private string TextConvert(byte[] input, int count)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < count; i++)
            {
                sb.Append((input[i] < ' ' || (int)input[i] > 127) ? '.' : (char)input[i]);
            }
            return sb.ToString();
        }

        private string Pad(string str, int length, char fill)
        {
            // this is somewhat inefficent, but it is only called once.
            for (int i = str.Length; i < length; i++)
            {
                str += fill;
            }
            return str;
        }
    }
}


text:
using cl.maia.data.mappers;
using insitu.data.entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace insitu.data.mappers
{
    public class RutasMapper : IEntityMapper<Rutas>
    {
        public Rutas Map(System.Data.IDataRecord parent)
        {
            return new Rutas()
            {
                Axis = parent["Axis"].ToString(),
                Cliente = int.Parse(parent["Cliente"].ToString()),
                Fecha = parent["Fecha"].ToString(),
                ID = int.Parse(parent["ID"].ToString()),
                Speed = parent["Speed"].ToString()
            };
        }
    }
}


text:
package ca.gnewton.pst2json;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="contentMetadata")
public class XmlContentMetadata{
    @XmlElement(name="m")
    XmlMetadataItem[] items;
}


text:
#import "GSBookViewContainerView.h"
#import "GSBookShelfView.h"
#import "GSBookView.h"
#import <QuartzCore/QuartzCore.h>

#define kRatio_width_spacing 2.5f
#define kRatio_height_width 1.2f

#define kGrow_animation_duration 0.15
#define kSrink_animation_duration 0.15

typedef enum {
    ADD_TYPE_FIRSTTIME,
    ADD_TYPE_HEAD,
    ADD_TYPE_TAIL
}AddType;

typedef enum {
    RM_TYPE_HEAD,
    RM_TYPE_TAIL
}RemoveType;

@interface GSBookViewContainerView (Private)

// reuse

- (void)addReuseableBookView:(UIView *)bookView;

// Scroll
- (void)stopScrollTimer;
- (void)scrollIfNecessary;

// Move
- (void)moveBooksIfNecessary;

// Animation
- (void)growAnimationAtPoint:(CGPoint)point forView:(UIView *)view;
- (void)animateBookViewToBookViewPostion:(BookViewPostion)toPosition rect:(CGRect)toRect;

// BookView Rect
- (CGRect)bookViewRectAtBookViewPosition:(BookViewPostion)position;

@end

@interface GSBookViewContainerView (Test)

- (void)checkVisibleBookViewsValid;
@end

@implementation GSBookViewContainerView

@synthesize parentBookShelfView = _parentBookShelfView;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {

        _reuseableBookViews = [[NSMutableDictionary alloc] initWithCapacity:0];

        _firstVisibleRow = -1;
        _lastVisibleRow = -1;

        _visibleBookViews = [[NSMutableArray alloc] initWithCapacity:0];

        // dragAndDrop
        _isDragViewPickedUp = NO;
        _isBooksMoving = NO;
        _isDragViewRemovedFromVisibleBookViews = NO;

        // Remove
        _isRemoving = NO;
        _indexsOfBookViewNotShown = [NSMutableIndexSet indexSet];
        _tempVisibleBookViewCollector = [[NSMutableArray alloc] initWithCapacity:0];

        // GestureRecognizer
        UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPressGesture:)];
        [self addGestureRecognizer:longPressGestureRecognizer];

    }
    return self;
}

# pragma mark - Reload

- (void)calculateLayout {
    CGFloat cellWidth = _parentBookShelfView.frame.size.width;
    CGFloat cellMargin = _parentBookShelfView.cellMargin; //[_parentBookShelfView.dataSource cellMarginOfBookShelfView:_parentBookShelfView];

    NSInteger numOfBooksInCell = [_parentBookShelfView.dataSource numberOFBooksInCellOfBookShelfView:_parentBookShelfView];

    _bookViewWidth = [_parentBookShelfView.dataSource bookViewWidthOfBookShelfView:_parentBookShelfView];
    _bookViewHeight = [_parentBookShelfView.dataSource bookViewHeightOfBookShelfView:_parentBookShelfView];

    _bookViewSpacingWidth = numOfBooksInCell == 1 ? 0 : (cellWidth - 2 * cellMargin - numOfBooksInCell * _bookViewWidth) / (numOfBooksInCell - 1);

    NSAssert(_bookViewSpacingWidth >= 0, @"invalid book size");
}

- (void)reloadData {
    [self calculateLayout];

    // Flags
    // visible row
    _firstVisibleRow = -1;
    _lastVisibleRow = -1;

    // dragAndDrop
    _isDragViewPickedUp = NO;
    _isBooksMoving = NO;
    _isDragViewRemovedFromVisibleBookViews = NO;

    // Remove
    _isRemoving = NO;

    for (UIView *view in _visibleBookViews) {
        [self addReuseableBookView:view];
        [view removeFromSuperview];
    }
    [_visibleBookViews removeAllObjects];

    //[_reuseableBookViews removeAllObjects];
}

#pragma mark - Reuse

- (void)addReuseableBookView:(UIView *)bookView {
    NSString *reuseIdentifier = nil;
    if ([bookView respondsToSelector:@selector(reuseIdentifier)]) {
        reuseIdentifier = [(id<GSBookView>)bookView reuseIdentifier];
    }

    if (reuseIdentifier == nil) {
        return;
    }

    NSMutableSet *bookViewSet = [_reuseableBookViews objectForKey:reuseIdentifier];
    if (!bookViewSet) {
        bookViewSet = [[NSMutableSet alloc] initWithCapacity:0];
        [_reuseableBookViews setObject:bookViewSet forKey:reuseIdentifier];
    }
    [bookViewSet addObject:bookView];
    //NSLog(@"bookViewSet count:%d", [bookViewSet count]);
}

- (UIView *)dequeueReusableBookViewWithIdentifier:(NSString *)identifier {
    NSMutableSet *bookViewSet = (NSMutableSet *)[_reuseableBookViews objectForKey:identifier];
    UIView *bookView = [bookViewSet anyObject];
    if (bookView) {
        [bookViewSet removeObject:bookView];
    }
    return bookView;
}

#pragma mark - Layout

- (UIView *)addBookViewAsSubviewWithBookViewPosition:(BookViewPostion)position {
    [UIView setAnimationsEnabled:NO];
    UIView *bookView = [_parentBookShelfView.dataSource bookShelfView:_parentBookShelfView bookViewAtIndex:position.index];
    // Take a look at the "Discussion" in removeBookViewWithType:
    // Since _dragView won't be removed from supervie, we should not add it or change the frame either. And although the new bookView returned from dataSource have the same position with _dragView, but they are not the same view, so set _dragView to bookView, ignore the bookView returned from dataSource.
    if (_isDragViewPickedUp && position.index == _pickUpPosition.index) {
        _isDragViewRemovedFromVisibleBookViews = NO;
        bookView = _dragView;
    }
    else {
        //bookView.tag = position.index; // set the tag as the index
        [bookView setFrame:[self bookViewRectAtBookViewPosition:position]];

        //NSLog(@"bookView Frame:%@", NSStringFromCGRect(bookView.frame));
        /*if (![_indexsOfBookViewToBeRemoved containsIndex:position.index] && !_isRemoving) {
            [self addSubview:bookView];
        }*/
        if (!([_indexsOfBookViewToBeRemoved containsIndex:position.index] || [_indexsOfBookViewNotShown containsIndex:position.index])) {
            [self addSubview:bookView];
        }

    }
    [UIView setAnimationsEnabled:YES];
    return bookView;
}

- (void)addBookViewAtBookViewPosition:(BookViewPostion) position addType:(AddType)addType {

    UIView *bookView = [self addBookViewAsSubviewWithBookViewPosition:position];

    NSMutableArray *visibleBookViews = _isRemoving ? _tempVisibleBookViewCollector : _visibleBookViews;

    switch (addType) {
        case ADD_TYPE_FIRSTTIME:
        case ADD_TYPE_TAIL:
            [visibleBookViews addObject:bookView];
            break;

        case ADD_TYPE_HEAD:
            [visibleBookViews insertObject:bookView atIndex:0];
            break;
    }
}

- (void)removeBookViewWithType:(RemoveType)rmType {
    NSInteger rmIndex;
    switch (rmType) {
        case RM_TYPE_HEAD:
            rmIndex = 0;
            break;
        case RM_TYPE_TAIL:
            rmIndex = [_visibleBookViews count] - 1;
    }
    UIView *bookView = [_visibleBookViews objectAtIndex:rmIndex];
    // Discusstion:When Drag And Scroll happends,somtimes _dragView's pickupPosition may have not changed. Then it may be told to be removed from superView, and this will cause the _dragView dissappear. So here we prevent the removeFromSuperview from happening, but still remove it from the _visibleBookViews. _visibleBookViews tells which view is visible except the _dragView, which means _dragView is "invisible" for _visibleBookViews when it's original position scroll out of the _availableRect.
    if (_isDragViewPickedUp && bookView == _dragView) {
        _isDragViewRemovedFromVisibleBookViews = YES;
    }
    else {
        [self addReuseableBookView:bookView];
        [bookView removeFromSuperview];
    }
    [_visibleBookViews removeObjectAtIndex:rmIndex];
}

- (void)layoutSubviewsWithAvailableRect:(CGRect)availableRect visibleRect:(CGRect)visibleRect{
    // To reduce memory usage, we only add visible bookViews to the subviews. So every time it scrolls, we shoud add and remove some bookViews.You can check the sample project (ScrollView Suit >> Tiling) for information.

    // Discussion: the layout sequence is easy to understand. There are 6 situation we should consider.  You can draw these condition on a papper to get it more clear.

    // 1. lastNeededRow < _firstVisibleRow
    // 2. firstNeededRow < _firstVisibleRow && lastNeededRow > _firstVisibleRow && lastNeededRow < _lastVisibleRow
    // 3. firstNeededRow < _firstVisibleRow && lastNeededRow > _lastVisibleRow
    // 4. firstNeededRow > _firstVisibleRow && lastNeededRow < _lastVisibleRow
    // 5. firstNeededRow > _firstVisibleRow && firstNeededRow < _lastVisibleRow && lastNeededRow > _lastVisibleRow
    // 6. firstNeededRow > _lastVisibleRow

    // We deal with these situations with a sequence of operation:
    // 1. if (lastNeededRow < _lastVisibleRow) remove some from the tail of _visibleBookViews
    // 2. if (firstNeededRow < _firstVisibleRow) add some to the head of _visibleBookViews
    // 3. if (firstNeededRow > _firstVisibleRow) remove some from the head of _visibleBookViews
    // 4. if (lastNeededRow > _lastVisibleRow) add some to the tail of _visibleBookViews

    // only two of these four steps will happen for each situation. Thanks to these we don't need to consider about where to insert or remove a propper bookView. Just add or remove then at the head or tail.

    //NSLog(@"bookViewContainer layout");
    //NSLog(@"availableRect %@", NSStringFromCGRect(availableRect));
    _availableRect = availableRect;
    _visibleRect = visibleRect;

    NSInteger numberOfBooksInCell = [_parentBookShelfView.dataSource numberOFBooksInCellOfBookShelfView:_parentBookShelfView];

    NSInteger numberOfBooks = [_parentBookShelfView.dataSource numberOfBooksInBookShelfView:_parentBookShelfView];

    NSInteger numberOfCells = ceilf((float)numberOfBooks / (float)numberOfBooksInCell);

    NSInteger cellHeight = [_parentBookShelfView.dataSource cellHeightOfBookShelfView:_parentBookShelfView];

    NSInteger firstNeededRow = MAX(0, floorf(CGRectGetMinY(availableRect) / cellHeight));
    NSInteger lastNeededRow = MIN(numberOfCells - 1, floorf(CGRectGetMaxY(availableRect) / cellHeight));

    //NSLog(@"\n------------\nfirstNeededRow:%d firstVisibleRow:%d\nlastNeededRow: %d lastVisibleRow: %d\n************", firstNeededRow, _firstVisibleRow, lastNeededRow, _lastVisibleRow);

    // remove and add bookview according to the row
    if (_firstVisibleRow == -1) {
        // First time
        for (NSInteger row = firstNeededRow; row <= lastNeededRow; row++) {
            // add firstTime
            for (NSInteger col = 0; col < numberOfBooksInCell; col++) {
                NSInteger index = row * numberOfBooksInCell + col;
                if (index >= numberOfBooks) {
                    break;
                }
                BookViewPostion position = {row, col, index};
                [self addBookViewAtBookViewPosition:position addType:ADD_TYPE_FIRSTTIME];
            }
        }
    }
    else {
        // Not first time

        if (lastNeededRow < _lastVisibleRow) {
            NSInteger rmFromRow = (_firstVisibleRow > lastNeededRow + 1) ? _firstVisibleRow : lastNeededRow + 1;
            for (NSInteger row = _lastVisibleRow; row >= rmFromRow; row--) {
                // rm from tail of the _visibleBookView
                // use reversed row to always remove at tile
                for (NSInteger col = numberOfBooksInCell - 1; col >= 0; col--) {
                    NSInteger index = row * numberOfBooksInCell + col;
                    if (index < numberOfBooks) {
                        [self removeBookViewWithType:RM_TYPE_TAIL];
                    }
                }
            }
        }

        if (firstNeededRow < _firstVisibleRow) {
            NSInteger addToRow = (_firstVisibleRow - 1 < lastNeededRow) ? _firstVisibleRow - 1 : lastNeededRow;

            for (NSInteger row = addToRow; row >= firstNeededRow; row--) {
                // add to head of the _visibileBookView
                // use reversed row to always add to index 0
                for (NSInteger col = numberOfBooksInCell - 1; col >= 0; col--) {
                    NSInteger index = row * numberOfBooksInCell + col;
                    if (index < numberOfBooks) {
                        BookViewPostion position = {row, col, index};
                        [self addBookViewAtBookViewPosition:position addType:ADD_TYPE_HEAD];
                    }
                }
            }
        }

        if (firstNeededRow > _firstVisibleRow) {
            NSInteger rmToRow = (_lastVisibleRow  <= firstNeededRow - 1) ? _lastVisibleRow : firstNeededRow - 1;
            for (NSInteger row = _firstVisibleRow; row <= rmToRow; row++) {
                // rm from head
                for (NSInteger col = 0; col < numberOfBooksInCell; col++) {
                    NSInteger index = row * numberOfBooksInCell + col;
                    if (index >= numberOfBooks) {
                        break;
                    }
                    [self removeBookViewWithType:RM_TYPE_HEAD];
                }
            }
        }

        if (lastNeededRow > _lastVisibleRow) {
            NSInteger addFromRow = (_lastVisibleRow + 1 > firstNeededRow) ? _lastVisibleRow + 1 : firstNeededRow;
            for (NSInteger row = addFromRow; row <= lastNeededRow; row++) {
                // add to tail
                for (NSInteger col = 0; col < numberOfBooksInCell; col++) {
                    NSInteger index = row * numberOfBooksInCell + col;
                    if (index >= numberOfBooks) {
                        break;
                    }
                    BookViewPostion position = {row, col, index};
                    [self addBookViewAtBookViewPosition:position addType:ADD_TYPE_TAIL];
                }
            }
        }
    }

    //[self checkVisibleBookViewsValid];
    //NSLog(@"visible count:%d", [_visibleBookViews count]);
    _firstVisibleRow = firstNeededRow;
    _lastVisibleRow = lastNeededRow;
}

- (void)layoutSubviews {
    // Do nothing here
    // use layoutSubviewsWithavailableRect: instead
}

#pragma mark - BookViewPosition

#pragma mark - BookView Rect

- (NSInteger)convertToIndexFromVisibleBookViewIndex:(NSInteger)index {
    // not safe for some events
    return _firstVisibleRow * _parentBookShelfView.numberOfBooksInCell + index;
}

- (BookViewPostion)convertToBookViewPositionFromIndex:(NSInteger)index {
    NSInteger row = index / _parentBookShelfView.numberOfBooksInCell;
    NSInteger col = index % _parentBookShelfView.numberOfBooksInCell;
    BookViewPostion position = {row, col, index};
    return position;
}

- (NSInteger)converToIndexOfVisibleBookViewsFromBookViewPosition:(BookViewPostion)position {

    NSInteger numberOfBooksInCell = _parentBookShelfView.numberOfBooksInCell;

    NSInteger indexOfVisibleBookViews = numberOfBooksInCell * (position.row - _firstVisibleRow) + position.col;

    return indexOfVisibleBookViews;
}

- (NSInteger)converToIndexOfVisibleBookViewsFromIndex:(NSInteger)index {
    BookViewPostion position = [self convertToBookViewPositionFromIndex:index];
    return [self converToIndexOfVisibleBookViewsFromBookViewPosition:position];
}

- (BOOL)isBookViewPositionVisible:(BookViewPostion)position {
    NSInteger numberOfBooks = [_parentBookShelfView.dataSource numberOfBooksInBookShelfView:_parentBookShelfView];

    /*if (position.index < numberOfBooks && position.index >= 0) {
        return YES;
    }*/
    if (position.row >= _firstVisibleRow && position.row <= _lastVisibleRow && position.index < numberOfBooks && position.index >= 0) {
        return YES;
    }

    return NO;
}

- (CGRect)bookViewRectAtBookViewPosition:(BookViewPostion)position {
    // Do not need position.index here
    CGFloat cellHeight = _parentBookShelfView.cellHeight;
    CGFloat bookViewBottomOffset = _parentBookShelfView.bookViewBottomOffset;
    CGFloat cellMarginWidth = _parentBookShelfView.cellMargin;

    CGFloat originX = cellMarginWidth + position.col * (_bookViewWidth + _bookViewSpacingWidth);
    CGFloat originY = position.row * cellHeight + bookViewBottomOffset - _bookViewHeight;

    return CGRectMake(originX, originY, _bookViewWidth, _bookViewHeight);
}

- (CGRect)bookViewEffectiveRectAtBookViewPosition:(BookViewPostion)position {
    CGFloat cellHeight = _parentBookShelfView.cellHeight;
    CGFloat bookViewBottomOffset = _parentBookShelfView.bookViewBottomOffset;
    CGFloat cellMarginWidth = _parentBookShelfView.cellMargin;

    NSInteger numberOfBooksInCell = _parentBookShelfView.numberOfBooksInCell;

    CGFloat originX = position.col * (_bookViewWidth + _bookViewSpacingWidth) + (position.col > 0 ? (cellMarginWidth - _bookViewSpacingWidth / 2) : 0);

    CGFloat effectiveWidth = _bookViewWidth + _bookViewSpacingWidth + ((position.col == 0 || position.col == numberOfBooksInCell - 1) ? (cellMarginWidth - _bookViewSpacingWidth / 2) : 0);

    CGFloat originY = position.row * cellHeight + bookViewBottomOffset - _bookViewHeight;

    return CGRectMake(originX, originY, effectiveWidth, _bookViewHeight);
}

- (BookViewPostion)bookViewPositionAtPoint:(CGPoint)point {
    // Always return a valid BookViewPosition
    CGFloat cellHeight = _parentBookShelfView.cellHeight;

    NSInteger currentRow = floorf(point.y / cellHeight);

    CGFloat cellMarginWidth = _parentBookShelfView.cellMargin;

    CGFloat firstColWidth = cellMarginWidth + _bookViewWidth + _bookViewSpacingWidth / 2;
    CGFloat middleColWidth = _bookViewWidth + _bookViewSpacingWidth;

    NSInteger numberOfBooksInCell = _parentBookShelfView.numberOfBooksInCell;

    NSInteger currentCol;

    if (point.x < firstColWidth) {
        currentCol = 0;
    }
    else {
        currentCol =  MIN(floorf((point.x - firstColWidth) / middleColWidth) + 1, numberOfBooksInCell - 1);
    }

    BookViewPostion position = {currentRow, currentCol, currentRow * numberOfBooksInCell + currentCol};

    //NSLog(@"position [%d] [%d]", currentRow, currentCol);

    return position;
}

- (CGRect)bookViewRectAtPoint:(CGPoint)point {
    // Return an CGRectZero if the point is not in any bookView's frame
    BookViewPostion position = [self bookViewPositionAtPoint:point];
    CGRect bookViewRect = [self bookViewRectAtBookViewPosition:position];

    if (!CGRectContainsPoint(bookViewRect, point)) {
        bookViewRect = CGRectZero;
    }

    return bookViewRect;
}

- (UIView *)bookViewAtPoint:(CGPoint)point {
    UIView *bookView = nil;

    BookViewPostion position = [self bookViewPositionAtPoint:point];
    CGRect bookViewRect = [self bookViewRectAtBookViewPosition:position];

    if (!CGRectEqualToRect(bookViewRect, CGRectZero) && [self isBookViewPositionVisible:position]) {
        // a valid bookViewRect
        NSInteger indexOfVisibleBookViews = [self converToIndexOfVisibleBookViewsFromBookViewPosition:position];

        bookView = [_visibleBookViews objectAtIndex:indexOfVisibleBookViews];
    }
    return bookView;
}

#pragma mark - Gesture Recognizer

- (void)handleLongPressGesture:(UILongPressGestureRecognizer *)gestureRecognizer {

    if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
        CGPoint touchPoint = [gestureRecognizer locationInView:self];
        BOOL dragAndDropEnable = _parentBookShelfView.dragAndDropEnabled;
        if (dragAndDropEnable) {

            BookViewPostion position = [self bookViewPositionAtPoint:touchPoint];
            CGRect bookViewRect = [self bookViewRectAtBookViewPosition:position];

            if (CGRectContainsPoint(bookViewRect, touchPoint) && [self isBookViewPositionVisible:position]) {
                NSInteger indexOfVisibleBookViews = [self converToIndexOfVisibleBookViewsFromBookViewPosition:position];
                _dragView = [_visibleBookViews objectAtIndex:indexOfVisibleBookViews];
                [self bringSubviewToFront:_dragView];
                [self growAnimationAtPoint:touchPoint forView:_dragView];

                _pickUpPosition = position;
                _pickUpRect = bookViewRect;
                _isDragViewPickedUp = YES;
                _isDragViewRemovedFromVisibleBookViews = NO;
            }
        }
    }
    else if (gestureRecognizer.state == UIGestureRecognizerStateChanged) {
        if (_isDragViewPickedUp) {
            CGPoint touchPoint = [gestureRecognizer locationInView:self];
            _dragView.center = touchPoint;
            [self moveBooksIfNecessary];
            [self scrollIfNecessary];

        }
    }
    /*else if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
        if (_isDragViewPickedUp) {
            [UIView animateWithDuration:0.3
                                  delay:0.0
                                options:UIViewAnimationCurveLinear | UIViewAnimationOptionLayoutSubviews
                             animations:^{
                                 _dragView.frame = _pickUpRect;
                             }
                             completion:^(BOOL finished) {
                                 _isDragViewPickedUp = NO;
                             }];

        }
        [self stopScrollTimer];
    }*/
    else {
        if (_isDragViewPickedUp) {
            [UIView animateWithDuration:0.3
                                  delay:0.0
                                options:UIViewAnimationCurveLinear | UIViewAnimationOptionLayoutSubviews
                             animations:^{
                                 //_dragView.frame = _pickUpRect;
                                 _dragView.transform = CGAffineTransformIdentity;
                                 _dragView.center = CGPointMake(CGRectGetMidX(_pickUpRect), CGRectGetMidY(_pickUpRect));
                             }
                             completion:^(BOOL finished) {
                                 _isDragViewPickedUp = NO;
                                 if (_isDragViewRemovedFromVisibleBookViews) {
                                     [self addReuseableBookView:_dragView];
                                     [_dragView removeFromSuperview];
                                 }
                                 _dragView = nil;
                             }];

        }
        [self stopScrollTimer];
    }

}

#pragma mark - Scroll While Draging

#define kScroll_trigger_dis 40.0f
#define kScroll_dis_scale 27
#define kScroll_max_speed 20

- (void)stopScrollTimer {
    [_displayLink removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
    [_displayLink invalidate];
    _displayLink = nil;
}

- (void)scrollIfNecessary {
    if (_parentBookShelfView.scrollWhileDragingEnabled) {
        [self stopScrollTimer];

        CGFloat distanceFromTop = _dragView.center.y - _visibleRect.origin.y;
        if (distanceFromTop < kScroll_trigger_dis || distanceFromTop > _visibleRect.size.height - kScroll_trigger_dis) {
            _lastDragScrollTime = CACurrentMediaTime(); // Note: See http://stackoverflow.com/questions/358207/iphone-how-to-get-current-milliseconds for speed comparation
            _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(dragScroll:)];
            [_displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        }
    }
}

// Not used currently
- (BOOL)canScroll:(BOOL)isScrollUp {
    if (isScrollUp) {
        if (_parentBookShelfView.contentOffset.y <= 0) {
            return NO;
        }
    }
    else {
        if (_parentBookShelfView.contentOffset.y + _visibleRect.size.height >=_parentBookShelfView.contentSize.height) {
            return NO;
        }
    }
    return YES;
}

- (CGFloat)safeHorizontalScrollDistanceWithDistance:(CGFloat)distance isScrollUp:(BOOL)isScrollUp {
    if (isScrollUp) {
        CGFloat maxDis = _parentBookShelfView.contentOffset.y;
        return MIN(maxDis, distance);
    }
    else {
        CGFloat maxDis = _parentBookShelfView.contentSize.height - (_parentBookShelfView.contentOffset.y + _visibleRect.size.height);
        return MIN(maxDis, distance);
    }
}

- (void)dragScroll:(NSTimer *)timer {
    BOOL isScrollUp;
    CGFloat distanceFromTop = _dragView.center.y - _visibleRect.origin.y;
    double timeSinceLastScroll = CACurrentMediaTime() - _lastDragScrollTime; // Around 0.015
    CGFloat scrollDistance = 0;
    double rate; // Between 0 to 40

    if (distanceFromTop < kScroll_trigger_dis) {
        isScrollUp = YES;
        rate = (kScroll_trigger_dis - distanceFromTop);
    }
    else {
        isScrollUp = NO;
        rate = (kScroll_trigger_dis - (_visibleRect.size.height - distanceFromTop));
    }

    scrollDistance = rate * timeSinceLastScroll * kScroll_dis_scale; // Between 0 to around 20
    scrollDistance = [self safeHorizontalScrollDistanceWithDistance:scrollDistance isScrollUp:isScrollUp];
    if (scrollDistance >= 1) {
        // Actually it won't scroll when the distance is below 1
        // Also the contentOffset is always interger
        // so there's no difference betteen scroll 1.0 and 1.4/1.9 ??
        // we round the float to integer to get the best fit value <<- is this necessary ?
        scrollDistance = roundf(scrollDistance);
        scrollDistance = MIN(scrollDistance, kScroll_max_speed);

        CGPoint newOffset = _parentBookShelfView.contentOffset;
        newOffset.y = newOffset.y + (isScrollUp ? -scrollDistance : scrollDistance);
        [_parentBookShelfView setContentOffset:newOffset];

        CGPoint newDragViewCenter = _dragView.center;
        newDragViewCenter.y = newDragViewCenter.y + (isScrollUp ? -scrollDistance : scrollDistance);
        _dragView.center = newDragViewCenter;
        [self moveBooksIfNecessary];

        // Refresh time only when it really scrolled
        _lastDragScrollTime = CACurrentMediaTime();
    }
}

#pragma mark - Move

- (void)moveBooksIfNecessary {
    [self bringSubviewToFront:_dragView];
    BookViewPostion position = [self bookViewPositionAtPoint:_dragView.center];
    CGRect bookViewRect = [self bookViewRectAtBookViewPosition:position];
    CGRect bookviewEffectiveRect = [self bookViewEffectiveRectAtBookViewPosition:position];

    //NSLog(@"[0] %@", NSStringFromCGPoint(_dragView.center));
    //NSLog(@"[1] %@", NSStringFromCGRect(bookViewRect));
    //NSLog(@"[2] %@", NSStringFromCGRect(bookviewEffectiveRect));

    if (CGRectContainsPoint(bookviewEffectiveRect, _dragView.center) && [self isBookViewPositionVisible:position]) {
        //NSLog(@"contain");
        if (!CGRectEqualToRect(bookViewRect, _pickUpRect)) {
            // Rerange _visibleBookViews
            //NSLog(@"Rerange");
            [self animateBookViewToBookViewPostion:position rect:bookViewRect];
        }
    }
}

- (void)moveBookView:(UIView *)bookView steps:(NSInteger)steps {
    BookViewPostion position = [self bookViewPositionAtPoint:bookView.center];
    NSInteger nPerCell = _parentBookShelfView.numberOfBooksInCell;
    CGFloat horizontalDisPerStep = _bookViewWidth + _bookViewSpacingWidth;
    CGFloat verticalDisPerStep = _parentBookShelfView.cellHeight;

    NSInteger horizontalSteps = ((position.col + steps) % nPerCell + nPerCell) % nPerCell - position.col;
    NSInteger verticalSteps = floorf((position.col + steps) / (float) nPerCell);
    CGFloat newCenterX = bookView.center.x + horizontalSteps * horizontalDisPerStep;
    CGFloat newCenterY = bookView.center.y + verticalSteps * verticalDisPerStep;
    bookView.center = CGPointMake(newCenterX, newCenterY);
}

#pragma mark - Animation

- (void)growAnimationAtPoint:(CGPoint)point forView:(UIView *)view {
    [UIView animateWithDuration:kGrow_animation_duration
                          delay:0.0
                        options:UIViewAnimationCurveLinear | UIViewAnimationOptionLayoutSubviews
                     animations:^{
                         view.transform = CGAffineTransformMakeScale(1.2, 1.2);
                         view.center = point;
                     }
                     completion:NULL];
}

- (void)shrinkAnimationToPoint:(CGPoint)point forView:(UIView *)view {

}

- (void)animateBookViewToBookViewPostion:(BookViewPostion)toPosition rect:(CGRect)toRect {
    if (!_isBooksMoving) {
        BOOL shouldRemoveHeadOrTailFromVisibleBookViews = NO;
        if (_isDragViewRemovedFromVisibleBookViews) {
            // Take a look at the "Discussion" in removeBookViewWithType:
            // Discussion: if the _dragView is "invisible". _dragView maybe insert into the _visibleBookViews and the head or tail in _visibleBookViews should be removedFromSuperview to keep the _visibleBookViews contains only bookViews in visible rows.
            _isDragViewRemovedFromVisibleBookViews = NO;
            shouldRemoveHeadOrTailFromVisibleBookViews = YES;
        }

        if (_pickUpPosition.index < toPosition.index) {
            // drag forward/down

            NSInteger fromIndexOfVisibleBookViews = [self converToIndexOfVisibleBookViewsFromBookViewPosition:_pickUpPosition];
            NSInteger toIndexOfVisibleBookViews = [self converToIndexOfVisibleBookViewsFromBookViewPosition:toPosition];

            NSInteger indexOfBookViewToBeRemoved = MAX(0, fromIndexOfVisibleBookViews);
            UIView *bookViewToRemove = [_visibleBookViews objectAtIndex:indexOfBookViewToBeRemoved];

            [UIView animateWithDuration:0.3
                                  delay:0.0
                                options:UIViewAnimationCurveLinear | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionLayoutSubviews
                             animations:^{
                                 _isBooksMoving = YES;

                                 assert(toIndexOfVisibleBookViews < [_visibleBookViews count]);
                                 for (NSInteger index = MAX(0, fromIndexOfVisibleBookViews + 1); index <= MIN(toIndexOfVisibleBookViews, [_visibleBookViews count] - 1); index++) {
                                     UIView *bookView = [_visibleBookViews objectAtIndex:index];
                                     [self moveBookView:bookView steps:-1];
                                 }

                                 [_visibleBookViews removeObjectAtIndex:indexOfBookViewToBeRemoved];
                                 [_visibleBookViews insertObject:_dragView atIndex:toIndexOfVisibleBookViews];

                                 if ([_parentBookShelfView.dataSource respondsToSelector:@selector(bookShelfView:moveBookFromIndex:toIndex:)]) {
                                     [_parentBookShelfView.dataSource bookShelfView:_parentBookShelfView moveBookFromIndex:_pickUpPosition.index toIndex:toPosition.index];
                                 }

                                 _pickUpPosition = toPosition;
                                 _pickUpRect = toRect;
                             }
                             completion:^(BOOL finished) {
                                 _isBooksMoving = NO;
                                 if (shouldRemoveHeadOrTailFromVisibleBookViews) {
                                     [bookViewToRemove removeFromSuperview];
                                 }

                             }];

        }

        else {
            // drag backward/up

            NSInteger fromIndexOfVisibleBookViews = [self converToIndexOfVisibleBookViewsFromBookViewPosition:_pickUpPosition];
            NSInteger toIndexOfVisibleBookViews = [self converToIndexOfVisibleBookViewsFromBookViewPosition:toPosition];

            NSInteger indexOfBookViewToBeRemoved = MIN([_visibleBookViews count] - 1, fromIndexOfVisibleBookViews);
            UIView *bookViewToRemove = [_visibleBookViews objectAtIndex:indexOfBookViewToBeRemoved];

            [UIView animateWithDuration:0.3
                                  delay:0.0
                                options:UIViewAnimationCurveLinear | UIViewAnimationOptionAllowUserInteraction | UIViewAnimationOptionLayoutSubviews
                             animations:^{
                                 _isBooksMoving = YES;

                                 assert(toIndexOfVisibleBookViews >= 0);
                                 for (NSInteger index = MAX(0, toIndexOfVisibleBookViews); index <= MIN(fromIndexOfVisibleBookViews - 1, [_visibleBookViews count] - 1); index++) {
                                     UIView *bookView = [_visibleBookViews objectAtIndex:index];
                                     [self moveBookView:bookView steps:1];
                                 }

                                 [_visibleBookViews removeObjectAtIndex:indexOfBookViewToBeRemoved];
                                 [_visibleBookViews insertObject:_dragView atIndex:toIndexOfVisibleBookViews];

                                 if ([_parentBookShelfView.dataSource respondsToSelector:@selector(bookShelfView:moveBookFromIndex:toIndex:)]) {
                                     [_parentBookShelfView.dataSource bookShelfView:_parentBookShelfView moveBookFromIndex:_pickUpPosition.index toIndex:toPosition.index];
                                 }

                                 _pickUpPosition = toPosition;
                                 _pickUpRect = toRect;
                             }
                             completion:^(BOOL finished) {
                                 _isBooksMoving = NO;
                                 if (shouldRemoveHeadOrTailFromVisibleBookViews) {
                                     [bookViewToRemove removeFromSuperview];
                                 }

                             }];
        }
    }
}

#pragma mark - Delete and Add

- (void)removeBookViewsAtIndexs:(NSIndexSet *)indexs animate:(BOOL)animate; {
    // The animation Sequence is:
    // 1. make bookViews disappear (a scale to (0.001, 0.001) in fact)
    // 2. because some rows may be removed, we will set the contentOffset to a propper postition
    // 3. move bookViews to fill blank

    // Discussion 1: _parentBookShelfView's remove.... method did step 2 above before coming in to the current method. Seems the layoutSubviews called by setContentOffset(step 2) should occour before step 1. But the true is:layoutSubvies occour after step 1. I think it's "runloop" that cause this. Animation was set and then main thread enter next loop and layoutSubviews occour.(I'm not so sure about this.)

    // Discussion 2:
    // step 1. in the first animation we scale the bookViews to be removed. The current visible bookVie will move to some position in step 3 so we record the steps for each visible bookView(stepsArray), and record the positions(indexs) they will move to(_indexsOfBookViewNotShown).
    // step 2. in the layoutSubviews. we add all new added bookView to  _tempVisibleBookViewCollector instead of _visibleBookViews to keep _visibleBookViews "clean"(contains only bookViews showed in step 1). And check if the added bookview index is in _indexsOfBookViewNotShown (not add them to subviews). After layoutSubviews, the contentOffset has been set properly, and the proper bookViews will show up with some blank waiting for some bookViews moving to.
    // step 3. This is simple, just let each bookViews move with the steps record in stepsArray. After all animation. We clean the Arrays and Sets and refresh the current contents to make some bookView visible and keep everything go back to normal status.

    _isRemoving = YES;
    _indexsOfBookViewToBeRemoved = [[NSMutableIndexSet alloc] initWithIndexSet:indexs];

    NSMutableArray *stepsArray = [[NSMutableArray alloc] initWithCapacity:[_visibleBookViews count]];

    // Record the bookViews to be remvoed
    [UIView animateWithDuration:animate ? 0.15 : 0.0
                          delay:0.0
                        options:UIViewAnimationCurveLinear | UIViewAnimationOptionLayoutSubviews
                     animations:^{
                         // Dissmiss BookView
                         //NSLog(@"disappear animation");

                         __block NSInteger steps = 0;
                         __block NSInteger moveFromIndex = 0;

                         [indexs enumerateIndexesUsingBlock:^(NSUInteger index, BOOL *stop) {
                             BookViewPostion position = [self convertToBookViewPositionFromIndex:index];
                             NSInteger indexOfVisibleBookViews = [self converToIndexOfVisibleBookViewsFromBookViewPosition:position];
                             if (indexOfVisibleBookViews >= 0) {
                                 if (indexOfVisibleBookViews >= [_visibleBookViews count]) {
                                     *stop = YES;
                                     // added on 12.08.24 fix deletion when deletion index bigger than max visible index
                                     // not increse steps, balance with steps++
                                     steps--;
                                 }
                                 else {
                                     // shrink
                                     UIView *bookView = [_visibleBookViews objectAtIndex:indexOfVisibleBookViews];
                                     bookView.transform = CGAffineTransformMakeScale(0.001f, 0.001f);

                                     // record _indexsOfBookViewNotShown
                                     BOOL overVisible = indexOfVisibleBookViews >= [_visibleBookViews count];
                                     NSInteger moveToIndex = overVisible ? [_visibleBookViews count] - 1 : indexOfVisibleBookViews;
                                     while (moveFromIndex <= moveToIndex) {
                                         NSInteger realIndex = [self convertToIndexFromVisibleBookViewIndex:moveFromIndex] - steps;
                                         [_indexsOfBookViewNotShown addIndex:realIndex];

                                         [stepsArray addObject:[NSNumber numberWithInt:-steps]];

                                         moveFromIndex++;
                                     }
                                 }
                             }

                             steps++;

                             //NSLog(@"index not shown: %@", [_indexsOfBookViewNotShown description]);
                         }];
                         while (moveFromIndex < [_visibleBookViews count]) {
                             NSInteger realIndex = [self convertToIndexFromVisibleBookViewIndex:moveFromIndex] - steps;
                             [_indexsOfBookViewNotShown addIndex:realIndex];

                             [stepsArray addObject:[NSNumber numberWithInt:-steps]];

                             moveFromIndex++;
                         }
                     }completion:^(BOOL finished) {
                         //NSLog(@"disappear animation completion");

                         [UIView animateWithDuration:animate ? 0.3 : 0.0
                                               delay:0.01
                                             options:UIViewAnimationOptionCurveLinear
                                          animations:^ {
                                              //NSLog(@"move animation");
                                              for (int i = 0; i < [_visibleBookViews count]; i++) {
                                                  UIView *bookView = [_visibleBookViews objectAtIndex:i];
                                                  [self moveBookView:bookView steps:[(NSNumber *)[stepsArray objectAtIndex:i] intValue]];
                                              }
                                              return;
                                          }
                                          completion:^(BOOL finished) {
                                              //NSLog(@"move animation completion");
                                              [_indexsOfBookViewToBeRemoved removeAllIndexes];
                                              [_indexsOfBookViewNotShown removeAllIndexes];

                                              _isRemoving = NO;
                                              for (UIView *view in _tempVisibleBookViewCollector) {
                                                  [view removeFromSuperview];
                                              }
                                              [_tempVisibleBookViewCollector removeAllObjects];

                                              for (UIView *bookView in _visibleBookViews) {
                                                  [bookView removeFromSuperview];
                                              }
                                              [_visibleBookViews removeAllObjects];
                                              _firstVisibleRow = -1;
                                              _lastVisibleRow = -1;
                                              [_parentBookShelfView setNeedsLayout];
                                          }];
                     }];
}

- (void)insertBookViewsAtIndexs:(NSIndexSet *)indexs animate:(BOOL)animate; {
    // The animation Sequence is:
    // 1. move to get blanks for bookViews will be added
    // 2. show the added bookViews

    // Discussion:
    // step.1 we count from first insert index to the real index in _visibleBookView to calculte the steps of bookView in _visibleBookViews will move.
    // before animation in step 2.we get bookView from datasource and set the scale to (0.001,0.001) without animation
    // then in the animation, we set the bookView's scale to (1,1) to "show" the bookView and then refresh the _visibleBookView as we did in removeBookViewsAtIndexs:animate:
    [UIView animateWithDuration:animate ? 0.3 : 0.0
                          delay:0.0
                        options:UIViewAnimationOptionCurveLinear
                     animations:^{
                         __block NSInteger steps = 0;
                         __block NSInteger moveFromIndex = 0;
                         __block NSInteger lastIndexInIndexs = -1;
                         __block NSInteger tempIndex = 0;

                         [indexs enumerateIndexesUsingBlock:^(NSUInteger index, BOOL *stop) {
                             NSInteger diff = index - lastIndexInIndexs;

                             if (diff > 1) {
                                 if (lastIndexInIndexs < 0) {
                                     // first enumerate
                                     tempIndex = index;
                                 }
                                 else {
                                     tempIndex = moveFromIndex + diff - 1;
                                 }
                                 while (moveFromIndex < tempIndex) {
                                     BookViewPostion position = [self convertToBookViewPositionFromIndex:moveFromIndex];
                                     NSInteger indexOfVisibleBookViews = [self converToIndexOfVisibleBookViewsFromBookViewPosition:position];
                                     if (indexOfVisibleBookViews > (NSInteger)[_visibleBookViews count] - 1) {
                                         *stop = YES;
                                         break;
                                     }
                                     else if (indexOfVisibleBookViews >= 0) {
                                         UIView *bookView = [_visibleBookViews objectAtIndex:indexOfVisibleBookViews];
                                         [self moveBookView:bookView steps:steps];
                                     }
                                     moveFromIndex++;
                                 }
                             }
                             steps++;
                             lastIndexInIndexs = index;
                         }];
                         while (YES) {
                             BookViewPostion position = [self convertToBookViewPositionFromIndex:moveFromIndex];
                             NSInteger indexOfVisibleBookViews = [self converToIndexOfVisibleBookViewsFromBookViewPosition:position];
                             if (indexOfVisibleBookViews > (NSInteger)[_visibleBookViews count] - 1) {
                                 break;
                             }
                             else if (indexOfVisibleBookViews >= 0) {
                                 UIView *bookView = [_visibleBookViews objectAtIndex:indexOfVisibleBookViews];
                                 [self moveBookView:bookView steps:steps];
                             }
                             moveFromIndex++;
                         }
                     }
                     completion:^(BOOL finished) {
                         NSMutableArray *tempBookViewArray = [[NSMutableArray alloc] initWithCapacity:0];
                         [indexs enumerateIndexesUsingBlock:^(NSUInteger index, BOOL *stop) {
                             BookViewPostion position = [self convertToBookViewPositionFromIndex:index];
                             if (position.row > _lastVisibleRow) {
                                 *stop = YES;
                             }
                             else if (position.row >= _firstVisibleRow) {
                                 UIView *bookView = [_parentBookShelfView.dataSource bookShelfView:_parentBookShelfView bookViewAtIndex:index];
                                 CGRect bookViewFrame = [self bookViewRectAtBookViewPosition:position];
                                 [bookView setFrame:bookViewFrame];
                                 [self addSubview:bookView];
                                 bookView.transform = CGAffineTransformMakeScale(0.001f, 0.001f);

                                 [tempBookViewArray addObject:bookView];
                             }
                         }];
                         [UIView animateWithDuration:animate ? 0.25 : 0.0
                                               delay:0.0
                                             options:UIViewAnimationCurveEaseOut | UIViewAnimationOptionLayoutSubviews
                                          animations:^{
                                              for (UIView *bookView in tempBookViewArray) {
                                                  bookView.transform = CGAffineTransformMakeScale(1.0f, 1.0f);
                                              }
                                          }
                                          completion:^(BOOL finished) {
                                              for (UIView *bookView in tempBookViewArray) {
                                                  [bookView removeFromSuperview];
                                                  [self addReuseableBookView:bookView];
                                              }
                                              [tempBookViewArray removeAllObjects];

                                              for (UIView *bookView in _visibleBookViews) {
                                                  [bookView removeFromSuperview];
                                                  [self addReuseableBookView:bookView];
                                              }
                                              [_visibleBookViews removeAllObjects];
                                              _firstVisibleRow = -1;
                                              _lastVisibleRow = -1;
                                              [_parentBookShelfView setNeedsLayout];
                                          }];

                     }];
}

#pragma mark - visible

- (NSArray *)visibleBookViews {
    return _visibleBookViews;
}

- (UIView *)bookViewAtIndex:(NSInteger)index {
    NSInteger indexOfVisible = [self converToIndexOfVisibleBookViewsFromIndex:index];
    if (indexOfVisible < 0 || indexOfVisible >= [_visibleBookViews count]) {
        return nil;
    }
    return [_visibleBookViews objectAtIndex:indexOfVisible];
}

#pragma mark - test

- (void)checkVisibleBookViewsValid {
    //NSLog(@"---------------------------");
    int i = ((UIView *)[_visibleBookViews objectAtIndex:0]).tag;
    for (UIView *view in _visibleBookViews) {
        if (i != view.tag) {
            NSLog(@"$$$$$$ checkVisibleBookViewsValid error");
        }
        i++;
    }
    //NSLog(@"***************************");
}

@end


text:
package org.apache.flink.sql.parser.ddl.resource;

import org.apache.calcite.sql.SqlCall;
import org.apache.calcite.sql.SqlCharStringLiteral;
import org.apache.calcite.sql.SqlKind;
import org.apache.calcite.sql.SqlLiteral;
import org.apache.calcite.sql.SqlNode;
import org.apache.calcite.sql.SqlOperator;
import org.apache.calcite.sql.SqlSpecialOperator;
import org.apache.calcite.sql.SqlWriter;
import org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.calcite.util.ImmutableNullableList;

import javax.annotation.Nonnull;

import java.util.List;

/** SqlNode to describe resource type and its path information. */
public class SqlResource extends SqlCall {

    private static final SqlOperator OPERATOR =
            new SqlSpecialOperator("SqlResource", SqlKind.OTHER);

    private final SqlLiteral resourceType;
    private final SqlCharStringLiteral resourcePath;

    public SqlResource(
            SqlParserPos pos, SqlLiteral resourceType, SqlCharStringLiteral resourcePath) {
        super(pos);
        this.resourceType = resourceType;
        this.resourcePath = resourcePath;
    }

    @Nonnull
    @Override
    public SqlOperator getOperator() {
        return OPERATOR;
    }

    @Nonnull
    @Override
    public List<SqlNode> getOperandList() {
        return ImmutableNullableList.of(resourceType, resourcePath);
    }

    public SqlLiteral getResourceType() {
        return resourceType;
    }

    public SqlCharStringLiteral getResourcePath() {
        return resourcePath;
    }

    @Override
    public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
        resourceType.unparse(writer, leftPrec, rightPrec);
        resourcePath.unparse(writer, leftPrec, rightPrec);
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>SoundCity Prototyp: SoundController.m-Dateireferenz</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Hauptseite

Zusätzliche Informationen

Klassen

Dateien

Auflistung der Dateien

Datei-Elemente

SoundController.m-Dateireferenz
#import "SoundController.h"

#import "AudioStreamer.h"

#import <QuartzCore/CoreAnimation.h>

#import <MediaPlayer/MediaPlayer.h>

#import <CFNetwork/CFNetwork.h>

gehe zum Quellcode dieser Datei

Variablen

NSString *const 	PLAYING = @"PLAYING"

NSString *const 	STOPPED = @"STOPPED"

NSString *const 	IDLE = @"IDLE"

NSString *const 	WAITING = @"WAITING"

Variablen-Dokumentation

          NSString* const IDLE = @"IDLE"

Definiert in Zeile 17 der Datei SoundController.m.

          NSString* const PLAYING = @"PLAYING"

Definiert in Zeile 15 der Datei SoundController.m.

          NSString* const STOPPED = @"STOPPED"

Definiert in Zeile 16 der Datei SoundController.m.

          NSString* const WAITING = @"WAITING"

Definiert in Zeile 18 der Datei SoundController.m.

<address style="text-align: right;">Erzeugt am Thu Nov 12 17:19:33 2009 für SoundCity Prototyp von

 1.6.1 </address>


text:
using namespace cv;
using namespace std;

// Mouse Handler Global Variables
Mat image;
Point origin;
Rect selection;
bool selectObject = false, computeHist = false;

// Mouse Handler Function
static void onMouse(int event, int x, int y, int, void*)
{
	if (selectObject)
	{
		selection.x = MIN(x, origin.x);
		selection.y = MIN(y, origin.y);
		selection.width = std::abs(x - origin.x);
		selection.height = std::abs(y - origin.y);
		selection &= Rect(0, 0, image.cols, image.rows);
	}

	switch (event)
	{
	case EVENT_LBUTTONDOWN:
		origin = Point(x, y);
		selection = Rect(x, y, 0, 0);
		selectObject = true;
		break;
	case EVENT_LBUTTONUP:
		selectObject = false;
		if (selection.width > 0 && selection.height > 0)
			computeHist = true;
		break;
	}
}

int main(int argc, char** argv)
{
	// Creating camera capture
	VideoCapture cap;

	// Open the camera
	cap.open(0);

	// Check for error in opening the camera
	if (!cap.isOpened())
	{
		cout << "Could not initialize capturing" << endl;
		return -1;
	}

	// Creating named window and trackbars
	namedWindow("CamShift", 0);
	namedWindow("BackProjection", 0);
	setMouseCallback("CamShift", onMouse, 0);

	// Matrix initialization
	int key;
	Mat frame, disp, hsv, mask, hue, hist, backproj;

	//Get a sample image
	cap >> frame;
	if (frame.empty())
	{
		cout << "Error opening the image" << endl;
		return -1;
	}
	frame.copyTo(disp);
	frame.copyTo(image);

	// Get the selection from the opencv mat
	while (1)
	{
		// Show the selection
		if (selectObject && selection.width > 0 && selection.height > 0)
		{
			frame.copyTo(disp);
			Mat roi(disp, selection);
			bitwise_not(roi, roi);
		}

		// Display the image
		imshow("CamShift", disp);
		key = waitKey(10);
		if (key == 27)
			break;
	}

	// Cleanup
	destroyWindow("CamShift");

	// Convert saved frame to hsv color space
	cvtColor(image, hsv, CV_BGR2HSV);

	// Perform HSV Based Color Extraction based on the sat, val limits
	inRange(hsv, Scalar(0, SMIN, VMIN), Scalar(180, 256, VMAX), mask);

	// Hue extraction parameter initialization
	int ch[] = { 0, 0 };
	hue.create(hsv.size(), hsv.depth());

	// Get the hue channel from the hsv image
	mixChannels(&hsv, 1, &hue, 1, ch, 1);

	// Parameter initialization for computing the histograms
	int hsize = 16;
	float hranges[] = { 0, 180 };
	const float* phranges = hranges;

	// Get the ROIs from the Mask, Hue images
	Mat roi(hue, selection), maskroi(mask, selection);

	// Compute the histogram and normaize the histogram
	calcHist(&roi, 1, 0, maskroi, hist, 1, &hsize, &phranges);
	normalize(hist, hist, 0, 255, NORM_MINMAX);

	// Track Window Initialization
	Rect trackWindow = selection;

	// Floodfill Variables
	Mat objEdge;
	int thresh = 100;
	int sizeThresh = 10;
	vector< vector<Point> > contours;
	vector<Vec4i> hierarchy;
	Scalar color = Scalar(0, 255, 0);

	while (1)
	{
		// Get a new frame
		cap >> frame;
		if (frame.empty())
		{
			cout << "Error getting image from camera" << endl;
			break;
		}
		frame.copyTo(image);

		// Perform color extraction
		cvtColor(image, hsv, CV_BGR2HSV);
		inRange(hsv, Scalar(0, SMIN, VMIN), Scalar(180, 256, VMAX), mask);

		// Get the hue channel
		hue.create(hsv.size(), hsv.depth());
		mixChannels(&hsv, 1, &hue, 1, ch, 1);

		// Get the back projection
		calcBackProject(&hue, 1, 0, hist, backproj, &phranges);
		backproj &= mask;

		RotatedRect trackBox = CamShift(backproj, trackWindow, TermCriteria(TermCriteria::EPS | TermCriteria::COUNT, 10, 1));

		int cols = backproj.cols, rows = backproj.rows;

		if (trackWindow.area() <= 1)
			trackWindow = Rect(0, 0, cols, rows);

		//trackWindow = Rect(Point(trackWindow.x - sizeThresh, trackWindow.y - sizeThresh), Point(trackWindow.x + trackWindow.width + sizeThresh, trackWindow.y + trackWindow.height + sizeThresh)) | Rect(0,0,cols,rows);

		//hierarchy.clear();
		//contours.clear();
		//Mat obj(backproj,trackWindow);
		//Canny(obj, objEdge, thresh, thresh*2, 3);
		//findContours(objEdge, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

		//imshow("Window", obj);
		//imshow("Window: Canny", objEdge);

		//Mat img(image, trackWindow);
		//for (int i = 0; i < 1; i++)
		//drawContours(img, contours, i, color, 2, 8, hierarchy, 0, Point());

		Point2f rect_points[4];
		trackBox.points(rect_points);
		for (int j = 0; j < 4; j++)
			line(image, rect_points[j], rect_points[(j + 1) % 4], color, 1, 8);

		// Display the image
		imshow("CamShift", image);
		imshow("BackProjection", backproj);
		key = waitKey(10);
		if (key == 27)
			break;
	}

	// Safe return from program
	destroyAllWindows();
	return 0;
}


text:
package com.orientechnologies.orient.core.index.hashindex.local;

import com.orientechnologies.common.serialization.types.OBinarySerializer;
import com.orientechnologies.orient.core.storage.cache.OCacheEntry;
import com.orientechnologies.orient.core.storage.impl.local.paginated.base.ODurablePage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWALChangesTree;

import java.io.IOException;

/**
 * @author Andrey Lomakin (a.lomakin-at-orientechnologies.com)
 * @since 4/25/14
 */
public class ONullBucket<V> extends ODurablePage {
  private final OBinarySerializer<V> valueSerializer;

  public ONullBucket(OCacheEntry cacheEntry, OWALChangesTree changesTree, OBinarySerializer<V> valueSerializer, boolean isNew) {
    super(cacheEntry, changesTree);
    this.valueSerializer = valueSerializer;

    if (isNew)
      setByteValue(NEXT_FREE_POSITION, (byte) 0);
  }

  public void setValue(V value) throws IOException {
    setByteValue(NEXT_FREE_POSITION, (byte) 1);

    final int valueSize = valueSerializer.getObjectSize(value);

    final byte[] serializedValue = new byte[valueSize];
    valueSerializer.serializeNativeObject(value, serializedValue, 0);

    setBinaryValue(NEXT_FREE_POSITION + 1, serializedValue);
  }

  public V getValue() {
    if (getByteValue(NEXT_FREE_POSITION) == 0)
      return null;

    return deserializeFromDirectMemory(valueSerializer, NEXT_FREE_POSITION + 1);
  }

  public void removeValue() {
    setByteValue(NEXT_FREE_POSITION, (byte) 0);
  }
}


text:
/**
 * OsCommerceOrderImporter.java
 * Created on 27.07.2008
 * (c) 2005 by "Wolschon Softwaredesign und Beratung".
 *
 *  Permission is granted to use, modify, publish and sub-license this code
 *  as specified in the contract. If nothing else is specified these rights
 *  are given non-exclusively with no restrictions solely to the contractor(s).
 *  If no specified otherwise I reserve the right to use, modify, publish and
 *  sub-license this code to other parties myself.
 *
 * Otherwise, this code is made available under GPLv3 or later.
 *
 * -----------------------------------------------------------
 * major Changes:
 *  27.07.2008 - initial version
 * ...
 *
 */
package biz.wolschon.finance.jgnucash.helper;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * created: 27.07.2008

 *
 * Helper-Class to getch a URL with HTTP-Basic-Auth.
 *
 * @author Marcus Wolschon
 */

public final class HttpFetcher {

    /**
     * Automatically created logger for debug and error-output.
     */
    private static final Log LOGGER = LogFactory.getLog(HttpFetcher.class);

    /**
     * Utility-class with no instances.
     */
    private HttpFetcher() {

    }

    /**
     * Fetch the given URL with http-basic-auth.
     * @param url the URL
     * @param username username
     * @param password password
     * @return the page-content or null
     */
    public static String fetchURL(final URL url, final String username, final String password) {
        StringWriter sw = new StringWriter();

        try {
            PrintWriter  pw = new PrintWriter(sw);
            InputStream content = fetchURLStream(url, username, password);
            BufferedReader in   =
                new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = in.readLine()) != null) {
                pw.println(line);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            LOGGER.error("cannot fetch malformed URL " + url, e);
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("cannot fetch URL " + url, e);
            return null;
        }
        return sw.toString();
    }

    /**
     * Fetch the given URL with http-basic-auth.
     * @param url the URL
     * @param username username
     * @param password password
     * @return the page-content or null
     */
    public static InputStream fetchURLStream(final URL url, final String username, final String password) {

        try {
            String userPassword = username + ":" + password;

            // Encode String
            String encoding = new sun.misc.BASE64Encoder().encode(userPassword.getBytes());

            URLConnection uc = url.openConnection();
            uc.setRequestProperty("Authorization", "Basic " + encoding);
            return uc.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            LOGGER.error("cannot fetch malformed URL " + url, e);
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            LOGGER.error("cannot fetch URL " + url, e);
            return null;
        }
    }

}


text:
package com.vincent.reversechain;

/**
 * Created by Vincent on 5/4/16.
 */
public class Node {
    String value;
    Node next;

    public Node(String value, Node next) {
        this.value = value;
        this.next = next;
    }
}


text:
/**
 * @file
 * @author  Piotr Bartosiewicz (p.bartosiewi@partner.samsung.com)
 * @brief   Unit tests of worker thread
 */

#include "config.hpp"

#include "ut.hpp"

#include "utils/worker.hpp"
#include "utils/latch.hpp"

#include <chrono>
#include <thread>
#include <atomic>

using namespace utils;

BOOST_AUTO_TEST_SUITE(WorkerSuite)

const int unsigned TIMEOUT = 1000;

BOOST_AUTO_TEST_CASE(NoTasks)
{
    Worker::Pointer worker = Worker::create();
}

BOOST_AUTO_TEST_CASE(NoTasksWithSubWorkers)
{
    Worker::Pointer worker = Worker::create();
    Worker::Pointer sub1 = worker->createSubWorker();
    Worker::Pointer sub2 = worker->createSubWorker();
    Worker::Pointer sub3 = sub1->createSubWorker();

    sub1.reset();
    worker.reset();
}

BOOST_AUTO_TEST_CASE(Simple)
{
    Latch done;

    Worker::Pointer worker = Worker::create();
    worker->addTask([&] {
        done.set();
    });

    BOOST_CHECK(done.wait(TIMEOUT));
}

BOOST_AUTO_TEST_CASE(Queue)
{
    std::mutex mutex;
    std::string result;

    Worker::Pointer worker = Worker::create();

    for (int n=0; n<10; ++n) {
        worker->addTask([&, n]{
            std::lock_guard<std::mutex> lock(mutex);
            result += std::to_string(n);
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        });
    }

    worker.reset();

    std::lock_guard<std::mutex> lock(mutex);
    BOOST_CHECK_EQUAL("0123456789", result);
}

BOOST_AUTO_TEST_CASE(ThreadResume)
{
    Latch done;

    const auto task = [&] {
        done.set();
    };

    Worker::Pointer worker = Worker::create();

    worker->addTask(task);

    BOOST_CHECK(done.wait(TIMEOUT));

    // make sure worker thread is in waiting state
    std::this_thread::sleep_for(std::chrono::milliseconds(100));

    worker->addTask(task);

    worker.reset();

    BOOST_CHECK(done.wait(TIMEOUT));
}

BOOST_AUTO_TEST_CASE(SubWorker)
{
    std::mutex mutex;
    std::string result;

    Worker::Pointer worker = Worker::create();
    Worker::Pointer sub1 = worker->createSubWorker();
    Worker::Pointer sub2 = worker->createSubWorker();

    auto addTask = [&](Worker::Pointer w, const std::string& id) {
        w->addTask([&, id]{
            std::lock_guard<std::mutex> lock(mutex);
            result += id;
            std::this_thread::sleep_for(std::chrono::milliseconds(10));
        });
    };

    for (int n=0; n<4; ++n) {
        addTask(worker, "_w" + std::to_string(n));
        addTask(sub1, "_a" + std::to_string(n));
    }

    worker.reset();
    sub1.reset();

    {
        std::lock_guard<std::mutex> lock(mutex);
        BOOST_CHECK_EQUAL("_w0_a0_w1_a1_w2_a2_w3_a3", result);
        result.clear();
    }

    addTask(sub2, "_b0");
    addTask(sub2, "_b1");

    sub2.reset();

    {
        std::lock_guard<std::mutex> lock(mutex);
        BOOST_CHECK_EQUAL("_b0_b1", result);
    }
}

BOOST_AUTO_TEST_CASE(NoCopy)
{
    typedef std::atomic_int Counter;

    struct Task {
        Counter& count;

        Task(Counter& c) : count(c) {}
        Task(const Task& t) : count(t.count) {++count;}
        Task(Task&& r) : count(r.count) {}
        Task& operator=(const Task&) = delete;
        Task& operator=(Task&&) = delete;
        void operator() () const {}

    };

    Counter copyCount(0);

    Worker::Pointer worker = Worker::create();
    worker->addTask(Task(copyCount));
    worker.reset();

    BOOST_CHECK_EQUAL(1, copyCount); // one copy for creating std::function
}

BOOST_AUTO_TEST_SUITE_END()