text:
#ifndef _TBB_arena_slot_H
#define _TBB_arena_slot_H

#include "oneapi/tbb/detail/_config.h"
#include "oneapi/tbb/detail/_utils.h"
#include "oneapi/tbb/detail/_template_helpers.h"
#include "oneapi/tbb/detail/_task.h"

#include "oneapi/tbb/cache_aligned_allocator.h"

#include "misc.h"
#include "mailbox.h"
#include "scheduler_common.h"

#include <atomic>

namespace tbb {
namespace detail {
namespace r1 {

class arena;
class task_group_context;

//--------------------------------------------------------------------------------------------------------
// Arena Slot
//--------------------------------------------------------------------------------------------------------

static d1::task** const EmptyTaskPool  = nullptr;
static d1::task** const LockedTaskPool = reinterpret_cast<d1::task**>(~std::intptr_t(0));

struct alignas(max_nfs_size) arena_slot_shared_state {
    //! Scheduler of the thread attached to the slot
    /** Marks the slot as busy, and is used to iterate through the schedulers belonging to this arena **/
    std::atomic<bool> my_is_occupied;

    // Synchronization of access to Task pool
    /** Also is used to specify if the slot is empty or locked:
         0 - empty
        -1 - locked **/
    std::atomic<d1::task**> task_pool;

    //! Index of the first ready task in the deque.
    /** Modified by thieves, and by the owner during compaction/reallocation **/
    std::atomic<std::size_t> head;
};

struct alignas(max_nfs_size) arena_slot_private_state {
    //! Hint provided for operations with the container of starvation-resistant tasks.
    /** Modified by the owner thread (during these operations). **/
    unsigned hint_for_fifo_stream;

#if __TBB_PREVIEW_CRITICAL_TASKS
    //! Similar to 'hint_for_fifo_stream' but for critical tasks.
    unsigned hint_for_critical_stream;
#endif

    //! Similar to 'hint_for_fifo_stream' but for the resume tasks.
    unsigned hint_for_resume_stream;

    //! Index of the element following the last ready task in the deque.
    /** Modified by the owner thread. **/
    std::atomic<std::size_t> tail;

    //! Capacity of the primary task pool (number of elements - pointers to task).
    std::size_t my_task_pool_size;

    //! Task pool of the scheduler that owns this slot
    // TODO: previously was task**__TBB_atomic, but seems like not accessed on other thread
    d1::task** task_pool_ptr;
};

class arena_slot : private arena_slot_shared_state, private arena_slot_private_state {
    friend class arena;
    friend class outermost_worker_waiter;
    friend class task_dispatcher;
    friend class thread_data;
    friend class nested_arena_context;

    //! The original task dispather associated with this slot
    task_dispatcher* my_default_task_dispatcher;

#if TBB_USE_ASSERT
    void fill_with_canary_pattern ( std::size_t first, std::size_t last ) {
        for ( std::size_t i = first; i < last; ++i )
            poison_pointer(task_pool_ptr[i]);
    }
#else
    void fill_with_canary_pattern ( size_t, std::size_t ) {}
#endif /* TBB_USE_ASSERT */

    static constexpr std::size_t min_task_pool_size = 64;

    void allocate_task_pool( std::size_t n ) {
        std::size_t byte_size = ((n * sizeof(d1::task*) + max_nfs_size - 1) / max_nfs_size) * max_nfs_size;
        my_task_pool_size = byte_size / sizeof(d1::task*);
        task_pool_ptr = (d1::task**)cache_aligned_allocate(byte_size);
        // No need to clear the fresh deque since valid items are designated by the head and tail members.
        // But fill it with a canary pattern in the high vigilance debug mode.
        fill_with_canary_pattern( 0, my_task_pool_size );
    }

public:
    //! Deallocate task pool that was allocated by means of allocate_task_pool.
    void free_task_pool( ) {
        // TODO: understand the assertion and modify
        // __TBB_ASSERT( !task_pool /* TODO: == EmptyTaskPool */, nullptr);
        if( task_pool_ptr ) {
           __TBB_ASSERT( my_task_pool_size, nullptr);
           cache_aligned_deallocate( task_pool_ptr );
           task_pool_ptr = nullptr;
           my_task_pool_size = 0;
        }
    }

    //! Get a task from the local pool.
    /** Called only by the pool owner.
        Returns the pointer to the task or nullptr if a suitable task is not found.
        Resets the pool if it is empty. **/
    d1::task* get_task(execution_data_ext&, isolation_type);

    //! Steal task from slot's ready pool
    d1::task* steal_task(arena&, isolation_type, std::size_t);

    //! Some thread is now the owner of this slot
    void occupy() {
        __TBB_ASSERT(!my_is_occupied.load(std::memory_order_relaxed), nullptr);
        my_is_occupied.store(true, std::memory_order_release);
    }

    //! Try to occupy the slot
    bool try_occupy() {
        return !is_occupied() && my_is_occupied.exchange(true) == false;
    }

    //! Some thread is now the owner of this slot
    void release() {
        __TBB_ASSERT(my_is_occupied.load(std::memory_order_relaxed), nullptr);
        my_is_occupied.store(false, std::memory_order_release);
    }

    //! Spawn newly created tasks
    void spawn(d1::task& t) {
        std::size_t T = prepare_task_pool(1);
        __TBB_ASSERT(is_poisoned(task_pool_ptr[T]), nullptr);
        task_pool_ptr[T] = &t;
        commit_spawned_tasks(T + 1);
        if (!is_task_pool_published()) {
            publish_task_pool();
        }
    }

