text:
use std::cell::UnsafeCell;
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ptr;
use std::sync::atomic::{self, AtomicPtr, AtomicUsize, Ordering};
use std::time::Instant;

use crossbeam_utils::{Backoff, CachePadded};

use crate::context::Context;
use crate::err::{RecvTimeoutError, SendTimeoutError, TryRecvError, TrySendError};
use crate::select::{Operation, SelectHandle, Selected, Token};
use crate::waker::SyncWaker;

// TODO(stjepang): Once we bump the minimum required Rust version to 1.28 or newer, re-apply the
// following changes by @kleimkuhler:
//
// 1. https://github.com/crossbeam-rs/crossbeam-channel/pull/100
// 2. https://github.com/crossbeam-rs/crossbeam-channel/pull/101

// Bits indicating the state of a slot:
// * If a message has been written into the slot, `WRITE` is set.
// * If a message has been read from the slot, `READ` is set.
// * If the block is being destroyed, `DESTROY` is set.
const WRITE: usize = 1;
const READ: usize = 2;
const DESTROY: usize = 4;

// Each block covers one "lap" of indices.
const LAP: usize = 32;
// The maximum number of messages a block can hold.
const BLOCK_CAP: usize = LAP - 1;
// How many lower bits are reserved for metadata.
const SHIFT: usize = 1;
// Has two different purposes:
// * If set in head, indicates that the block is not the last one.
// * If set in tail, indicates that the channel is disconnected.
const MARK_BIT: usize = 1;

/// A slot in a block.
struct Slot<T> {
    /// The message.
    msg: UnsafeCell<MaybeUninit<T>>,

    /// The state of the slot.
    state: AtomicUsize,
}

impl<T> Slot<T> {
    /// Waits until a message is written into the slot.
    fn wait_write(&self) {
        let backoff = Backoff::new();
        while self.state.load(Ordering::Acquire) & WRITE == 0 {
            backoff.snooze();
        }
    }
}

/// A block in a linked list.
///
/// Each block in the list can hold up to `BLOCK_CAP` messages.
struct Block<T> {
    /// The next block in the linked list.
    next: AtomicPtr<Block<T>>,

    /// Slots for messages.
    slots: [Slot<T>; BLOCK_CAP],
}

impl<T> Block<T> {
    /// Creates an empty block.
    fn new() -> Block<T> {
        // SAFETY: This is safe because:
        //  [1] `Block::next` (AtomicPtr) may be safely zero initialized.
        //  [2] `Block::slots` (Array) may be safely zero initialized because of [3, 4].
        //  [3] `Slot::msg` (UnsafeCell) may be safely zero initialized because it
        //       holds a MaybeUninit.
        //  [4] `Slot::state` (AtomicUsize) may be safely zero initialized.
        unsafe { MaybeUninit::zeroed().assume_init() }
    }

    /// Waits until the next pointer is set.
    fn wait_next(&self) -> *mut Block<T> {
        let backoff = Backoff::new();
        loop {
            let next = self.next.load(Ordering::Acquire);
            if !next.is_null() {
                return next;
            }
            backoff.snooze();
        }
    }

    /// Sets the `DESTROY` bit in slots starting from `start` and destroys the block.
    unsafe fn destroy(this: *mut Block<T>, start: usize) {
        // It is not necessary to set the `DESTROY` bit in the last slot because that slot has
        // begun destruction of the block.
        for i in start..BLOCK_CAP - 1 {
            let slot = (*this).slots.get_unchecked(i);

            // Mark the `DESTROY` bit if a thread is still using the slot.
            if slot.state.load(Ordering::Acquire) & READ == 0
                && slot.state.fetch_or(DESTROY, Ordering::AcqRel) & READ == 0
            {
                // If a thread is still using the slot, it will continue destruction of the block.
                return;
            }
        }

        // No thread is using the block, now it is safe to destroy it.
        drop(Box::from_raw(this));
    }
}

/// A position in a channel.
#[derive(Debug)]
struct Position<T> {
    /// The index in the channel.
    index: AtomicUsize,

    /// The block in the linked list.
    block: AtomicPtr<Block<T>>,
}

/// The token type for the list flavor.
#[derive(Debug)]
pub(crate) struct ListToken {
    /// The block of slots.
    block: *const u8,

    /// The offset into the block.
    offset: usize,
}

impl Default for ListToken {
    #[inline]
    fn default() -> Self {
        ListToken {
            block: ptr::null(),
            offset: 0,
        }
    }
}

/// Unbounded channel implemented as a linked list.
///
/// Each message sent into the channel is assigned a sequence number, i.e. an index. Indices are
/// represented as numbers of type `usize` and wrap on overflow.
///
/// Consecutive messages are grouped into blocks in order to put less pressure on the allocator and
/// improve cache efficiency.
pub(crate) struct Channel<T> {
    /// The head of the channel.
    head: CachePadded<Position<T>>,

    /// The tail of the channel.
    tail: CachePadded<Position<T>>,

    /// Receivers waiting while the channel is empty and not disconnected.
    receivers: SyncWaker,

    /// Indicates that dropping a `Channel<T>` may drop messages of type `T`.
    _marker: PhantomData<T>,
}

impl<T> Channel<T> {
    /// Creates a new unbounded channel.
    pub(crate) fn new() -> Self {
        Channel {
            head: CachePadded::new(Position {
                block: AtomicPtr::new(ptr::null_mut()),
                index: AtomicUsize::new(0),
            }),
            tail: CachePadded::new(Position {
                block: AtomicPtr::new(ptr::null_mut()),
                index: AtomicUsize::new(0),
            }),
            receivers: SyncWaker::new(),
            _marker: PhantomData,
        }
    }