    bool is_task_pool_published() const {
        return task_pool.load(std::memory_order_relaxed) != EmptyTaskPool;
    }

    bool is_occupied() const {
        return my_is_occupied.load(std::memory_order_relaxed);
    }

    task_dispatcher& default_task_dispatcher() {
        __TBB_ASSERT(my_default_task_dispatcher != nullptr, nullptr);
        return *my_default_task_dispatcher;
    }

    void init_task_streams(unsigned h) {
        hint_for_fifo_stream = h;
#if __TBB_RESUMABLE_TASKS
        hint_for_resume_stream = h;
#endif
#if __TBB_PREVIEW_CRITICAL_TASKS
        hint_for_critical_stream = h;
#endif
    }

#if __TBB_PREVIEW_CRITICAL_TASKS
    unsigned& critical_hint() {
        return hint_for_critical_stream;
    }
#endif
private:
    //! Get a task from the local pool at specified location T.
    /** Returns the pointer to the task or nullptr if the task cannot be executed,
        e.g. proxy has been deallocated or isolation constraint is not met.
        tasks_omitted tells if some tasks have been omitted.
        Called only by the pool owner. The caller should guarantee that the
        position T is not available for a thief. **/
    d1::task* get_task_impl(size_t T, execution_data_ext& ed, bool& tasks_omitted, isolation_type isolation);

    //! Makes sure that the task pool can accommodate at least n more elements
    /** If necessary relocates existing task pointers or grows the ready task deque.
     *  Returns (possible updated) tail index (not accounting for n). **/
    std::size_t prepare_task_pool(std::size_t num_tasks) {
        std::size_t T = tail.load(std::memory_order_relaxed); // mirror
        if ( T + num_tasks <= my_task_pool_size ) {
            return T;
        }

        std::size_t new_size = num_tasks;
        if ( !my_task_pool_size ) {
            __TBB_ASSERT( !is_task_pool_published() && is_quiescent_local_task_pool_reset(), nullptr);
            __TBB_ASSERT( !task_pool_ptr, nullptr);
            if ( num_tasks < min_task_pool_size ) new_size = min_task_pool_size;
            allocate_task_pool( new_size );
            return 0;
        }
        acquire_task_pool();
        std::size_t H =  head.load(std::memory_order_relaxed); // mirror
        d1::task** new_task_pool = task_pool_ptr;;
        __TBB_ASSERT( my_task_pool_size >= min_task_pool_size, nullptr);
        // Count not skipped tasks. Consider using std::count_if.
        for ( std::size_t i = H; i < T; ++i )
            if ( new_task_pool[i] ) ++new_size;
        // If the free space at the beginning of the task pool is too short, we
        // are likely facing a pathological single-producer-multiple-consumers
        // scenario, and thus it's better to expand the task pool
        bool allocate = new_size > my_task_pool_size - min_task_pool_size/4;
        if ( allocate ) {
            // Grow task pool. As this operation is rare, and its cost is asymptotically
            // amortizable, we can tolerate new task pool allocation done under the lock.
            if ( new_size < 2 * my_task_pool_size )
                new_size = 2 * my_task_pool_size;
            allocate_task_pool( new_size ); // updates my_task_pool_size
        }
        // Filter out skipped tasks. Consider using std::copy_if.
        std::size_t T1 = 0;
        for ( std::size_t i = H; i < T; ++i ) {
            if ( new_task_pool[i] ) {
                task_pool_ptr[T1++] = new_task_pool[i];
            }
        }
        // Deallocate the previous task pool if a new one has been allocated.
        if ( allocate )
            cache_aligned_deallocate( new_task_pool );
        else
            fill_with_canary_pattern( T1, tail );
        // Publish the new state.
        commit_relocated_tasks( T1 );
        // assert_task_pool_valid();
        return T1;
    }

    //! Makes newly spawned tasks visible to thieves
    void commit_spawned_tasks(std::size_t new_tail) {
        __TBB_ASSERT (new_tail <= my_task_pool_size, "task deque end was overwritten");
        // emit "task was released" signal
        // Release fence is necessary to make sure that previously stored task pointers
        // are visible to thieves.
        tail.store(new_tail, std::memory_order_release);
    }

    //! Used by workers to enter the task pool
    /** Does not lock the task pool in case if arena slot has been successfully grabbed. **/
    void publish_task_pool() {
        __TBB_ASSERT ( task_pool == EmptyTaskPool, "someone else grabbed my arena slot?" );
        __TBB_ASSERT ( head.load(std::memory_order_relaxed) < tail.load(std::memory_order_relaxed),
                "entering arena without tasks to share" );
        // Release signal on behalf of previously spawned tasks (when this thread was not in arena yet)
        task_pool.store(task_pool_ptr, std::memory_order_release );
    }

    //! Locks the local task pool
    /** Garbles task_pool for the duration of the lock. Requires correctly set task_pool_ptr.
        ATTENTION: This method is mostly the same as generic_scheduler::lock_task_pool(), with
        a little different logic of slot state checks (slot is either locked or points
        to our task pool). Thus if either of them is changed, consider changing the counterpart as well. **/
    void acquire_task_pool() {
        if (!is_task_pool_published()) {
            return; // we are not in arena - nothing to lock
        }
        bool sync_prepare_done = false;
        for( atomic_backoff b;;b.pause() ) {
#if TBB_USE_ASSERT
            // Local copy of the arena slot task pool pointer is necessary for the next
            // assertion to work correctly to exclude asynchronous state transition effect.
            d1::task** tp = task_pool.load(std::memory_order_relaxed);
            __TBB_ASSERT( tp == LockedTaskPool || tp == task_pool_ptr, "slot ownership corrupt?" );
#endif
            d1::task** expected = task_pool_ptr;
            if( task_pool.load(std::memory_order_relaxed) != LockedTaskPool &&
                task_pool.compare_exchange_strong(expected, LockedTaskPool ) ) {
                // We acquired our own slot
                break;
            } else if( !sync_prepare_done ) {
                // Start waiting
                sync_prepare_done = true;
            }
            // Someone else acquired a lock, so pause and do exponential backoff.
        }
        __TBB_ASSERT( task_pool.load(std::memory_order_relaxed) == LockedTaskPool, "not really acquired task pool" );
    }

    //! Unlocks the local task pool
    /** Restores task_pool munged by acquire_task_pool. Requires
        correctly set task_pool_ptr. **/
    void release_task_pool() {
        if ( !(task_pool.load(std::memory_order_relaxed) != EmptyTaskPool) )
            return; // we are not in arena - nothing to unlock
        __TBB_ASSERT( task_pool.load(std::memory_order_relaxed) == LockedTaskPool, "arena slot is not locked" );
        task_pool.store( task_pool_ptr, std::memory_order_release );
    }

    //! Locks victim's task pool, and returns pointer to it. The pointer can be nullptr.
    /** Garbles victim_arena_slot->task_pool for the duration of the lock. **/
    d1::task** lock_task_pool() {
        d1::task** victim_task_pool;
        for ( atomic_backoff backoff;; /*backoff pause embedded in the loop*/) {
            victim_task_pool = task_pool.load(std::memory_order_relaxed);
            // Microbenchmarks demonstrated that aborting stealing attempt when the
            // victim's task pool is locked degrade performance.
            // NOTE: Do not use comparison of head and tail indices to check for
            // the presence of work in the victim's task pool, as they may give
            // incorrect indication because of task pool relocations and resizes.
            if (victim_task_pool == EmptyTaskPool) {
                break;
            }
            d1::task** expected = victim_task_pool;
            if (victim_task_pool != LockedTaskPool && task_pool.compare_exchange_strong(expected, LockedTaskPool) ) {
                // We've locked victim's task pool
                break;
            }
            // Someone else acquired a lock, so pause and do exponential backoff.
            backoff.pause();
        }
        __TBB_ASSERT(victim_task_pool == EmptyTaskPool ||
                    (task_pool.load(std::memory_order_relaxed) == LockedTaskPool &&
                    victim_task_pool != LockedTaskPool), "not really locked victim's task pool?");
        return victim_task_pool;
    }

    //! Unlocks victim's task pool
    /** Restores victim_arena_slot->task_pool munged by lock_task_pool. **/
    void unlock_task_pool(d1::task** victim_task_pool) {
        __TBB_ASSERT(task_pool.load(std::memory_order_relaxed) == LockedTaskPool, "victim arena slot is not locked");
        __TBB_ASSERT(victim_task_pool != LockedTaskPool, nullptr);
        task_pool.store(victim_task_pool, std::memory_order_release);
    }

#if TBB_USE_ASSERT
    bool is_local_task_pool_quiescent() const {
        d1::task** tp = task_pool.load(std::memory_order_relaxed);
        return tp == EmptyTaskPool || tp == LockedTaskPool;
    }

    bool is_quiescent_local_task_pool_empty() const {
        __TBB_ASSERT(is_local_task_pool_quiescent(), "Task pool is not quiescent");
        return head.load(std::memory_order_relaxed) == tail.load(std::memory_order_relaxed);
    }

    bool is_quiescent_local_task_pool_reset() const {
        __TBB_ASSERT(is_local_task_pool_quiescent(), "Task pool is not quiescent");
        return head.load(std::memory_order_relaxed) == 0 && tail.load(std::memory_order_relaxed) == 0;
    }
#endif // TBB_USE_ASSERT

    //! Leave the task pool
    /** Leaving task pool automatically releases the task pool if it is locked. **/
    void leave_task_pool() {
        __TBB_ASSERT(is_task_pool_published(), "Not in arena");
        // Do not reset my_arena_index. It will be used to (attempt to) re-acquire the slot next time
        __TBB_ASSERT(task_pool.load(std::memory_order_relaxed) == LockedTaskPool, "Task pool must be locked when leaving arena");
        __TBB_ASSERT(is_quiescent_local_task_pool_empty(), "Cannot leave arena when the task pool is not empty");
        // No release fence is necessary here as this assignment precludes external
        // accesses to the local task pool when becomes visible. Thus it is harmless
        // if it gets hoisted above preceding local bookkeeping manipulations.
        task_pool.store(EmptyTaskPool, std::memory_order_relaxed);
    }

    //! Resets head and tail indices to 0, and leaves task pool
    /** The task pool must be locked by the owner (via acquire_task_pool).**/
    void reset_task_pool_and_leave() {
        __TBB_ASSERT(task_pool.load(std::memory_order_relaxed) == LockedTaskPool, "Task pool must be locked when resetting task pool");
        tail.store(0, std::memory_order_relaxed);
        head.store(0, std::memory_order_relaxed);
        leave_task_pool();
    }