    /// Returns a receiver handle to the channel.
    pub(crate) fn receiver(&self) -> Receiver<'_, T> {
        Receiver(self)
    }

    /// Returns a sender handle to the channel.
    pub(crate) fn sender(&self) -> Sender<'_, T> {
        Sender(self)
    }

    /// Attempts to reserve a slot for sending a message.
    fn start_send(&self, token: &mut Token) -> bool {
        let backoff = Backoff::new();
        let mut tail = self.tail.index.load(Ordering::Acquire);
        let mut block = self.tail.block.load(Ordering::Acquire);
        let mut next_block = None;

        loop {
            // Check if the channel is disconnected.
            if tail & MARK_BIT != 0 {
                token.list.block = ptr::null();
                return true;
            }

            // Calculate the offset of the index into the block.
            let offset = (tail >> SHIFT) % LAP;

            // If we reached the end of the block, wait until the next one is installed.
            if offset == BLOCK_CAP {
                backoff.snooze();
                tail = self.tail.index.load(Ordering::Acquire);
                block = self.tail.block.load(Ordering::Acquire);
                continue;
            }

            // If we're going to have to install the next block, allocate it in advance in order to
            // make the wait for other threads as short as possible.
            if offset + 1 == BLOCK_CAP && next_block.is_none() {
                next_block = Some(Box::new(Block::<T>::new()));
            }

            // If this is the first message to be sent into the channel, we need to allocate the
            // first block and install it.
            if block.is_null() {
                let new = Box::into_raw(Box::new(Block::<T>::new()));

                if self
                    .tail
                    .block
                    .compare_exchange(block, new, Ordering::Release, Ordering::Relaxed)
                    .is_ok()
                {
                    self.head.block.store(new, Ordering::Release);
                    block = new;
                } else {
                    next_block = unsafe { Some(Box::from_raw(new)) };
                    tail = self.tail.index.load(Ordering::Acquire);
                    block = self.tail.block.load(Ordering::Acquire);
                    continue;
                }
            }

            let new_tail = tail + (1 << SHIFT);

            // Try advancing the tail forward.
            match self.tail.index.compare_exchange_weak(
                tail,
                new_tail,
                Ordering::SeqCst,
                Ordering::Acquire,
            ) {
                Ok(_) => unsafe {
                    // If we've reached the end of the block, install the next one.
                    if offset + 1 == BLOCK_CAP {
                        let next_block = Box::into_raw(next_block.unwrap());
                        self.tail.block.store(next_block, Ordering::Release);
                        self.tail.index.fetch_add(1 << SHIFT, Ordering::Release);
                        (*block).next.store(next_block, Ordering::Release);
                    }

                    token.list.block = block as *const u8;
                    token.list.offset = offset;
                    return true;
                },
                Err(t) => {
                    tail = t;
                    block = self.tail.block.load(Ordering::Acquire);
                    backoff.spin();
                }
            }
        }
    }

    /// Writes a message into the channel.
    pub(crate) unsafe fn write(&self, token: &mut Token, msg: T) -> Result<(), T> {
        // If there is no slot, the channel is disconnected.
        if token.list.block.is_null() {
            return Err(msg);
        }

        // Write the message into the slot.
        let block = token.list.block as *mut Block<T>;
        let offset = token.list.offset;
        let slot = (*block).slots.get_unchecked(offset);
        slot.msg.get().write(MaybeUninit::new(msg));
        slot.state.fetch_or(WRITE, Ordering::Release);

        // Wake a sleeping receiver.
        self.receivers.notify();
        Ok(())
    }

    /// Attempts to reserve a slot for receiving a message.
    fn start_recv(&self, token: &mut Token) -> bool {
        let backoff = Backoff::new();
        let mut head = self.head.index.load(Ordering::Acquire);
        let mut block = self.head.block.load(Ordering::Acquire);

        loop {
            // Calculate the offset of the index into the block.
            let offset = (head >> SHIFT) % LAP;

            // If we reached the end of the block, wait until the next one is installed.
            if offset == BLOCK_CAP {
                backoff.snooze();
                head = self.head.index.load(Ordering::Acquire);
                block = self.head.block.load(Ordering::Acquire);
                continue;
            }

            let mut new_head = head + (1 << SHIFT);

            if new_head & MARK_BIT == 0 {
                atomic::fence(Ordering::SeqCst);
                let tail = self.tail.index.load(Ordering::Relaxed);

                // If the tail equals the head, that means the channel is empty.
                if head >> SHIFT == tail >> SHIFT {
                    // If the channel is disconnected...
                    if tail & MARK_BIT != 0 {
                        // ...then receive an error.
                        token.list.block = ptr::null();
                        return true;
                    } else {
                        // Otherwise, the receive operation is not ready.
                        return false;
                    }
                }

                // If head and tail are not in the same block, set `MARK_BIT` in head.
                if (head >> SHIFT) / LAP != (tail >> SHIFT) / LAP {
                    new_head |= MARK_BIT;
                }
            }

            // The block can be null here only if the first message is being sent into the channel.
            // In that case, just wait until it gets initialized.
            if block.is_null() {
                backoff.snooze();
                head = self.head.index.load(Ordering::Acquire);
                block = self.head.block.load(Ordering::Acquire);
                continue;
            }

            // Try moving the head index forward.
            match self.head.index.compare_exchange_weak(
                head,
                new_head,
                Ordering::SeqCst,
                Ordering::Acquire,
            ) {
                Ok(_) => unsafe {
                    // If we've reached the end of the block, move to the next one.
                    if offset + 1 == BLOCK_CAP {
                        let next = (*block).wait_next();
                        let mut next_index = (new_head & !MARK_BIT).wrapping_add(1 << SHIFT);
                        if !(*next).next.load(Ordering::Relaxed).is_null() {
                            next_index |= MARK_BIT;
                        }

                        self.head.block.store(next, Ordering::Release);
                        self.head.index.store(next_index, Ordering::Release);
                    }

                    token.list.block = block as *const u8;
                    token.list.offset = offset;
                    return true;
                },
                Err(h) => {
                    head = h;
                    block = self.head.block.load(Ordering::Acquire);
                    backoff.spin();
                }
            }
        }
    }

    /// Reads a message from the channel.
    pub(crate) unsafe fn read(&self, token: &mut Token) -> Result<T, ()> {
        if token.list.block.is_null() {
            // The channel is disconnected.
            return Err(());
        }

        // Read the message.
        let block = token.list.block as *mut Block<T>;
        let offset = token.list.offset;
        let slot = (*block).slots.get_unchecked(offset);
        slot.wait_write();
        let msg = slot.msg.get().read().assume_init();

        // Destroy the block if we've reached the end, or if another thread wanted to destroy but
        // couldn't because we were busy reading from the slot.
        if offset + 1 == BLOCK_CAP {
            Block::destroy(block, 0);
        } else if slot.state.fetch_or(READ, Ordering::AcqRel) & DESTROY != 0 {
            Block::destroy(block, offset + 1);
        }

        Ok(msg)
    }

    /// Attempts to send a message into the channel.
    pub(crate) fn try_send(&self, msg: T) -> Result<(), TrySendError<T>> {
        self.send(msg, None).map_err(|err| match err {
            SendTimeoutError::Disconnected(msg) => TrySendError::Disconnected(msg),
            SendTimeoutError::Timeout(_) => unreachable!(),
        })
    }

    /// Sends a message into the channel.
    pub(crate) fn send(
        &self,
        msg: T,
        _deadline: Option<Instant>,
    ) -> Result<(), SendTimeoutError<T>> {
        let token = &mut Token::default();
        assert!(self.start_send(token));
        unsafe {
            self.write(token, msg)
                .map_err(SendTimeoutError::Disconnected)
        }
    }

    /// Attempts to receive a message without blocking.
    pub(crate) fn try_recv(&self) -> Result<T, TryRecvError> {
        let token = &mut Token::default();

        if self.start_recv(token) {
            unsafe { self.read(token).map_err(|_| TryRecvError::Disconnected) }
        } else {
            Err(TryRecvError::Empty)
        }
    }

    /// Receives a message from the channel.
    pub(crate) fn recv(&self, deadline: Option<Instant>) -> Result<T, RecvTimeoutError> {
        let token = &mut Token::default();
        loop {
            // Try receiving a message several times.
            let backoff = Backoff::new();
            loop {
                if self.start_recv(token) {
                    unsafe {
                        return self.read(token).map_err(|_| RecvTimeoutError::Disconnected);
                    }
                }

                if backoff.is_completed() {
                    break;
                } else {
                    backoff.snooze();
                }
            }

            if let Some(d) = deadline {
                if Instant::now() >= d {
                    return Err(RecvTimeoutError::Timeout);
                }
            }

            // Prepare for blocking until a sender wakes us up.
            Context::with(|cx| {
                let oper = Operation::hook(token);
                self.receivers.register(oper, cx);

                // Has the channel become ready just now?
                if !self.is_empty() || self.is_disconnected() {
                    let _ = cx.try_select(Selected::Aborted);
                }

                // Block the current thread.
                let sel = cx.wait_until(deadline);

                match sel {
                    Selected::Waiting => unreachable!(),
                    Selected::Aborted | Selected::Disconnected => {
                        self.receivers.unregister(oper).unwrap();
                        // If the channel was disconnected, we still have to check for remaining
                        // messages.
                    }
                    Selected::Operation(_) => {}
                }
            });
        }
    }

    /// Returns the current number of messages inside the channel.
    pub(crate) fn len(&self) -> usize {
        loop {
            // Load the tail index, then load the head index.
            let mut tail = self.tail.index.load(Ordering::SeqCst);
            let mut head = self.head.index.load(Ordering::SeqCst);

            // If the tail index didn't change, we've got consistent indices to work with.
            if self.tail.index.load(Ordering::SeqCst) == tail {
                // Erase the lower bits.
                tail &= !((1 << SHIFT) - 1);
                head &= !((1 << SHIFT) - 1);

                // Fix up indices if they fall onto block ends.
                if (tail >> SHIFT) & (LAP - 1) == LAP - 1 {
                    tail = tail.wrapping_add(1 << SHIFT);
                }
                if (head >> SHIFT) & (LAP - 1) == LAP - 1 {
                    head = head.wrapping_add(1 << SHIFT);
                }

                // Rotate indices so that head falls into the first block.
                let lap = (head >> SHIFT) / LAP;
                tail = tail.wrapping_sub((lap * LAP) << SHIFT);
                head = head.wrapping_sub((lap * LAP) << SHIFT);

                // Remove the lower bits.
                tail >>= SHIFT;
                head >>= SHIFT;

                // Return the difference minus the number of blocks between tail and head.
                return tail - head - tail / LAP;
            }
        }
    }

    /// Returns the capacity of the channel.
    pub(crate) fn capacity(&self) -> Option<usize> {
        None
    }

    /// Disconnects senders and wakes up all blocked receivers.
    ///
    /// Returns `true` if this call disconnected the channel.
    pub(crate) fn disconnect_senders(&self) -> bool {
        let tail = self.tail.index.fetch_or(MARK_BIT, Ordering::SeqCst);

        if tail & MARK_BIT == 0 {
            self.receivers.disconnect();
            true
        } else {
            false
        }
    }

    /// Disconnects receivers.
    ///
    /// Returns `true` if this call disconnected the channel.
    pub(crate) fn disconnect_receivers(&self) -> bool {
        let tail = self.tail.index.fetch_or(MARK_BIT, Ordering::SeqCst);

        if tail & MARK_BIT == 0 {
            // If receivers are dropped first, discard all messages to free
            // memory eagerly.
            self.discard_all_messages();
            true
        } else {
            false
        }
    }

    /// Discards all messages.
    ///
    /// This method should only be called when all receivers are dropped.
    fn discard_all_messages(&self) {
        let backoff = Backoff::new();
        let mut tail = self.tail.index.load(Ordering::Acquire);
        loop {
            let offset = (tail >> SHIFT) % LAP;
            if offset != BLOCK_CAP {
                break;
            }

            // New updates to tail will be rejected by MARK_BIT and aborted unless it's
            // at boundary. We need to wait for the updates take affect otherwise there
            // can be memory leaks.
            backoff.snooze();
            tail = self.tail.index.load(Ordering::Acquire);
        }

        let mut head = self.head.index.load(Ordering::Acquire);
        let mut block = self.head.block.load(Ordering::Acquire);

        unsafe {
            // Drop all messages between head and tail and deallocate the heap-allocated blocks.
            while head >> SHIFT != tail >> SHIFT {
                let offset = (head >> SHIFT) % LAP;

                if offset < BLOCK_CAP {
                    // Drop the message in the slot.
                    let slot = (*block).slots.get_unchecked(offset);
                    slot.wait_write();
                    let p = &mut *slot.msg.get();
                    p.as_mut_ptr().drop_in_place();
                } else {
                    (*block).wait_next();
                    // Deallocate the block and move to the next one.
                    let next = (*block).next.load(Ordering::Acquire);
                    drop(Box::from_raw(block));
                    block = next;
                }

                head = head.wrapping_add(1 << SHIFT);
            }

            // Deallocate the last remaining block.
            if !block.is_null() {
                drop(Box::from_raw(block));
            }
        }
        head &= !MARK_BIT;
        self.head.block.store(ptr::null_mut(), Ordering::Release);
        self.head.index.store(head, Ordering::Release);
    }

    /// Returns `true` if the channel is disconnected.
    pub(crate) fn is_disconnected(&self) -> bool {
        self.tail.index.load(Ordering::SeqCst) & MARK_BIT != 0
    }

    /// Returns `true` if the channel is empty.
    pub(crate) fn is_empty(&self) -> bool {
        let head = self.head.index.load(Ordering::SeqCst);
        let tail = self.tail.index.load(Ordering::SeqCst);
        head >> SHIFT == tail >> SHIFT
    }

    /// Returns `true` if the channel is full.
    pub(crate) fn is_full(&self) -> bool {
        false
    }
}