    //! Makes relocated tasks visible to thieves and releases the local task pool.
    /** Obviously, the task pool must be locked when calling this method. **/
    void commit_relocated_tasks(std::size_t new_tail) {
        __TBB_ASSERT(is_local_task_pool_quiescent(), "Task pool must be locked when calling commit_relocated_tasks()");
        head.store(0, std::memory_order_relaxed);
        // Tail is updated last to minimize probability of a thread making arena
        // snapshot being misguided into thinking that this task pool is empty.
        tail.store(new_tail, std::memory_order_release);
        release_task_pool();
    }
};

} // namespace r1
} // namespace detail
} // namespace tbb

#endif // __TBB_arena_slot_H

redpajama_set_name: RedPajamaGithub


text:
namespace google {
    namespace protobuf {
        namespace io {
            class Printer;             // printer.h
        }
    }

    namespace protobuf {
        namespace compiler {
            namespace swift {

                class EnumGenerator {
                public:
                    explicit EnumGenerator(const EnumDescriptor* descriptor);
                    ~EnumGenerator();

                    void GenerateSource(io::Printer* printer);
                    void GenerateDescription(io::Printer* printer);
                    void GenerateCaseFields(io::Printer* printer);

                private:
                    const EnumDescriptor* descriptor_;
                    void GenerateRawRepresentable(io::Printer* printer);
                    void GenerateInit(io::Printer* printer);
                    void GenerateMethodThrow(io::Printer* printer);
                    void GenerateHash(io::Printer* printer);
                    vector<const EnumValueDescriptor*> canonical_values_;

                    struct Alias {
                        const EnumValueDescriptor* value;
                        const EnumValueDescriptor* canonical_value;
                    };
                    vector<Alias> aliases_;

                    GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumGenerator);
                };

            }  // namespace swift
        }  // namespace compiler
    }  // namespace protobuf
}  // namespace google

#endif // swift_ENUM_H


text:
package com.example.david.crudrealm.Entidades;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.RealmClass;
import io.realm.annotations.Required;

/**
 * Created by david on 1/03/16.
 */
public class Post extends RealmObject {
    @PrimaryKey
    private int userId;
    @Required
    private  String title;
    @Required
    private String body;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

}