impl<T> Drop for Channel<T> {
    fn drop(&mut self) {
        let mut head = self.head.index.load(Ordering::Relaxed);
        let mut tail = self.tail.index.load(Ordering::Relaxed);
        let mut block = self.head.block.load(Ordering::Relaxed);

        // Erase the lower bits.
        head &= !((1 << SHIFT) - 1);
        tail &= !((1 << SHIFT) - 1);

        unsafe {
            // Drop all messages between head and tail and deallocate the heap-allocated blocks.
            while head != tail {
                let offset = (head >> SHIFT) % LAP;

                if offset < BLOCK_CAP {
                    // Drop the message in the slot.
                    let slot = (*block).slots.get_unchecked(offset);
                    let p = &mut *slot.msg.get();
                    p.as_mut_ptr().drop_in_place();
                } else {
                    // Deallocate the block and move to the next one.
                    let next = (*block).next.load(Ordering::Relaxed);
                    drop(Box::from_raw(block));
                    block = next;
                }

                head = head.wrapping_add(1 << SHIFT);
            }

            // Deallocate the last remaining block.
            if !block.is_null() {
                drop(Box::from_raw(block));
            }
        }
    }
}

/// Receiver handle to a channel.
pub(crate) struct Receiver<'a, T>(&'a Channel<T>);

/// Sender handle to a channel.
pub(crate) struct Sender<'a, T>(&'a Channel<T>);

impl<T> SelectHandle for Receiver<'_, T> {
    fn try_select(&self, token: &mut Token) -> bool {
        self.0.start_recv(token)
    }

    fn deadline(&self) -> Option<Instant> {
        None
    }

    fn register(&self, oper: Operation, cx: &Context) -> bool {
        self.0.receivers.register(oper, cx);
        self.is_ready()
    }

    fn unregister(&self, oper: Operation) {
        self.0.receivers.unregister(oper);
    }

    fn accept(&self, token: &mut Token, _cx: &Context) -> bool {
        self.try_select(token)
    }

    fn is_ready(&self) -> bool {
        !self.0.is_empty() || self.0.is_disconnected()
    }

    fn watch(&self, oper: Operation, cx: &Context) -> bool {
        self.0.receivers.watch(oper, cx);
        self.is_ready()
    }

    fn unwatch(&self, oper: Operation) {
        self.0.receivers.unwatch(oper);
    }
}

impl<T> SelectHandle for Sender<'_, T> {
    fn try_select(&self, token: &mut Token) -> bool {
        self.0.start_send(token)
    }

    fn deadline(&self) -> Option<Instant> {
        None
    }

    fn register(&self, _oper: Operation, _cx: &Context) -> bool {
        self.is_ready()
    }

    fn unregister(&self, _oper: Operation) {}

    fn accept(&self, token: &mut Token, _cx: &Context) -> bool {
        self.try_select(token)
    }

    fn is_ready(&self) -> bool {
        true
    }

    fn watch(&self, _oper: Operation, _cx: &Context) -> bool {
        self.is_ready()
    }

    fn unwatch(&self, _oper: Operation) {}
}


text:
<?php

namespace PHPExiftool\Driver\Tag\Composite;

use JMS\Serializer\Annotation\ExclusionPolicy;
use PHPExiftool\Driver\AbstractTag;

/**
 * @ExclusionPolicy("all")
 */
class DOF extends AbstractTag
{

    protected $Id = 'DOF';

    protected $Name = 'DOF';

    protected $FullName = 'Composite';

    protected $GroupName = 'Composite';

    protected $g0 = 'Composite';

    protected $g1 = 'Composite';

    protected $g2 = 'Other';

    protected $Type = '?';

    protected $Writable = false;

    protected $Description = 'Depth Of Field';

    protected $local_g2 = 'Image';

}

redpajama_set_name: RedPajamaGithub


text:
@class RMMeeting;

@protocol RMMeetingRepositoryProtocol <NSObject>

- (RMMeeting *)currentMeeting;

@end


text:
import random
import unittest

import numpy as np
from get_gpt_model import FakeDataset, generate_model

import paddle
from paddle.distributed.fleet import auto
from paddle.fluid.dygraph.parallel import ParallelEnv

def apply_pass(use_amp=False, level=None):
    strategy = auto.Strategy()
    strategy.auto_mode = "semi"
    strategy.reinit = True
    if use_amp:
        amp = strategy.amp
        amp.enable = True
        amp.custom_white_list = ['softmax', 'layer_norm', 'gelu']
        amp.custom_black_list = [
            'c_softmax_with_cross_entropy',
            'elementwise_div',
            'reduce_sum',
        ]
        amp.init_loss_scaling = 32768
        amp.use_fp16_guard = False
        amp.use_pure_fp16 = level in ["o2", "o3"]
        amp.use_optimizer_fp16 = level == "o3"
        print("amp level: ", level)
    return strategy

def reset_prog():
    paddle.fluid.framework.switch_main_program(paddle.static.Program())
    paddle.fluid.framework.switch_startup_program(paddle.static.Program())