text:
(function(window, document, undefined) {
	"use strict"
	var canvas = document.getElementById("canvas"),
		btnsContainer = document.getElementById("btnsContainer"),
		lineColor = "black",
		ctx = canvas.getContext("2d");
	init();
	function init() { //初始化
		initCanvasSize(canvas, btnsContainer);
		drawBorder(ctx);
		bindEvent(ctx, canvas);
		bindBtnEvent(canvas, ctx);
	}
	function initCanvasSize(canvas, btnsContainer) { //根据屏幕高宽,初始化canvas大小
		var w = Math.min(600, window.innerWidth - 20),
			h = w;
		canvas.width = w;
		canvas.height = h;
		btnsContainer.style.width = w + "px";
	}
	function drawBorder(ctx) { //绘制写字的边框线
		ctx.save();
		ctx.beginPath();
		ctx.strokeStyle = "rgb(230,11,9)"
		ctx.lineWidth = 5;
		ctx.strokeRect(0, 0, canvas.width, canvas.height);
		drawDottedLine(ctx, {
			x: 0,
			y: 0
		}, {
			x: canvas.width,
			y: canvas.height
		});
		drawDottedLine(ctx, {
			x: 0,
			y: canvas.height
		}, {
			x: canvas.width,
			y: 0
		});
		drawDottedLine(ctx, {
			x: canvas.width / 2,
			y: 0
		}, {
			x: canvas.width / 2,
			y: canvas.height
		});
		drawDottedLine(ctx, {
			x: 0,
			y: canvas.height / 2
		}, {
			x: canvas.width,
			y: canvas.height / 2
		});
		ctx.closePath();
		ctx.restore();
		function drawDottedLine(ctx, startPoint, endPoint) { //绘制虚线
			var defaultWidth = 20,
				defaultSpacing = 3, //默认短线的长度为30,线段的间距为10
				angle = Math.atan(Math.abs(endPoint.x - startPoint.x) / Math.abs(endPoint.y - startPoint.y)), //获取角度值
				lineSize = (angle == 0) ?
				Math.ceil(Math.abs(endPoint.y - startPoint.y) / (defaultWidth + defaultSpacing)) :
				Math.ceil((Math.abs(endPoint.x - startPoint.x) / Math.sin(angle)) / (defaultWidth + defaultSpacing));
			var xDir = endPoint.x >= startPoint.x ? 1 : -1,
				yDir = endPoint.y >= startPoint.y ? 1 : -1,
				xAdd = xDir * (defaultWidth + defaultSpacing) * Math.sin(angle),
				yAdd = yDir * (defaultWidth + defaultSpacing) * Math.cos(angle),
				firstStart = startPoint,
				firstEnd = {
					x: startPoint.x + xDir * defaultWidth * Math.sin(angle),
					y: startPoint.y + yDir * defaultWidth * Math.cos(angle)
				};
			for (var i = 0; i < lineSize; i++) {
				ctx.moveTo(firstStart.x + i * xAdd, firstStart.y + i * yAdd);
				ctx.lineWidth = 1;
				ctx.lineTo(firstEnd.x + i * xAdd, firstEnd.y + i * yAdd);
				ctx.stroke();
			}
		}
	}
	function bindEvent(ctx, canvas) { //绑定事件
		var canWrite = false,
			lastTamp = 0,
			lastPos = {
				x: 0,
				y: 0
			},
			lastLineWidth = 0,
			cbox = canvas.getBoundingClientRect();
		init();
		function init() {
			if (isMobile())
				bindMobileEvent();
			else
				bindPcEvent();
		}
		function bindPcEvent() { //绑定PC事件
			canvas.onmousedown = function(e) {
				e.preventDefault();
				strokeStart(e.clientX, e.clientY);
			}
			canvas.onmouseup = function(e) {
				e.preventDefault();
				strokeEnd();
			}
			canvas.onmousemove = function(e) {
				e.preventDefault();
				if (!canWrite) return;
				stroking(e.clientX, e.clientY);
			}
			canvas.onmouseout = function(e) {
				e.preventDefault();
				strokeEnd();
			}
		}
		function bindMobileEvent() { //绑定移动事件
			canvas.addEventListener("touchstart", function(e) {
				e.preventDefault();
				strokeStart(e.touches[0].pageX, e.touches[0].pageY);
			});
			canvas.addEventListener("touchmove", function(e) {
				e.preventDefault();
				stroking(e.touches[0].pageX, e.touches[0].pageY);
			});
			canvas.addEventListener("touchend", function(e) {
				e.preventDefault();
				strokeEnd();
			});
		}
		function strokeStart(x, y) { //绘制开始
			canWrite = true;
			lastPos = windowToCanvas(x, y);
			lastTamp = Date.now();
		}
		function stroking(x, y) { //绘制中
			var curPos = windowToCanvas(x, y),
				curTamp = Date.now(),
				moveDistance = Math.sqrt((curPos.x - lastPos.x) * (curPos.x - lastPos.x) + (curPos.y - lastPos.y) * (curPos.y - lastPos.y)),
				ts = curTamp - lastTamp;
			ctx.beginPath();
			ctx.lineWidth = getLineWidth(moveDistance / ts);
			ctx.strokeStyle = lineColor;
			ctx.lineCap = "round";
			ctx.lineJoin = "round";
			ctx.moveTo(lastPos.x, lastPos.y);
			ctx.lineTo(curPos.x, curPos.y);
			ctx.stroke();
			ctx.closePath();
			lastPos = curPos;
			lastTamp = curTamp;
		}
		function strokeEnd() { //绘制结束
			canWrite = false;
		}
		function isMobile() { //判断是否是移动设备
			var userAgentInfo = navigator.userAgent,
				Agents = ["iPhone", "iPad", "iPod", "Android"];
			for (var i = 0, item; item = Agents[i++];) {
				if (userAgentInfo.indexOf(item) >= 0) return true;
			}
			return false;
		}
		function windowToCanvas(x, y) { //window坐标转canvas坐标
			return {
				x: Math.round(x - cbox.left),
				y: Math.round(y - cbox.top)
			}
		}
		function getLineWidth(v) { //根据速度获取绘制线条的宽度
			var maxLineWidth = 20,
				minLineWidth = 1,
				maxV = 10,
				minV = 0.1;
			return (function() {
				var retLineWidth;
				if (v >= maxV) {
					retLineWidth = minLineWidth;
				} else if (v <= minV) {
					retLineWidth = maxLineWidth
				} else {
					retLineWidth = maxLineWidth - (v - minV) / (maxV - minV) * (maxLineWidth - minLineWidth);
				}
				return lastLineWidth = (retLineWidth * 2 / 5 + lastLineWidth * 3 / 5);
			})();
		}
	}
	function bindBtnEvent(canvas, ctx) { //绑定按钮事件
		var clearBtn = document.getElementsByClassName("clearBtn")[0];
		clearBtn.onclick = function() {
			ctx.clearRect(0, 0, canvas.width, canvas.height);
			drawBorder(ctx);
		}
		var colorBtns = document.getElementsByClassName("colorBtn");
		for (var index = 0, item; item = colorBtns[index++];) {
			item.onclick = function() {
				removeClassCur();
				this.className += " " + "cur";
				lineColor = this.getAttribute("data-color");
			}
		}
		function removeClassCur() {
			for (var i = 0, obj; obj = colorBtns[i++];) {
				obj.className = obj.className.replace(new RegExp("(\\s|^)" + "cur" + "(\\s|$)"), " ");
			}
		}
	}
})(window, document)


text:
layout:     post
title:      "Jdk1.8在CentOS7中的安装与配置"
date:       2015-06-05 12:00:00
author:     "Mrchor"
header-img: "img/post-bg-2015.jpg"
catalog:	true
tags:	JDK CentOS7
---

> "这就是我,一个低调的作者。"

自从2014年3月19日甲骨文公司发布Java 8.0的正式版以来,面向对象的Java语言不仅朝着一个更好的方向发展,而且吸取了当前比较流行的函数式编程的特性——Java 8.0加入了函数式编程的特点。可以说是Java 8比Java 7有一个更好的性质。今天我将为大家演示一下Jdk 8在CentOS 7的安装与配置:

## 一、前期准备

环境:最小安装的CentOS 7(虚拟机安装的新版的centos系统,与6有一些配置文件上的差异),提前装好了lrssz工具(不会安装的,可以参看我的另一篇随笔——lrssz的安装)。

#### a)         首先从官网上下载Jdk 8 for Linux x64到window下。

#### b)         我这边用的最小安装,所以没有安装centos自带的openjdk,如果你安装时,不是最小安装的话,可能集成了系统的openjdk,所以我们先要删除自带的openjdk,具体步骤如下:

###### 1)       在系统终端输入:rpm -qa | grep java,如果有openjdk的话,会出现类似于XXXX_openjdk_XXX的信息

###### 2)       删除openjdk,在终端输入:rpm -e –-nodeps XXXX_openjdk_XXX 。即可删除自带的openjdk。

注意:上面这两步可以一次性完成,而且很简单哦!

	rpm -e --nodeps `rpm -qa | grep java`

## 二、Jdk的安装

#### a)         我们登录超级用户,在超级用户目录root下建立一个目录app:

	su root  #然后输入密码

	mkdir app

#### b)         我们进入app,将下载好的jdk压缩包导入centos:

	cd app

	rz   #使用rz命令将jdk压缩包从window导入centos当下目录app中

#### c)         解压jdk压缩包

	tar –xzvf jdk-8u45-linux-x64.gz

#### d)         解压后的jdk的文件夹名字为jdk1.8.0_45,我们把它改为jdk1.8:

	mv jdk1.8.0_45/ jdk1.8/

#### e)         进入jdk文件夹,获取目录绝对路径(我的绝对路径是:/root/app/jdk1.8):

	cd jdk1.8

	pwd

三、jdk的配置

a)         使用vim命令打开系统的环境变量配置文件:

	vi /etc/profile

b)         在profile文件最后加入:

	## JAVA

	export JAVA_HOME=jdk的绝对路径(我的是:/root/app/jdk1.8)

	export PATH=$PATH:$JAVA_HOME/bin

## 四、配置验证

#### a)         首先,我们输入java –version,会得到:

	java version "1.8.0_45"

	Java(TM) SE Runtime Environment (build 1.8.0_45-b14)

	Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)

#### b)         我们再输入javac,会得出:

	Usage: javac <options> <source files>

	where possible options include:

	 -g                         Generate all debugging info

	 -g:none                    Generate no debugging info

 	-g:{lines,vars,source}     Generate only some debugging info

	-nowarn                    Generate no warnings

	  -verbose                   Output messages about what the compiler is doing

	  -deprecation               Output source locations where deprecated APIs are used

 	 -classpath <path>          Specify where to find user class files and annotation processors

	-cp <path>                 Specify where to find user class files and annotation processors

	-sourcepath <path>         Specify where to find input source files

	-bootclasspath <path>      Override location of bootstrap class files

	-extdirs <dirs>            Override location of installed extensions

	-endorseddirs <dirs>       Override location of endorsed standards path

	-proc:{none,only}          Control whether annotation processing and/or compilation is done.

	-processor <class1>[,<class2>,<class3>...] Names of the annotation processors to run; bypasses default discovery process

	-processorpath <path>      Specify where to find annotation processors

	-parameters                Generate metadata for reflection on method parameters

	-d <directory>             Specify where to place generated class files

	-s <directory>             Specify where to place generated source files

	-h <directory>             Specify where to place generated native header files

	-implicit:{none,class}     Specify whether or not to generate class files for implicitly referenced files

	-encoding <encoding>       Specify character encoding used by source files

	-source <release>          Provide source compatibility with specified release

	-target <release>          Generate class files for specific VM version

	-profile <profile>         Check that API used is available in the specified profile

	-version                   Version information

	-help                      Print a synopsis of standard options

	-Akey[=value]              Options to pass to annotation processors

	-X                         Print a synopsis of nonstandard options

	-J<flag>                   Pass <flag> directly to the runtime system

	-Werror                    Terminate compilation if warnings occur

	@<filename>                Read options and filenames from file

#### c)         如果得到以上两步正确结果的话,恭喜你,你的jdk8就已经配置好了。


text:
package de.otto.edison.hal;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.Test;

import java.util.List;

import static de.otto.edison.hal.Link.*;
import static de.otto.edison.hal.LinkPredicates.*;
import static de.otto.edison.hal.Links.emptyLinks;
import static de.otto.edison.hal.Links.linkingTo;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

public class LinksTest {

    @Test
    public void shouldCreateEmptyLinks() {
        Links links = emptyLinks();
        assertThat(links.isEmpty(), is(true));
    }

    @Test
    public void shouldCreateLinks() {
        final Links links = linkingTo().self("http://example.org").build();
        assertThat(links.getLinkBy("self").isPresent(), is(true));
        assertThat(links.getLinkBy("self").get().getRel(), is("self"));
        assertThat(links.getLinkBy("self").get().getHref(), is("http://example.org"));
    }

    @Test
    public void shouldCreateMultipleLinks() {
        final Links links = linkingTo()
                .self("http://example.org/items/42")
                .single(collection("http://example.org/items"))
                .build();
        assertThat(links.getLinkBy("self").isPresent(), is(true));
        assertThat(links.getLinkBy("collection").isPresent(), is(true));
    }

    @Test
    public void shouldCreateMultipleLinksFromList() {
        final Links links = linkingTo()
                .single(asList(self("http://example.org/items")))
                .array(asList(
                    item("http://example.org/items/1"),
                    item("http://example.org/items/2"))

                ).build();
        assertThat(links.getLinkBy("self").isPresent(), is(true));
        assertThat(links.getLinkBy("item").isPresent(), is(true));
        assertThat(links.getLinksBy("item"), hasSize(2));
    }

    @Test
    public void shouldCreateMultipleLinksUsingBuilder() {
        final Links links = linkingTo()
                .self("http://example.org/items")
                .array(
                        item("http://example.org/items/1"),
                        item("http://example.org/items/2"))
                .build();
        assertThat(links.getLinkBy("self").isPresent(), is(true));
        assertThat(links.getLinkBy("item").isPresent(), is(true));
        assertThat(links.getLinksBy("item"), hasSize(2));
    }