class TestAMPPass(unittest.TestCase):
    def setUp(self):
        self.rtol = 1e-5
        self.atol = 1e-8
        self.batch_size = 1
        self.batch_num = 10
        self.clip_norm = 0.2
        self.dataset = FakeDataset(self.batch_size * self.batch_num)

    def init(self, engine):
        paddle.seed(2021)
        np.random.seed(2021)
        random.seed(2021)
        place = paddle.fluid.CUDAPlace(ParallelEnv().dev_id)
        engine._executor = paddle.static.Executor(place)

    def get_engine(self, use_amp=False, level=None):
        reset_prog()

        strategy = apply_pass(use_amp, level)
        clip = paddle.nn.ClipGradByGlobalNorm(self.clip_norm)
        opt = paddle.optimizer.AdamW(learning_rate=0.00001, grad_clip=clip)
        model, loss = generate_model("mp")

        engine = auto.Engine(model, loss, opt, strategy=strategy)
        self.init(engine)
        return engine

    def check_results(self, ref_losses, check_losses, rtol=None, atol=None):
        np.testing.assert_allclose(
            ref_losses,
            check_losses,
            rtol=rtol or self.rtol,
            atol=atol or self.atol,
            err_msg='pass {} has wrong results!, \nu={}\nv={}\ndiff={}'.format(
                __class__, ref_losses, check_losses, ref_losses - check_losses
            ),
        )

    def test_amp_pass(self):
        # mp2 training
        mp_engine = self.get_engine()
        history = mp_engine.fit(self.dataset, 3, batch_size=self.batch_size)
        mp_losses = np.array(history.history["loss"])

        # mp2 amp-o1 training
        amp_o1_engine = self.get_engine(True, "o1")
        history = amp_o1_engine.fit(self.dataset, 3, batch_size=self.batch_size)
        amp_o1_losses = np.array(history.history["loss"])
        amp_o1_engine.evaluate(self.dataset, 3, batch_size=self.batch_size)
        # self.check_results(mp_losses, amp_o1_losses)

        # mp2 amp-o2 training
        amp_o2_engine = self.get_engine(True, "o2")
        history = amp_o2_engine.fit(self.dataset, 3, batch_size=self.batch_size)
        amp_o2_losses = np.array(history.history["loss"])
        amp_o2_engine.evaluate(self.dataset, 3, batch_size=self.batch_size)
        # self.check_results(mp_losses, amp_o2_losses)

        # mp2 amp-o3 training
        amp_o3_engine = self.get_engine(True, "o3")
        history = amp_o3_engine.fit(self.dataset, 3, batch_size=self.batch_size)
        amp_o3_losses = np.array(history.history["loss"])
        amp_o3_engine.evaluate(self.dataset, 3, batch_size=self.batch_size)
        # self.check_results(mp_losses, amp_o3_losses)

if __name__ == "__main__":
    unittest.main()


text:
title:  Höggormurinn
date:  03/04/2022
---

`Lestu 1Mós 3.1, 2; 2Kor 11.3 og Opb 12.7-9. Hver er þessi höggormur og hvernig blekkti hann Evu?`

Sú staðreynd að "höggormurinn" er með ákveðnum greini bendir til þess að hann sé lesandanum vel kunnur, hann viti vel hver höggormurinn er. Hann er því vel þekktur allt frá upphafi kaflans.

Ritningin staðfestir að um sé að ræða óvin Guðs (Jes 27.1) og kallar hann "djöful og Satan" (Opb 12.9). Auk þess er litið á höggorminn í Austurlöndum nær sem persónugervingu illra afla.

"Til þess að Satan tækist ætlunarverk sitt án þess að nokkuð bæri á því valdi hann sem miðil höggorminn – dulargervi sem hentaði honum vel til blekkingar. Höggormurinn var þá ein gáfaðasta og fallegasta skepna á jörðinni. Hann hafði vængi og þar sem hann flaug um loftið glóði hann í birtu og litir hans voru skínandi fallegir eins og gljáfægt gull" (ÆS, bls. 32).

Þegar Biblían talar um djöfulinn í hvaða formi sem er er það ekki aðeins myndlíking. Ritningin talar um Satan sem bókstaflega veru en ekki sem gervitákn eða óhlutstæða meginreglu um hið illa eða dökka hlið mannkynsins.

Höggormurinn kynnir sig ekki sem óvin Guðs. Þess í stað vitnar höggormurinn í orð Guðs, endurtekur þau og virðist styðja þau. Allt frá upphafi sjáum við að Satan fellur vel að vitna í Guð og hann vitnar jafnvel í Orð Guðs, eins og við munum síðar sjá (Matt 4.6).

Taktu eftir því að höggormurinn deilir ekki við konuna heldur setur hann fram spurningu sem virðist gefa til kynna að hann trúi því sem Drottinn hefur sagt þeim. Hann spyr því: "Er það satt að Guð hafi sagt . . . " (1Mós 3.1)? Þannig sjáum við allt frá upphafi hve slungin og fláráð þessi skepna var. Og eins og við sjáum þá virkaði það.

`Satan tókst að blekkja hina syndlausu Evu í aldingarðinum en erum við ekki enn viðkvæmari fyrir því en hún var? Hver er besta vörn okkar gegn blekkingum hans?`


text:
from __future__ import unicode_literals

from flask import render_template, jsonify
from www.main.exceptions import ApiError
from www.decorators import add_headers

def init_app(app):

    @app.errorhandler(ApiError)
    @add_headers({'Access-Control-Allow-Origin': '*'})
    def api_error(error):
        response = jsonify(error.to_dict())
        response.status_code = error.status_code
        return response

    @app.errorhandler(403)
    def forbidden_page(error):
        return render_template('error/403.html', page={
            'title': '403',
        }), 403

    @app.errorhandler(404)
    def page_not_found(error):
        return render_template('error/404.html', page={
            'title': '404',
        }), 404

    @app.errorhandler(500)
    def server_error_page(error):
        return render_template('error/500.html',  page={
            'title': '500',
        }), 500


text:
<?xml version="1.0" encoding="UTF-8" ?>

<feed xmlns="http://www.w3.org/2005/Atom"
      xmlns:g="http://base.google.com/ns/1.0">

  <title>subject_area test case 1</title>
  <link href="http://base.google.com/base/attribute_list.html" />
  <updated>2003-12-13T18:30:02Z</updated>
  <id>http://feedvalidator.org/gbase</id>
  <author><name>Google</name></author>

  <entry>
    <title>subject_area test case 1</title>
    <id>tag:base.google.com,2005:subject_area_1</id>
    <link href="http://base.google.com/base/attribute_list.html#subject_area" />
    <updated>2003-12-13T18:30:02Z</updated>

      From subject_area

    <g:subject_area>Mathematics</g:subject_area>
  </entry>
</feed>


text:
set_name("quickapp_qt")

-- set description
set_description("The Quick Application (Qt)")

-- set project directory
set_projectdir("project")

-- add macros
add_macros("targetname", "$(targetname)")

-- add macro files
add_macrofiles("xmake.lua")


text:
import os
import sys
import signal
import pickle
from io import BytesIO

from . import reduction, spawn
from .context import get_spawning_popen, set_spawning_popen
from multiprocessing import util, process

if sys.version_info[:2] < (3, 3):
    ProcessLookupError = OSError

if sys.platform != "win32":
    from . import semaphore_tracker

__all__ = []

if sys.platform != "win32":
    #
    # Wrapper for an fd used while launching a process
    #

    class _DupFd(object):
        def __init__(self, fd):
            self.fd = reduction._mk_inheritable(fd)

        def detach(self):
            return self.fd

    #
    # Start child process using subprocess.Popen
    #

    __all__.append('Popen')

    class Popen(object):
        method = 'loky'
        DupFd = _DupFd

        def __init__(self, process_obj):
            sys.stdout.flush()
            sys.stderr.flush()
            self.returncode = None
            self._fds = []
            self._launch(process_obj)

        if sys.version_info < (3, 4):
            @classmethod
            def duplicate_for_child(cls, fd):
                popen = get_spawning_popen()
                popen._fds.append(fd)
                return reduction._mk_inheritable(fd)

        else:
            def duplicate_for_child(self, fd):
                self._fds.append(fd)
                return reduction._mk_inheritable(fd)

        def poll(self, flag=os.WNOHANG):
            if self.returncode is None:
                while True:
                    try:
                        pid, sts = os.waitpid(self.pid, flag)
                    except OSError as e:
                        # Child process not yet created. See #1731717
                        # e.errno == errno.ECHILD == 10
                        return None
                    else:
                        break
                if pid == self.pid:
                    if os.WIFSIGNALED(sts):
                        self.returncode = -os.WTERMSIG(sts)
                    else:
                        assert os.WIFEXITED(sts)
                        self.returncode = os.WEXITSTATUS(sts)
            return self.returncode

        def wait(self, timeout=None):
            if sys.version_info < (3, 3):
                import time
                if timeout is None:
                    return self.poll(0)
                deadline = time.time() + timeout
                delay = 0.0005
                while 1:
                    res = self.poll()
                    if res is not None:
                        break
                    remaining = deadline - time.time()
                    if remaining <= 0:
                        break
                    delay = min(delay * 2, remaining, 0.05)
                    time.sleep(delay)
                return res

            if self.returncode is None:
                if timeout is not None:
                    from multiprocessing.connection import wait
                    if not wait([self.sentinel], timeout):
                        return None
                # This shouldn't block if wait() returned successfully.
                return self.poll(os.WNOHANG if timeout == 0.0 else 0)
            return self.returncode

        def terminate(self):
            if self.returncode is None:
                try:
                    os.kill(self.pid, signal.SIGTERM)
                except ProcessLookupError:
                    pass
                except OSError:
                    if self.wait(timeout=0.1) is None:
                        raise

        def _launch(self, process_obj):

            tracker_fd = semaphore_tracker._semaphore_tracker.getfd()

            fp = BytesIO()
            set_spawning_popen(self)
            try:
                prep_data = spawn.get_preparation_data(
                    process_obj._name,
                    getattr(process_obj, "init_main_module", True))
                reduction.dump(prep_data, fp)
                reduction.dump(process_obj, fp)

            finally:
                set_spawning_popen(None)

            try:
                parent_r, child_w = os.pipe()
                child_r, parent_w = os.pipe()
                # for fd in self._fds:
                #     _mk_inheritable(fd)

                cmd_python = [sys.executable]
                cmd_python += ['-m', self.__module__]
                cmd_python += ['--process-name', str(process_obj.name)]
                cmd_python += ['--pipe',
                               str(reduction._mk_inheritable(child_r))]
                reduction._mk_inheritable(child_w)
                if tracker_fd is not None:
                    cmd_python += ['--semaphore',
                                   str(reduction._mk_inheritable(tracker_fd))]
                self._fds.extend([child_r, child_w, tracker_fd])
                from .fork_exec import fork_exec
                pid = fork_exec(cmd_python, self._fds)
                util.debug("launched python with pid {} and cmd:\n{}"
                           .format(pid, cmd_python))
                self.sentinel = parent_r

                method = 'getbuffer'
                if not hasattr(fp, method):
                    method = 'getvalue'
                with os.fdopen(parent_w, 'wb') as f:
                    f.write(getattr(fp, method)())
                self.pid = pid
            finally:
                if parent_r is not None:
                    util.Finalize(self, os.close, (parent_r,))
                for fd in (child_r, child_w):
                    if fd is not None:
                        os.close(fd)

        @staticmethod
        def thread_is_spawning():
            return True

if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser('Command line parser')
    parser.add_argument('--pipe', type=int, required=True,
                        help='File handle for the pipe')
    parser.add_argument('--semaphore', type=int, required=True,
                        help='File handle name for the semaphore tracker')
    parser.add_argument('--process-name', type=str, default=None,
                        help='Identifier for debugging purpose')

    args = parser.parse_args()

    info = dict()
    semaphore_tracker._semaphore_tracker._fd = args.semaphore

    exitcode = 1
    try:
        with os.fdopen(args.pipe, 'rb') as from_parent:
            process.current_process()._inheriting = True
            try:
                prep_data = pickle.load(from_parent)
                spawn.prepare(prep_data)
                process_obj = pickle.load(from_parent)
            finally:
                del process.current_process()._inheriting

        exitcode = process_obj._bootstrap()
    except Exception as e:
        print('\n\n' + '-' * 80)
        print('{} failed with traceback: '.format(args.process_name))
        print('-' * 80)
        import traceback
        print(traceback.format_exc())
        print('\n' + '-' * 80)
    finally:
        if from_parent is not None:
            from_parent.close()

        sys.exit(exitcode)


text:
package com.miguelpalacio.mymacros;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.miguelpalacio.mymacros.database.DatabaseAdapter;

import java.lang.reflect.Type;
import java.util.ArrayList;

/**
 * When this receiver is triggered, store some user data into the database.
 */
public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        //Toast.makeText(context, "Hey, I was executed!", Toast.LENGTH_SHORT).show();

        // Log some user data into the database.
        DatabaseAdapter databaseAdapter = new DatabaseAdapter(context);

        // Load the data from SharedPreferences.
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

        Gson gson = new Gson();
        Type type = new TypeToken<ArrayList<Double>>(){}.getType();
        String json;
        ArrayList<Double> macroList;

        double proteinConsumed;
        double carbsConsumed;
        double fatConsumed;

        json = prefs.getString(PlannerFragment.KEY_MEAL_PROTEIN_LIST, null);

        // If the preference exist, calculate the macro consumption.
        if (json != null) {

            macroList = gson.fromJson(json, type);
            proteinConsumed = Utilities.getSummation(macroList);

            json = prefs.getString(PlannerFragment.KEY_MEAL_CARBS_LIST, null);
            macroList = gson.fromJson(json, type);
            carbsConsumed = Utilities.getSummation(macroList);

            json = prefs.getString(PlannerFragment.KEY_MEAL_FAT_LIST, null);
            macroList = gson.fromJson(json, type);
            fatConsumed = Utilities.getSummation(macroList);

            // Since the day is over, remove all the lists in SharedPreferences (reset).
            PlannerFragment.setResetLists();

        } else {
            proteinConsumed = 0;
            carbsConsumed = 0;
            fatConsumed = 0;
        }

        double proteinTarget = Double.parseDouble(prefs.getString(ProfileFragment.KEY_PROTEIN_GRAMS, "0"));
        double carbsTarget = Double.parseDouble(prefs.getString(ProfileFragment.KEY_CARBS_GRAMS, "0"));
        double fatTarget = Double.parseDouble(prefs.getString(ProfileFragment.KEY_FAT_GRAMS, "0"));

        double userWeight = Double.parseDouble(prefs.getString(ProfileFragment.KEY_WEIGHT, "0"));
        if (prefs.getString(SettingsFragment.KEY_WEIGHT, "").equals("lb")) {
            // Always store weight in kg.
            userWeight = userWeight / 2.2046;
        }

        long logDateTime = System.currentTimeMillis();

        Toast.makeText(context, "Alarm went off!!!", Toast.LENGTH_SHORT).show();

        // Insert the data into the DailyLogs table of the database.
        databaseAdapter.insertLog(proteinTarget, proteinConsumed, carbsTarget, carbsConsumed,
                fatTarget, fatConsumed, userWeight, logDateTime);
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Stud. Mycol. 32: 71 (1990)

#### Original name
Pseudocercosporella dioscoreae Deighton

### Remarks
null


text:
This validator can be used to ensure that the given field is a __positive__ number.