    @Test
    public void shouldGetFirstLink() {
        final Links links = linkingTo()
                .item("http://example.org/items/42")
                .item("http://example.org/items/44")
                .build();
        assertThat(links.getLinkBy("item").isPresent(), is(true));
        assertThat(links.getLinkBy("item").get().getHref(), is("http://example.org/items/42"));
    }

    @Test
    public void shouldGetFirstLinkMatchingTypeAndProfile() {
        final Links links = linkingTo()
                .array(
                        linkBuilder("item", "http://example.org/items/42").build(),
                        linkBuilder("item", "http://example.org/items/42").withType("text/plain").withProfile("myprofile").build(),
                        linkBuilder("item", "http://example.org/items/42").withType("text/html").withProfile("THEprofile").build(),
                        linkBuilder("item", "http://example.org/items/42").withType("THEtype").withProfile("THEprofile").build())
                .build();
        assertThat(links.getLinkBy("item", havingType("THEtype").and(havingProfile("THEprofile"))).isPresent(), is(true));
        assertThat(links.getLinkBy("item", havingType("THEtype").and(havingProfile("THEprofile"))).get().getHref(), is("http://example.org/items/42"));
        assertThat(links.getLinkBy("item", havingType("text/plain")).get().getProfile(), is("myprofile"));
        assertThat(links.getLinkBy("item", havingProfile("THEprofile")).get().getType(), is("text/html"));
    }

    @Test
    public void shouldGetEmptyLinkForUnknownRel() {
        final Links links = emptyLinks();
        assertThat(links.getLinkBy("item").isPresent(), is(false));
    }

    @Test
    public void shouldGetEmptyLinkForFilteredUnknownRel() {
        final Links links = emptyLinks();
        assertThat(links.getLinkBy("item", havingType("text/plain")).isPresent(), is(false));
    }

    @Test
    public void shouldGetEmptyLinkForFilteredLink() {
        final Links links = linkingTo()
                .item("http://example.org/items/42")
                .build();
        assertThat(links.getLinkBy("item", havingType("text/plain")).isPresent(), is(false));
    }

    @Test
    public void shouldGetAllLinks() {
        final Links links = linkingTo()
                .item("http://example.org/items/42")
                .item("http://example.org/items/44")
                .build();
        assertThat(links.getLinksBy("item"), hasSize(2));
        assertThat(links.getLinksBy("item").get(0).getHref(), is("http://example.org/items/42"));
        assertThat(links.getLinksBy("item").get(1).getHref(), is("http://example.org/items/44"));
    }

    @Test
    public void shouldRemoveLinks() {
        final Links links = linkingTo()
                .item("http://example.org/items/42")
                .item("http://example.org/items/44")
                .build();
        links.remove("item");
        links.remove("does-not-exist");
        assertThat(links.isEmpty(), is(true));
    }

    @Test
    public void shouldGetLinksMatchingName() {
        final Links links = linkingTo()
                .array(
                        linkBuilder("item", "http://example.org/items/42").withName("Foo").withType("text/html").build(),
                        linkBuilder("item", "http://example.org/items/42").withName("Foo").build(),
                        linkBuilder("item", "http://example.org/items/42").withName("Bar").build())
                .build();
        assertThat(links.getLinksBy("item", havingName("Foo")), contains(
                linkBuilder("item", "http://example.org/items/42").withName("Foo").withType("text/html").build(),
                linkBuilder("item", "http://example.org/items/42").withName("Foo").build()));
        assertThat(links.getLinksBy("item", havingName("Foo").and(havingType("text/html"))), contains(
                linkBuilder("item", "http://example.org/items/42").withName("Foo").withType("text/html").build()));
    }

    @Test
    public void shouldGetLinksMatchingNameOrEmpty() {
        final Links links = linkingTo()
                .array(
                        linkBuilder("item", "http://example.org/items/41").build(),
                        linkBuilder("item", "http://example.org/items/42").withName("Foo").build(),
                        linkBuilder("item", "http://example.org/items/43").withName("Bar").build())
                .build();
        assertThat(links.getLinksBy("item", optionallyHavingName("Foo")), contains(
                linkBuilder("item", "http://example.org/items/41").build(),
                linkBuilder("item", "http://example.org/items/42").withName("Foo").build()));
    }

    @Test
    public void shouldGetAllLinkMatchingTypeAndProfile() {
        final Links links = linkingTo()
                .array(
                        linkBuilder("item", "http://example.org/items/42").build(),
                        linkBuilder("item", "http://example.org/items/42").withType("text/plain").withProfile("myprofile").build(),
                        linkBuilder("item", "http://example.org/items/42").withType("text/html").withProfile("THEprofile").build(),
                        linkBuilder("item", "http://example.org/items/42").withType("THEtype").withProfile("THEprofile").build())
                .build();
        assertThat(links.getLinksBy("item", havingType("THEtype").and(havingProfile("THEprofile"))).get(0).getHref(), is("http://example.org/items/42"));
        assertThat(links.getLinksBy("item", havingType("text/plain")).get(0).getProfile(), is("myprofile"));
        assertThat(links.getLinksBy("item", havingProfile("THEprofile")).get(0).getType(), is("text/html"));
    }

    @Test
    public void shouldStreamAllLinks() {
        final Links links = linkingTo().single(
                link("foo", "http://example.org/foo"),
                link("bar", "http://example.org/bar")).build();
        assertThat(links.stream().count(), is(2L));
    }

    @Test
    public void shouldGetAllLinkrelations() {
        final Links links = linkingTo().array(
                link("foo", "http://example.org/foo"),
                link("bar", "http://example.org/bar")).build();
        assertThat(links.getRels(), contains("foo", "bar"));
    }

    @Test
    public void shouldGetEmptyListForUnknownRel() {
        final Links links = emptyLinks();
        assertThat(links.getLinksBy("item"), hasSize(0));
    }

    @Test
    public void shouldGetCuriedLinksFromFullRel() throws JsonProcessingException {
        final Links links = linkingTo()
                .curi("o", "http://spec.otto.de/rels/{rel}")
                .array(link("o:product", "http://example.org/products/42"),
                link("o:product", "http://example.org/products/44")).build();
        final List<String> productHrefs = links.getLinksBy("http://spec.otto.de/rels/product")
                .stream()
                .map(Link::getHref)
                .collect(toList());
        assertThat(productHrefs, contains("http://example.org/products/42","http://example.org/products/44"));
    }

    @Test
    public void shouldGetCuriedLinksFromFullRelWithPredicate() throws JsonProcessingException {
        final Links links = linkingTo()
                .curi("o", "http://spec.otto.de/rels/{rel}")
                .array(
                linkBuilder("o:product", "http://example.org/products/42").withName("First").build(),
                linkBuilder("o:product", "http://example.org/products/44").withName("Second").build()).build();
        final List<String> productHrefs = links.getLinksBy("http://spec.otto.de/rels/product", havingName("Second"))
                .stream()
                .map(Link::getHref)
                .collect(toList());
        assertThat(productHrefs, contains("http://example.org/products/44"));

    }

    @Test
    public void shouldGetCuriedLinksFromCuriedRel() throws JsonProcessingException {
        final Links links = linkingTo()
                .curi("o", "http://spec.otto.de/rels/{rel}")
                .array(link("o:product", "http://example.org/products/42"))
                .array(link("o:product", "http://example.org/products/44"))
                .build();
        final List<String> productHrefs = links.getLinksBy("o:product")
                .stream()
                .map(Link::getHref)
                .collect(toList());
        assertThat(productHrefs, contains("http://example.org/products/42","http://example.org/products/44"));
    }

    @Test
    public void shouldGetCuriedLinksFromCuriedRelWithPredicate() throws JsonProcessingException {
        final Links links = linkingTo()
                .curi("o", "http://spec.otto.de/rels/{rel}")
                .array(
                        linkBuilder("o:product", "http://example.org/products/42").withName("First").build(),
                        linkBuilder("o:product", "http://example.org/products/44").withName("Second").build())
                .build();
        final List<String> productHrefs = links.getLinksBy("o:product", havingName("Second"))
                .stream()
                .map(Link::getHref)
                .collect(toList());
        assertThat(productHrefs, contains("http://example.org/products/44"));

    }

    @Test
    public void shouldReplaceFullRelsWithCuriedRels() throws JsonProcessingException {
        final Links links = linkingTo()
                .curi("o", "http://spec.otto.de/rels/{rel}")
                .array(
                        link("http://spec.otto.de/rels/product", "http://example.org/products/42"),
                        link("http://spec.otto.de/rels/product", "http://example.org/products/44"))
                .build();
        final List<String> productHrefs = links.getLinksBy("o:product")
                .stream()
                .map(Link::getHref)
                .collect(toList());
        assertThat(productHrefs, contains("http://example.org/products/42","http://example.org/products/44"));
    }

    @Test
    public void shouldReplaceFullRelsWithCuriedRelsAfterConstruction() throws JsonProcessingException {
        final Links links = linkingTo()
                .array(
                        link("http://spec.otto.de/rels/product", "http://example.org/products/42"),
                        link("http://spec.otto.de/rels/product", "http://example.org/products/44"))
                .curi("o", "http://spec.otto.de/rels/{rel}")
                .build();
        final List<String> productHrefs = links.getLinksBy("o:product")
                .stream()
                .map(Link::getHref)
                .collect(toList());
        assertThat(productHrefs, contains("http://example.org/products/42","http://example.org/products/44"));
    }

    @Test
    public void shouldIgnoreMissingCuries() throws JsonProcessingException {
        final Links links = linkingTo().array(
                link("o:product", "http://example.org/products/42"),
                link("o:product", "http://example.org/products/44"))
                .build();
        final List<String> productHrefs = links.getLinksBy("o:product")
                .stream()
                .map(Link::getHref)
                .collect(toList());
        assertThat(productHrefs, contains("http://example.org/products/42","http://example.org/products/44"));
    }

}


text:
#import <iWorkImport/KNSlideExporter.h>

#import "TSKImageExporter-Protocol.h"

// Not exported
@interface KNPreviewExporter : KNSlideExporter <TSKImageExporter>
{
}

- (void)setup;
@property(nonatomic) _Bool scaleToFit;
@property(nonatomic) unsigned long long height;
@property(nonatomic) unsigned long long width;
- (id)p_renderingExporterDelegate;

@end


text:
A Naive-Bayes Classifier for Swift

Swift port of https://github.com/ttezel/bayes project

## Instalation
Just add the `Classifier.swift` file into your project (nothing fancy)

## Usage

## Notes
* This project assumes the usage of SwiftyJSON project https://github.com/SwiftyJSON/SwiftyJSON