[**Back to Validators List**](./reference.md#validators-list)

## Usage

There are two different ways in which all Sparta validators can be used. See below examples for more explanations:

### Example #1:
You can simply instantiate the `Positive` validator and pass to it the data that you want to validate.

```php
<?php
use Sparta\Validators\Positive;

$validator = Positive();
if(!$validator->isValid('total')){
//Handle errors
}
```

### Example #2:
You can build your validation rules and pass it to the __Validation__ object to handle as shown below:

```php
<?php
use Sparta\Validation;

$rules = [
	'total' => 'positive',
	//other rules if any
];

$validation = new Validation($data, $rules);
if(!$validation->isValid()){
	//handle erros
}

```

In case of validation failure, error messages can be retrieved using the `getErrors` method.

[**Back to Validators List**](./reference.md#validators-list)


text:
package objects;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import jgame.JGObject;
import reflection.Reflection;
import saladConstants.SaladConstants;
import engineManagers.*;
import util.AttributeMaker;
import util.SaladUtil;
import engineManagers.CollisionManager;
import engineManagers.RevivalManager;
import engineManagers.ScoreManager;

/**
 * GameObject is the superclass of Player and NonPlayer
 * GameObject is a game unit that can execute certain actions and interactions
 *
 * @author: Main Justin (Zihao) Zhang
 *
 * @contribution (side detectors): Shenghan Chen
 * @contribution (Animation Manager & Revival Manager): David Chou
 */

public abstract class GameObject extends JGObject {

	protected ResourceBundle myBehaviors;
	protected CollisionManager myCollisionManager;
	protected RevivalManager myRevivalManager;
	protected ActionManager myActionManager;
	protected AnimationManager myAnimationManager;
	protected List<StatisticsManager> myGameManagers;

	protected int myXSize;
	protected int myYSize;
	protected double myInitX;
	protected double myInitY;
	protected int myInitBlood;
	protected int myBlood;
	protected int myUniqueID;
	protected int myJumpTimes;
	protected boolean myIsInAir;
	protected int myAirCounter;
	protected double myInitXSpeed;
	protected double myInitYSpeed;
	protected String myDefaultImage;
	protected List<String> myAttributes;
	protected String myName;
	protected int myXHead;
	protected int myYHead;
	protected int myPrevXHead;
	protected int myPrevYHead;
	protected List<GameObject> myShotThings;
	protected SideDetector[] mySideDetectors;

	public GameObject(int uniqueID, String staticGfxName, int xsize,
			int ysize, double xpos, double ypos, String name, int collisionId,
			int blood, CollisionManager collisionManager, ScoreManager scoreManager,
			BloodManager bloodManager, RevivalManager revivalManager, LiveManager liveManager,
			TriggerEventManager eventManager) {
		super(String.valueOf(uniqueID), true, xpos, ypos, collisionId, staticGfxName);

		resume_in_view = false;
		suspend();
		myBehaviors = ResourceBundle.getBundle(SaladConstants.DEFAULT_ENGINE_RESOURCE_PACKAGE
						+ SaladConstants.OBJECT_BEHAVIOR);
		setInitPos(xpos, ypos);
		setInitBlood(blood);
		myUniqueID = uniqueID;
		setSize(xsize, ysize);
		myShotThings = new ArrayList<GameObject>();
		myAttributes = new ArrayList<String>();
		myCollisionManager = collisionManager;
		myGameManagers = new ArrayList<StatisticsManager>();
		if(bloodManager != null) myGameManagers.add(bloodManager);
		if(scoreManager != null) myGameManagers.add(scoreManager);
		if(liveManager != null) myGameManagers.add(liveManager);
		if(eventManager != null) myGameManagers.add(eventManager);
		myRevivalManager = revivalManager;
		myDefaultImage = staticGfxName;
		myName = name;
		myActionManager = new ActionManager(this);
		myAnimationManager = new AnimationManager(this);
		initSideDetectors();
		myXHead = xdir;
		myYHead = ydir;
	}

	public GameObject(int uniqueID, String staticGfxName, int xsize,
			int ysize, double xpos, double ypos, String name, int collisionId, int blood,
			CollisionManager collisionManager, TriggerEventManager eventManager){
		this(uniqueID, staticGfxName, xsize, ysize, xpos, ypos, name, collisionId, blood,
				collisionManager, null, null, null, null, eventManager);
	}

	/**
	 * Initial the side detectors
	 */
	protected void initSideDetectors() {
		if (myUniqueID == SaladConstants.NULL_UNIQUE_ID) return;
		mySideDetectors = new SideDetector[SaladConstants.NUM_SIDE_DETECTORS];
		for (int i = 0; i < SaladConstants.NUM_SIDE_DETECTORS; i++) {
			setSideDetector(new SideDetector(this, i, SideDetector.SDcid(colid, i)));
		}
	}

	/**
	 * Set a behavior
	 * @param s
	 * @param args
	 */
	public void setBehavior(String behavior, Object ...args){
		myActionManager.setBehavior(behavior, args);
	}

	/**
	 * Perform an action
	 * @param action
	 */
	public void doAction(String action){
		myActionManager.doAction(action);
	}

	/**
	 * Get the x head direction
	 * @return
	 */
	public int getXHead(){
		return myXHead;
	}

	/**
	 * Get the y head direction
	 */
	public int getYHead(){
		return myYHead;
	}

	/**
	 * set the x head direction
	 */
	public void setXHead(int head){
		myXHead = head;
		if (myXHead < 0 && myPrevXHead != myXHead) {
			myAnimationManager.updateImage(SaladConstants.BK_MOVE);
		} else if (myXHead >= 0 && myPrevXHead != myXHead) {
			myAnimationManager.updateImage(SaladConstants.FD_MOVE);
		}
		myPrevXHead = myXHead;
	}

	/**
	 * set the y head direction
	 * @param head
	 */
	public void setYHead(int head){
		myYHead = head;
		if (myYHead < 0 && myPrevYHead != myYHead) {
			myAnimationManager.updateImage(SaladConstants.UP_MOVE);
		} else if (myYHead >= 0 && myPrevYHead != myYHead) {
			myAnimationManager.updateImage(SaladConstants.DW_MOVE);
		}
		myPrevYHead = myYHead;
	}

	/**
	 * Reset the name
	 *
	 * @param name
	 */
	public void resetName(String name) {
		myName = name;
	}

	/**
	 * Get Name
	 * @return
	 */
	public String getObjectName(){
		return myName;
	}

	/**
	 * Get the collision manager associated with this object
	 *
	 * @return myCollisionManager
	 */
	public CollisionManager getCollisionManager() {
		return myCollisionManager;
	}

	/**
	 * Get the side collision detector associated with this object in direction
	 * of dir
	 *
	 * @param dir
	 * @return mySideDetectors
	 */
	public SideDetector getSideDetector(int dir) {
		return mySideDetectors[dir];
	}

	/**
	 * Set the side collision detector associated with this object in direction
	 * of dir
	 *
	 * @param detector
	 * @return mySideDetectors
	 */
	public void setSideDetector(SideDetector detector) {
		mySideDetectors[detector.myDirection] = detector;
	}

	/**
	 * Set the dimension of the object image
	 *
	 * @param xsize
	 * @param ysize
	 */
	public void setSize(int xsize, int ysize) {
		myXSize = xsize;
		myYSize = ysize;
	}

	/**
	 * Get the x size of the object image
	 *
	 * @return int
	 */
	public int getXSize() {
		return myXSize;
	}

	/**
	 * Get the y size of the object image
	 *
	 * @return int
	 */
	public int getYSize() {
		return myYSize;
	}

	/**
	 * Set the initial position of the object in a scene
	 *
	 * @param x
	 * @param y
	 */
	public void setInitPos(double x, double y) {
		super.setPos(x, y);
		myInitX = x;
		myInitY = y;
	}

	/**
	 * Used for ActionManager or GameObject itself to getAttributes
	 * @return String
	 */
	public String modificationString() {
		if (this instanceof Player) { return SaladConstants.MODIFY_PLAYER; }
		return SaladConstants.MODIFY_ACTOR;
	}

	/**
	 * Used for ActionManager or GameObject itself to getAttributes
	 * @return String
	 */
	public String creationString(){
		if(this instanceof Player){ return SaladConstants.CREATE_PLAYER; }
		return SaladConstants.CREATE_ACTOR;
	}

	/**
	 * Set the intial speed
	 * @param xspeed
	 * @param yspeed
	 */
	public void setInitSpeed(double xspeed, double yspeed) {
		super.setSpeed(xspeed, yspeed);
		myInitXSpeed = xspeed;
		myInitYSpeed = yspeed;
		myAttributes.add(AttributeMaker.addAttribute(modificationString(),
				SaladConstants.ID, myUniqueID, SaladConstants.SPEED, false,
				myInitXSpeed, myInitYSpeed));
	}

	/**
	 * Restore to original state within a scene Used for live-editing
	 */
	public void restore(boolean resetPos) {
		if (resetPos) setPos(myInitX, myInitY);
		setSpeed(myInitXSpeed, myInitYSpeed);
		restoreBlood();
		if (!is_alive) {
			eng.markAddObject(this);
			is_alive = true;
		}
		if (mySideDetectors!=null){
			for (int i = 0; i < SaladConstants.NUM_SIDE_DETECTORS; i++) {
				mySideDetectors[i].restore(false);
			}
		}
	}

	/**
	 * Resume in view
	 */
	public void resume(){
		super.resume();
		if (mySideDetectors!=null){
			for (int i = 0; i < SaladConstants.NUM_SIDE_DETECTORS; i++) {
				mySideDetectors[i].resume();
			}
		}
	}

	/**
	 * suspend from view
	 */
	public void suspend(){
		super.suspend();
		if (mySideDetectors!=null){
			for (int i = 0; i < SaladConstants.NUM_SIDE_DETECTORS; i++) {
				mySideDetectors[i].suspend();
			}
		}
	}

	/**
	 * Reset the unique ID
	 *
	 * @param new uniqueID
	 */
	public void resetID(int uniqueID) {
		myUniqueID = uniqueID;
	}

	/**
	 * Get the unique ID
	 *
	 * @return int
	 */
	public int getID() {
		return myUniqueID;
	}

	/**
	 * Change the number of lives
	 */
	public void changeBlood(int blood) {
		myBlood += blood;
	}

	/**
	 * Initialize the number of lives
	 *
	 * @param lives
	 */
	public void setInitBlood(int blood) {
		myInitBlood = blood;
		restoreBlood();
	}

	protected void restoreBlood(){
		myBlood = myInitBlood;
	}

	/**
	 * Get current number of lives
	 *
	 * @return
	 */
	public int getBlood() {
		return myBlood;
	}

	/**
	 * Get number of initial lives
	 *
	 * @return
	 */
	public int getInitBlood() {
		return myInitBlood;
	}

	public void stop() {
		setSpeed(0);
		setPos(getLastX(), getLastY());
	}

	/**
	 * Called when hit the ground
	 */
	public void ground() {
		if(myIsInAir) setImage(myDefaultImage);
		myIsInAir = false;
		myAirCounter = 1;
		myJumpTimes = 0;
		stop();
	}

	/**
	 * Reset the collision ID
	 *
	 * @param new collisionID
	 */
	public void resetCollisionID(int collisionID) {
		colid = collisionID;
	}

	public int getAirCounter(){
		return myAirCounter;
	}

	public void incrementJumpTimes(int change){
		myJumpTimes += change;
	}

	/**
	 *
	 * @return int jump times
	 */
	public int getJumpTimes() {
		return myJumpTimes;
	}

	@Override
	public void move() {
		if (myBlood <= 0) doAction(SaladConstants.DIE);

		myAirCounter = 2 * (myAirCounter % 2);
	}

	/**
	 * Update the image
	 * @param behavior
	 */
	public void updateImage(String behavior){
		myAnimationManager.updateImage(behavior);
	}

	/**
	 * Called by behaviors to update the managers
	 * @param args
	 */
	public void updateManagers(Object ... args){
		try{
			for(StatisticsManager manager: myGameManagers){
				if(manager != null){
					Reflection.callMethod(manager, SaladConstants.MANAGER_UPDATE, args);
				}
			}
		} catch (Exception e){ e.printStackTrace(); }
	}

	@Override
	public void hit(JGObject other) {
		myCollisionManager.hitObject(myBehaviors, this, (GameObject) other);
	}

	@Override
	public void hit_bg(int tilecid, int tx, int ty, int txsize, int tysize) {
		myCollisionManager.hitTile(myBehaviors, this, tilecid, tx, ty, txsize, tysize);
	}

	@Override
	public void remove() {
		super.remove();
		if (mySideDetectors!=null){
			for (int i = 0; i < SaladConstants.NUM_SIDE_DETECTORS; i++) { mySideDetectors[i].remove();}
		}
		if (myUniqueID != SaladConstants.NULL_UNIQUE_ID) myRevivalManager.addRemovedObject(this);
		if (this instanceof Player) {
			LiveManager liveManager = (LiveManager) getSpecificManager(SaladConstants.LIVE_MANAGER_PATH);
			if(liveManager != null) liveManager.changeLive(myUniqueID, -1);
		}
	}

	protected StatisticsManager getSpecificManager(String name){
		for(StatisticsManager manager: myGameManagers){
			if(manager.getClass().getName().equals(name)){
				return manager;
			}
		}
		return null;
	}

	/**
	 * Should be called by the Parser class to get all attributes of the
	 * GameObject Return a list of Strings that match with the Data Format but
	 * without Key
	 *
	 * @return a list of Strings
	 */
	public List<String> getAttributes() {
		myAttributes.add(0, AttributeMaker.addAttribute(creationString(), SaladConstants.ID, myUniqueID,
				SaladConstants.IMAGE, false, myDefaultImage, myXSize, myYSize, SaladConstants.POSITION, myInitX,
				myInitY, SaladConstants.NAME, myName, SaladConstants.COLLISION_ID, colid, SaladConstants.LIVES, myInitBlood));
		myAttributes.addAll(myActionManager.getAttributes());
		myAttributes.addAll(myAnimationManager.getAttributes());
		List<String> deleteList = new ArrayList<String>();
		for(int i = 0; i < myAttributes.size(); i ++){
			if(myAttributes.get(i).startsWith(creationString()) && i != 0){ deleteList.add(myAttributes.get(i)); }
		}
		for(String s: deleteList){ myAttributes.remove(s); }
		return myAttributes;
	}

	/**
	 * @return the Gfx info
	 */
	public String getMyGfx() {
		return myDefaultImage;
	}

	public void setStaticGfx(String image) {
		myDefaultImage = image;
	}

	public TriggerEventManager getEventManager(){
		return (TriggerEventManager) getSpecificManager(SaladConstants.EVENT_MANAGER_PATH);
	}

	/**
	 * Get the number of the shots that are alive on the screen
	 * @return
	 */
	public int getNumAliveShots(){
		int count = 0;
		for(GameObject object: myShotThings){
			if(object.isAlive()) count ++;
		}
		List<GameObject> temp = new ArrayList<GameObject>();
		for(GameObject object: myShotThings){
			if(object.isAlive()) temp.add(object);
		}
		myShotThings = temp;
		return count;
	}

	public void setInAir(boolean inAir){
		myIsInAir = inAir;
	}

	public boolean getInAir(){
		return myIsInAir;
	}

	/**
	 * Add the shot bullet
	 * @param object
	 */
	public void addShotThing(GameObject object){
		myShotThings.add(object);
	}

    /**
     * @return the myInitX
     */
    public double getMyInitX() {
        return myInitX;
    }

    /**
     * Allows the user to modify the image for different actions
     * @param action
     * @param imgfile
     * @param xsize
     * @param ysize
     */
	public void modifyDynamicImage(String action, String imgfile, int xsize, int ysize) {
		myAnimationManager.modifyImage(action, imgfile);
	}

}


text:
package com.fm.model;

import java.io.Serializable;

/***********************************************************************
 * Module:  Area.java
 * Author:  Administrator
 * Purpose: Defines the Class Area
 ***********************************************************************/

/**
 * 地区(县)
 *
 * 2014-04-25 caizhi 1.0
 *
 */
public class Area implements Serializable{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * 地区id
	 *
	 */
	private String areaId;
	/**
	 * 城市id
	 *
	 */
	private String areaCityId;
	/**
	 * 地区名称
	 *
	 */
	private String areaName;
	/**
	 * 地区编码
	 *
	 */
	private String areaNo;
	/**
	 * 归属城市编码
	 *
	 */
	private String areaCityNo;

	public Area() {
		super();
	}

	public Area(String areaId) {
		super();
		this.areaId = areaId;
	}

	public Area(String areaId, String areaCityId, String areaName,
			String areaNo, String areaCityNo) {
		super();
		this.areaId = areaId;
		this.areaCityId = areaCityId;
		this.areaName = areaName;
		this.areaNo = areaNo;
		this.areaCityNo = areaCityNo;
	}

	/* getter、setter Method */
	public String getAreaId() {
		return areaId;
	}

	public void setAreaId(String areaId) {
		this.areaId = areaId;
	}

	public String getAreaCityId() {
		return areaCityId;
	}

	public void setAreaCityId(String areaCityId) {
		this.areaCityId = areaCityId;
	}

	public String getAreaName() {
		return areaName;
	}

	public void setAreaName(String areaName) {
		this.areaName = areaName;
	}

	public String getAreaNo() {
		return areaNo;
	}

	public void setAreaNo(String areaNo) {
		this.areaNo = areaNo;
	}

	public String getAreaCityNo() {
		return areaCityNo;
	}

	public void setAreaCityNo(String areaCityNo) {
		this.areaCityNo = areaCityNo;
	}

}


text:
package org.grobid.core.data;

import org.grobid.core.layout.LayoutToken;
import org.grobid.core.layout.Page;
import org.grobid.core.utilities.*;

import java.util.List;

import static com.google.common.collect.Iterables.getLast;

public class Note {

    public enum NoteType {
        FOOT,
        MARGIN
    };

    private String identifier;

    private String label;

    private List<LayoutToken> tokens;

    private String text;

    private int offsetStartInPage;

    private boolean ignored = false;

    private NoteType noteType;

    public Note() {
        this.identifier = KeyGen.getKey().substring(0, 7);
    }

    public Note(String label, List<LayoutToken> tokens, String text, NoteType noteType) {
        this.identifier = KeyGen.getKey().substring(0, 7);
        this.label = label;
        this.tokens = tokens;
        this.text = text;
        this.noteType = noteType;
    }

    public Note(String label, List<LayoutToken> tokens, String text, int offsetStartInPage, NoteType noteType) {
        this.identifier = KeyGen.getKey().substring(0, 7);
        this.label = label;
        this.tokens = tokens;
        this.text = text;
        this.offsetStartInPage = offsetStartInPage;
        this.noteType = noteType;
    }

    public Note(String label, List<LayoutToken> tokens, NoteType noteType) {
        this.identifier = KeyGen.getKey().substring(0, 7);
        this.label = label;
        this.tokens = tokens;
        this.noteType = noteType;
    }

    public String getIdentifier() {
        return identifier;
    }

    public void setIdentifier(String identifier) {
        this.identifier = identifier;
    }

    public int getOffsetStartInPage() {
        return offsetStartInPage;
    }

    public void setOffsetStartInPage(int offsetStartInPage) {
        this.offsetStartInPage = offsetStartInPage;
    }

    public int getPageNumber() {
        return tokens.get(0).getPage();
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public List<LayoutToken> getTokens() {
        return tokens;
    }

    public void setTokens(List<LayoutToken> tokens) {
        this.tokens = tokens;
    }

    public String getLabel() {
        return this.label;
    }

    public void setLabel(String label) {
        this.label = label;
    }

    public int getOffsetEndInPage() {
        return getLast(tokens).getOffset();
    }

    public boolean isIgnored() {
        return ignored;
    }

    public void setIgnored(boolean ignored) {
        this.ignored = ignored;
    }

    public NoteType getNoteType() {
        return this.noteType;
    }

    public void setNoteType(NoteType noteType) {
        this.noteType = noteType;
    }

    public String getNoteTypeName() {
        if (this.noteType == NoteType.FOOT) {
            return "foot";
        } else {
            return "margin";
        }
    }
}


text:
<?php

/**
 * @file
 * Contains \Drupal\taxonomy\Tests\Migrate\d6\MigrateTaxonomyConfigsTest.
 */

namespace Drupal\taxonomy\Tests\Migrate\d6;

use Drupal\config\Tests\SchemaCheckTestTrait;
use Drupal\migrate_drupal\Tests\d6\MigrateDrupal6TestBase;

/**
 * Upgrade variables to taxonomy.settings.yml.
 *
 * @group migrate_drupal_6
 */
class MigrateTaxonomyConfigsTest extends MigrateDrupal6TestBase {

  use SchemaCheckTestTrait;

  /**
   * Modules to enable.
   *
   * @var array
   */
  public static $modules = array('taxonomy');

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->executeMigration('d6_taxonomy_settings');
  }

  /**
   * Tests migration of taxonomy variables to taxonomy.settings.yml.
   */
  public function testTaxonomySettings() {
    $config = $this->config('taxonomy.settings');
    $this->assertIdentical(100, $config->get('terms_per_page_admin'));
    $this->assertIdentical(FALSE, $config->get('override_selector'));
    $this->assertConfigSchema(\Drupal::service('config.typed'), 'taxonomy.settings', $config->get());
  }

}


text:
from base import TestbedTest
from models import Image

class ImageTest(TestbedTest):

    def test_create_image(self):
        i = Image(slug="broom", icon_set="fugue",
                  path="icons/fugue/broom.png")
        i.put()
        self.assertEquals(i.slug, "broom")
        self.assertEquals(i.icon_set, "fugue")
        self.assertEquals(i.path, "icons/fugue/broom.png")
        self.assertEquals(i.absolute_url(), "/images/icons/fugue/broom.png")

    def test_load_default_images(self):
        Image.load_defaults()
        images = Image.all().fetch(1000)
        self.assertEquals(len(images), 112)

        fugue = Image.all().fetch(1000)


text:
'use strict'

import Vue from 'vue'
import Meta from 'vue-meta'
import { createRouter } from './router.js'
import { createStore } from './store.js'
import NuxtChild from './components/nuxt-child.js'
import NuxtLink from './components/nuxt-link.js'
import NuxtError from '/work/learn/learnjavascript/vue/nuxt/helloworld/layouts/error.vue'
import Nuxt from './components/nuxt.vue'
import App from './App.vue'

import { getContext } from './utils'

// Import SSR plugins

// Component: <nuxt-child>
Vue.component(NuxtChild.name, NuxtChild)
// Component: <nuxt-link>
Vue.component(NuxtLink.name, NuxtLink)
// Component: <nuxt>
Vue.component(Nuxt.name, Nuxt)

// vue-meta configuration
Vue.use(Meta, {
  keyName: 'head', // the component option name that vue-meta looks for meta info on.
  attribute: 'data-n-head', // the attribute name vue-meta adds to the tags it observes
  ssrAttribute: 'data-n-head-ssr', // the attribute name that lets vue-meta know that meta info has already been server-rendered
  tagIDKeyName: 'hid' // the property name that vue-meta uses to determine whether to overwrite or append a tag
})

const defaultTransition = {"name":"page","mode":"out-in"}

async function createApp (ssrContext) {

  const store = createStore()

  const router = createRouter()

  if (process.server && ssrContext && ssrContext.url) {
    await new Promise((resolve, reject) => {
      router.push(ssrContext.url, resolve, reject)
    })
  }

  if (process.browser) {

    // Replace store state before calling plugins
    if (window.__NUXT__ && window.__NUXT__.state) {
      store.replaceState(window.__NUXT__.state)
    }

    // window.onNuxtReady(() => console.log('Ready')) hook
    // Useful for jsdom testing or plugins (https://github.com/tmpvar/jsdom#dealing-with-asynchronous-script-loading)
    window._nuxtReadyCbs = []
    window.onNuxtReady = function (cb) {
      window._nuxtReadyCbs.push(cb)
    }
  }

  // root instance
  // here we inject the router and store to all child components,
  // making them available everywhere as `this.$router` and `this.$store`.
  let app = {
    router,
    store,
    _nuxt: {
      defaultTransition: defaultTransition,
      transitions: [ defaultTransition ],
      setTransitions (transitions) {
        if (!Array.isArray(transitions)) {
          transitions = [ transitions ]
        }
        transitions = transitions.map((transition) => {
          if (!transition) {
            transition = defaultTransition
          } else if (typeof transition === 'string') {
            transition = Object.assign({}, defaultTransition, { name: transition })
          } else {
            transition = Object.assign({}, defaultTransition, transition)
          }
          return transition
        })
        this.$options._nuxt.transitions = transitions
        return transitions
      },
      err: null,
      dateErr: null,
      error (err) {
        err = err || null
        if (typeof err === 'string') {
          err = { statusCode: 500, message: err }
        }
        this.$options._nuxt.dateErr = Date.now()
        this.$options._nuxt.err = err;
        return err
      }
    },
    ...App
  }

  const ctx = getContext({
    isServer: !!ssrContext,
    isClient: !ssrContext,
    route: router.currentRoute,
    store,
    req: ssrContext ? ssrContext.req : undefined,
    res: ssrContext ? ssrContext.res : undefined,
  }, app)
  delete ctx.redirect
  delete ctx.error

  // Inject external plugins

  if (process.browser) {
    let plugin0 = require('~plugins/vue-notifications.js')
    plugin0 = plugin0.default || plugin0
    if (typeof plugin0 === 'function') {
      await plugin0(ctx)
    }
  }

  return { app, router, store }
}

export { createApp, NuxtError }


text:
<?php

defined('WF_EDITOR') or die('RESTRICTED');

require_once( WF_EDITOR_LIBRARIES . '/classes/plugin.php' );

class WFColorpickerPlugin extends WFEditorPlugin {

    /**
     * @access	protected
     */
    public function __construct() {
        parent::__construct(array('colorpicker' => true));
    }

    public function display() {
        parent::display();

        $document = WFDocument::getInstance();

        $document->addScript(array('colorpicker'), 'plugins');
        $document->addStyleSheet(array('colorpicker'), 'plugins');
    }
}

?>