text:
#include <linux/device.h>
#include <linux/export.h>
#include <linux/err.h>
#include <linux/fs.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/uaccess.h>
#include <linux/compat.h>
#include <uapi/linux/kfd_ioctl.h>
#include <linux/time.h>
#include "kfd_priv.h"
#include <linux/mm.h>
#include <linux/mman.h>
#include <asm/processor.h>

/*
 * The primary memory I/O features being added for revisions of gfxip
 * beyond 7.0 (Kaveri) are:
 *
 * Access to ATC/IOMMU mapped memory w/ associated extension of VA to 48b
 *
 * "Flat" shader memory access – These are new shader vector memory
 * operations that do not reference a T#/V# so a "pointer" is what is
 * sourced from the vector gprs for direct access to memory.
 * This pointer space has the Shared(LDS) and Private(Scratch) memory
 * mapped into this pointer space as apertures.
 * The hardware then determines how to direct the memory request
 * based on what apertures the request falls in.
 *
 * Unaligned support and alignment check
 *
 *
 * System Unified Address - SUA
 *
 * The standard usage for GPU virtual addresses are that they are mapped by
 * a set of page tables we call GPUVM and these page tables are managed by
 * a combination of vidMM/driver software components.  The current virtual
 * address (VA) range for GPUVM is 40b.
 *
 * As of gfxip7.1 and beyond we're adding the ability for compute memory
 * clients (CP/RLC, DMA, SHADER(ifetch, scalar, and vector ops)) to access
 * the same page tables used by host x86 processors and that are managed by
 * the operating system. This is via a technique and hardware called ATC/IOMMU.
 * The GPU has the capability of accessing both the GPUVM and ATC address
 * spaces for a given VMID (process) simultaneously and we call this feature
 * system unified address (SUA).
 *
 * There are three fundamental address modes of operation for a given VMID
 * (process) on the GPU:
 *
 *	HSA64 – 64b pointers and the default address space is ATC
 *	HSA32 – 32b pointers and the default address space is ATC
 *	GPUVM – 64b pointers and the default address space is GPUVM (driver
 *		model mode)
 *
 *
 * HSA64 - ATC/IOMMU 64b
 *
 * A 64b pointer in the AMD64/IA64 CPU architecture is not fully utilized
 * by the CPU so an AMD CPU can only access the high area
 * (VA[63:47] == 0x1FFFF) and low area (VA[63:47 == 0) of the address space
 * so the actual VA carried to translation is 48b.  There is a "hole" in
 * the middle of the 64b VA space.
 *
 * The GPU not only has access to all of the CPU accessible address space via
 * ATC/IOMMU, but it also has access to the GPUVM address space.  The "system
 * unified address" feature (SUA) is the mapping of GPUVM and ATC address
 * spaces into a unified pointer space.  The method we take for 64b mode is
 * to map the full 40b GPUVM address space into the hole of the 64b address
 * space.

 * The GPUVM_Base/GPUVM_Limit defines the aperture in the 64b space where we
 * direct requests to be translated via GPUVM page tables instead of the
 * IOMMU path.
 *
 *
 * 64b to 49b Address conversion
 *
 * Note that there are still significant portions of unused regions (holes)
 * in the 64b address space even for the GPU.  There are several places in
 * the pipeline (sw and hw), we wish to compress the 64b virtual address
 * to a 49b address.  This 49b address is constituted of an "ATC" bit
 * plus a 48b virtual address.  This 49b address is what is passed to the
 * translation hardware.  ATC==0 means the 48b address is a GPUVM address
 * (max of 2^40 – 1) intended to be translated via GPUVM page tables.
 * ATC==1 means the 48b address is intended to be translated via IOMMU
 * page tables.
 *
 * A 64b pointer is compared to the apertures that are defined (Base/Limit), in
 * this case the GPUVM aperture (red) is defined and if a pointer falls in this
 * aperture, we subtract the GPUVM_Base address and set the ATC bit to zero
 * as part of the 64b to 49b conversion.
 *
 * Where this 64b to 49b conversion is done is a function of the usage.
 * Most GPU memory access is via memory objects where the driver builds
 * a descriptor which consists of a base address and a memory access by
 * the GPU usually consists of some kind of an offset or Cartesian coordinate
 * that references this memory descriptor.  This is the case for shader
 * instructions that reference the T# or V# constants, or for specified
 * locations of assets (ex. the shader program location).  In these cases
 * the driver is what handles the 64b to 49b conversion and the base
 * address in the descriptor (ex. V# or T# or shader program location)
 * is defined as a 48b address w/ an ATC bit.  For this usage a given
 * memory object cannot straddle multiple apertures in the 64b address
 * space. For example a shader program cannot jump in/out between ATC
 * and GPUVM space.
 *
 * In some cases we wish to pass a 64b pointer to the GPU hardware and
 * the GPU hw does the 64b to 49b conversion before passing memory
 * requests to the cache/memory system.  This is the case for the
 * S_LOAD and FLAT_* shader memory instructions where we have 64b pointers
 * in scalar and vector GPRs respectively.
 *
 * In all cases (no matter where the 64b -> 49b conversion is done), the gfxip
 * hardware sends a 48b address along w/ an ATC bit, to the memory controller
 * on the memory request interfaces.
 *
 *	<client>_MC_rdreq_atc   // read request ATC bit
 *
 *		0 : <client>_MC_rdreq_addr is a GPUVM VA
 *
 *		1 : <client>_MC_rdreq_addr is a ATC VA
 *
 *
 * "Spare" aperture (APE1)
 *
 * We use the GPUVM aperture to differentiate ATC vs. GPUVM, but we also use
 * apertures to set the Mtype field for S_LOAD/FLAT_* ops which is input to the
 * config tables for setting cache policies. The "spare" (APE1) aperture is
 * motivated by getting a different Mtype from the default.
 * The default aperture isn't an actual base/limit aperture; it is just the
 * address space that doesn't hit any defined base/limit apertures.
 * The following diagram is a complete picture of the gfxip7.x SUA apertures.
 * The APE1 can be placed either below or above
 * the hole (cannot be in the hole).
 *
 *
 * General Aperture definitions and rules
 *
 * An aperture register definition consists of a Base, Limit, Mtype, and
 * usually an ATC bit indicating which translation tables that aperture uses.
 * In all cases (for SUA and DUA apertures discussed later), aperture base
 * and limit definitions are 64KB aligned.
 *
 *	<ape>_Base[63:0] = { <ape>_Base_register[63:16], 0x0000 }
 *
 *	<ape>_Limit[63:0] = { <ape>_Limit_register[63:16], 0xFFFF }
 *
 * The base and limit are considered inclusive to an aperture so being
 * inside an aperture means (address >= Base) AND (address <= Limit).
 *
 * In no case is a payload that straddles multiple apertures expected to work.
 * For example a load_dword_x4 that starts in one aperture and ends in another,
 * does not work.  For the vector FLAT_* ops we have detection capability in
 * the shader for reporting a "memory violation" back to the
 * SQ block for use in traps.
 * A memory violation results when an op falls into the hole,
 * or a payload straddles multiple apertures.  The S_LOAD instruction
 * does not have this detection.
 *
 * Apertures cannot overlap.
 *
 *
 *
 * HSA32 - ATC/IOMMU 32b
 *
 * For HSA32 mode, the pointers are interpreted as 32 bits and use a single GPR
 * instead of two for the S_LOAD and FLAT_* ops. The entire GPUVM space of 40b
 * will not fit so there is only partial visibility to the GPUVM
 * space (defined by the aperture) for S_LOAD and FLAT_* ops.
 * There is no spare (APE1) aperture for HSA32 mode.
 *
 *
 * GPUVM 64b mode (driver model)
 *
 * This mode is related to HSA64 in that the difference really is that
 * the default aperture is GPUVM (ATC==0) and not ATC space.
 * We have gfxip7.x hardware that has FLAT_* and S_LOAD support for
 * SUA GPUVM mode, but does not support HSA32/HSA64.
 *
 *
 * Device Unified Address - DUA
 *
 * Device unified address (DUA) is the name of the feature that maps the
 * Shared(LDS) memory and Private(Scratch) memory into the overall address
 * space for use by the new FLAT_* vector memory ops.  The Shared and
 * Private memories are mapped as apertures into the address space,
 * and the hardware detects when a FLAT_* memory request is to be redirected
 * to the LDS or Scratch memory when it falls into one of these apertures.
 * Like the SUA apertures, the Shared/Private apertures are 64KB aligned and
 * the base/limit is "in" the aperture. For both HSA64 and GPUVM SUA modes,
 * the Shared/Private apertures are always placed in a limited selection of
 * options in the hole of the 64b address space. For HSA32 mode, the
 * Shared/Private apertures can be placed anywhere in the 32b space
 * except at 0.
 *
 *
 * HSA64 Apertures for FLAT_* vector ops
 *
 * For HSA64 SUA mode, the Shared and Private apertures are always placed
 * in the hole w/ a limited selection of possible locations. The requests
 * that fall in the private aperture are expanded as a function of the
 * work-item id (tid) and redirected to the location of the
 * "hidden private memory". The hidden private can be placed in either GPUVM
 * or ATC space. The addresses that fall in the shared aperture are
 * re-directed to the on-chip LDS memory hardware.
 *
 *
 * HSA32 Apertures for FLAT_* vector ops
 *
 * In HSA32 mode, the Private and Shared apertures can be placed anywhere
 * in the 32b space except at 0 (Private or Shared Base at zero disables
 * the apertures). If the base address of the apertures are non-zero
 * (ie apertures exists), the size is always 64KB.
 *
 *
 * GPUVM Apertures for FLAT_* vector ops
 *
 * In GPUVM mode, the Shared/Private apertures are specified identically
 * to HSA64 mode where they are always in the hole at a limited selection
 * of locations.
 *
 *
 * Aperture Definitions for SUA and DUA
 *
 * The interpretation of the aperture register definitions for a given
 * VMID is a function of the "SUA Mode" which is one of HSA64, HSA32, or
 * GPUVM64 discussed in previous sections. The mode is first decoded, and
 * then the remaining register decode is a function of the mode.
 *
 *
 * SUA Mode Decode
 *
 * For the S_LOAD and FLAT_* shader operations, the SUA mode is decoded from
 * the COMPUTE_DISPATCH_INITIATOR:DATA_ATC bit and
 * the SH_MEM_CONFIG:PTR32 bits.
 *
 * COMPUTE_DISPATCH_INITIATOR:DATA_ATC    SH_MEM_CONFIG:PTR32        Mode
 *
 * 1                                              0                  HSA64
 *
 * 1                                              1                  HSA32
 *
 * 0                                              X                 GPUVM64
 *
 * In general the hardware will ignore the PTR32 bit and treat
 * as "0" whenever DATA_ATC = "0", but sw should set PTR32=0
 * when DATA_ATC=0.
 *
 * The DATA_ATC bit is only set for compute dispatches.
 * All "Draw" dispatches are hardcoded to GPUVM64 mode
 * for FLAT_* / S_LOAD operations.
 */

#define MAKE_GPUVM_APP_BASE(gpu_num) \
	(((uint64_t)(gpu_num) << 61) + 0x1000000000000L)

#define MAKE_GPUVM_APP_LIMIT(base) \
	(((uint64_t)(base) & \
		0xFFFFFF0000000000UL) | 0xFFFFFFFFFFL)

#define MAKE_SCRATCH_APP_BASE(gpu_num) \
	(((uint64_t)(gpu_num) << 61) + 0x100000000L)

#define MAKE_SCRATCH_APP_LIMIT(base) \
	(((uint64_t)base & 0xFFFFFFFF00000000UL) | 0xFFFFFFFF)

#define MAKE_LDS_APP_BASE(gpu_num) \
	(((uint64_t)(gpu_num) << 61) + 0x0)
#define MAKE_LDS_APP_LIMIT(base) \
	(((uint64_t)(base) & 0xFFFFFFFF00000000UL) | 0xFFFFFFFF)

int kfd_init_apertures(struct kfd_process *process)
{
	uint8_t id  = 0;
	struct kfd_dev *dev;
	struct kfd_process_device *pdd;

	/*Iterating over all devices*/
	while ((dev = kfd_topology_enum_kfd_devices(id)) != NULL &&
		id < NUM_OF_SUPPORTED_GPUS) {

		pdd = kfd_create_process_device_data(dev, process);
		if (pdd == NULL) {
			pr_err("Failed to create process device data\n");
			return -1;
		}
		/*
		 * For 64 bit process aperture will be statically reserved in
		 * the x86_64 non canonical process address space
		 * amdkfd doesn't currently support apertures for 32 bit process
		 */
		if (process->is_32bit_user_mode) {
			pdd->lds_base = pdd->lds_limit = 0;
			pdd->gpuvm_base = pdd->gpuvm_limit = 0;
			pdd->scratch_base = pdd->scratch_limit = 0;
		} else {
			/*
			 * node id couldn't be 0 - the three MSB bits of
			 * aperture shoudn't be 0
			 */
			pdd->lds_base = MAKE_LDS_APP_BASE(id + 1);

			pdd->lds_limit = MAKE_LDS_APP_LIMIT(pdd->lds_base);

			pdd->gpuvm_base = MAKE_GPUVM_APP_BASE(id + 1);

			pdd->gpuvm_limit =
					MAKE_GPUVM_APP_LIMIT(pdd->gpuvm_base);

			pdd->scratch_base = MAKE_SCRATCH_APP_BASE(id + 1);

			pdd->scratch_limit =
				MAKE_SCRATCH_APP_LIMIT(pdd->scratch_base);
		}

		dev_dbg(kfd_device, "node id %u\n", id);
		dev_dbg(kfd_device, "gpu id %u\n", pdd->dev->id);
		dev_dbg(kfd_device, "lds_base %llX\n", pdd->lds_base);
		dev_dbg(kfd_device, "lds_limit %llX\n", pdd->lds_limit);
		dev_dbg(kfd_device, "gpuvm_base %llX\n", pdd->gpuvm_base);
		dev_dbg(kfd_device, "gpuvm_limit %llX\n", pdd->gpuvm_limit);
		dev_dbg(kfd_device, "scratch_base %llX\n", pdd->scratch_base);
		dev_dbg(kfd_device, "scratch_limit %llX\n", pdd->scratch_limit);

		id++;
	}

	return 0;
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: abaddon
 * Date: 15.08.14
 * Time: 12:22
 */

namespace Letim\CalenderBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
class ClientTunelAdmin extends Admin {
//    protected $datagridValues = array(
//        '_sort_order' => 'DESC',
//        '_sort_by' => 'startedAt'
//    );

    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
            //->add('tunel.id', null, array())
            ->add('client',null, array());
        ;
    }

    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
        $datagridMapper
            ->add('client', null,array());
//            );
            //->add('clients', null, array('label' => 'Клиент'))
            //$datagridMapper->add('startedAt', 'doctrine_orm_datetime_range', array('attr' => array('class' => 'datepicker')));
        //$datagridMapper->add('startedAt', 'doctrine_orm_datetime_range', array('label'=>'Диапозон дат'), null, array('widget' => 'single_text', 'required' => false,  'attr' => array('class' => 'datepicker_a')));
    }

    // Fields to be shown on lists
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            //->addIdentifier('tunel.id',null,array())
            ->addIdentifier('client.name', null, array())
//            ->addIdentifier('planType', null, array())
//            ->addIdentifier('clients', null, array())
        ;

    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.pentaho.di.jdbc;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.trans.step.RowListener;

/**
 * Helper class for collecting the datas.
 *
 * @author tomqin
 */
public class RowStepListener implements RowListener
{
	private transient final Log log = LogFactory.getLog(RowStepListener.class);
	private List<RowMetaAndData> rowsRead;
	private List<RowMetaAndData> rowsWritten;
    private List<RowMetaAndData> rowsError;

	public RowStepListener()
	{
		rowsRead = new ArrayList<RowMetaAndData>();
		rowsWritten = new ArrayList<RowMetaAndData>();
        rowsError = new ArrayList<RowMetaAndData>();
	}

    public void rowReadEvent(RowMetaInterface rowMeta, Object[] row)
    {
//    	log.debug("add the row....");
//    	rowsRead.add(new RowMetaAndData(rowMeta, row));
    }

    public void rowWrittenEvent(RowMetaInterface rowMeta, Object[] row)
    {
    	log.debug("write the row....");
    	rowsWritten.add(new RowMetaAndData(rowMeta, row));
    }

    public void errorRowWrittenEvent(RowMetaInterface rowMeta, Object[] row)
    {
//    	rowsError.add(new RowMetaAndData(rowMeta, row));
    }

	/**
	 * Clear the rows read and rows written.
	 */
	public void clear()
	{
		rowsRead.clear();
		rowsWritten.clear();
        rowsError.clear();
	}

	public List<RowMetaAndData> getRowsRead()
	{
		return rowsRead;
	}

	public List<RowMetaAndData> getRowsWritten()
	{
		return rowsWritten;
	}

    public List<RowMetaAndData> getRowsError()
    {
        return rowsError;
    }
}


text:
$(document).ready(function () {
    //When user is already logged in otherwise else part
    if ($('.navbar-admin').css("display") != "block") {
        $(".header-container").css("margin-top", "0px");
    }
    else {
        $(".header-container").css("margin-top", "90px");
    }

    //For adding white horizontal line between adminbar and portalbanner
    var $win = $(window);
    $win.resize(function () {
        //Top Right Non-Admin Menu

        //When user is already logged in otherwise else part
        if ($('.navbar-admin').css("display") != "block") {
            if ($win.width() > 768) {
                $('#PortBan').css("margin-top", "61px");
            }
            else {
                $('#PortBan').css("margin-top", "68px");
            }
        }
        else {
            $('#PortBan').css("margin-top", "-39px");
        }
    }).resize();
});


text:
#ifndef LI_SYS_MMAP_H
#define LI_SYS_MMAP_H
#include "first.h"

#if defined(HAVE_SYS_MMAN_H)

#include <sys/mman.h>

#elif defined(_WIN32)

#include <Windows.h>
#include <HandleAPI.h>
#include <io.h>
#include <MemoryAPI.h>

#ifndef MAP_FAILED
#define MAP_FAILED ((void *)-1)
#endif
#ifndef MAP_PRIVATE
#define MAP_PRIVATE 0
#endif
#ifndef MAP_SHARED
#define MAP_SHARED 0
#endif
#ifndef PROT_READ
#define PROT_READ PAGE_READONLY
#endif

#define HAVE_MMAP 1

#define munmap(addr, length) UnmapViewOfFile((LPCVOID)(addr))

static inline void *
mmap (void *addr, size_t length, int prot, int flags, int fd, off_t offset)
{
    /* XXX: this limited implementation maps args only to read-only mmap */
    if (prot != PAGE_READONLY) /*(for PAGE_READONLY and FILE_MAP_READ)*/
        return MAP_FAILED;
    UNUSED(flags);

    HANDLE mh = CreateFileMapping((HANDLE) _get_osfhandle(fd),
                                  NULL, PAGE_READONLY,
                                  (sizeof(size_t) > 4) ? length >> 32 : 0,
                                  length & 0xffffffff, NULL);
    if (NULL == mh)
        return MAP_FAILED;

    LPVOID p = MapViewOfFileEx(mh, FILE_MAP_READ,
                               (sizeof(off_t) > 4) ? offset >> 32 : 0,
                               offset & 0xffffffff, length, addr);
    CloseHandle(mh);
    return (NULL != p) ? (void *)p : MAP_FAILED;
}

#else

# define MAP_SHARED 0
# define MAP_PRIVATE 0
# define PROT_READ 0

# define mmap(a, b, c, d, e, f) (-1)
# define munmap(a, b) (-1)

#endif /* HAVE_SYS_MMAN_H */

/* NetBSD 1.3.x needs it; also make it available if mmap() is not present */
#if !defined(MAP_FAILED)
# define MAP_FAILED ((char*)-1)
#endif

#endif


text:
public interface IChessPiece {
	/**
	 * Return the player that owns this piece.
	 *
	 * @return the player that owns this piece.
	 */
	Player player();

	/**
	 * Return the type of this piece ("King", "Queen", "Rook", etc.).  Note:  In this case "type" refers to the game
	 * of chess, not the type of the Java class.
	 *
	 * @return the type of this piece
	 */
	String type();

	/**
	 * Returns whether the piece at location {@code [move.fromRow, move.fromColumn]} is allowed to move to location
	 * {@code [move.fromRow, move.fromColumn]}.
	 *
	 * Note:  Pieces don't store their own location (because doing so would be redundant).  Therefore,
	 * the {@code [move.fromRow, move.fromColumn]} component of {@code move} is necessary.
	 * {@code this} object must be the piece at location {@code [move.fromRow, move.fromColumn]}.
	 * (This method makes no sense otherwise.)
	 *
	 * @param move  a {@link W13project3.Move} object describing the move to be made.
	 * @param board the {@link W13project3.IChessBoard} in which this piece resides.
	 * @return {@code true} if the proposed move is valid, {@code false} otherwise.
	 * @throws IndexOutOfBoundsException if either {@code [move.fromRow, move.fromColumn]} or {@code [move.toRow,
	 *                                   move.toColumn]} don't represent valid locations on the board.
	 * @throws IllegalArgumentException  if {@code this} object isn't the piece at location {@code [move.fromRow, move.fromColumn]}.
	 */
	boolean isValidMove(Move move, IChessPiece[][] board);
}


text:
const Core = require('./core');

class Savage2 extends Core {
    constructor() {
        super();
    }

    async run(state) {
        const buffer = await this.udpSend('\x01',b => b);
        const reader = this.reader(buffer);

        reader.skip(12);
        state.name = this.stripColorCodes(reader.string());
        state.players.setNum(reader.uint(1));
        state.maxplayers = reader.uint(1);
        state.raw.time = reader.string();
        state.map = reader.string();
        state.raw.nextmap = reader.string();
        state.raw.location = reader.string();
        state.raw.minplayers = reader.uint(1);
        state.raw.gametype = reader.string();
        state.raw.version = reader.string();
        state.raw.minlevel = reader.uint(1);
    }

    stripColorCodes(str) {
        return str.replace(/\^./g,'');
    }
}

module.exports = Savage2;


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Panel_UserList.java
 *
 * Created on Apr 26, 2010, 8:44:08 AM
 */

package lprms.panel;

import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import javax.swing.JViewport;
import javax.swing.table.DefaultTableModel;
import lprms.LPRMSApp;
import lprms.obj.Item;
import lprms.sql.SQL_Library;
import org.jdesktop.application.Task;
import org.jdesktop.application.TaskMonitor;
import org.jdesktop.application.TaskService;

/**
 *
 * @author Sarah
 */
public class Panel_ItemList extends Panel {

    /** Creates new form Panel_UserList */
    public Panel_ItemList() {
        data = new DefaultTableModel(COLS, 0) {
            @Override public boolean isCellEditable(int rowIndex, int mColIndex) { return false; } };

        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        dataView = new javax.swing.JTable();
        info = new javax.swing.JLabel();

        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        dataView.setModel(data);
        dataView.setFocusable(false);
        dataView.setName("dataView"); // NOI18N
        dataView.setRequestFocusEnabled(false);
        dataView.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        dataView.setUpdateSelectionOnSort(false);
        dataView.setVerifyInputWhenFocusTarget(false);
        jScrollPane1.setViewportView(dataView);

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(lprms.LPRMSApp.class).getContext().getResourceMap(Panel_ItemList.class);
        info.setText(resourceMap.getString("info.text")); // NOI18N
        info.setName("info"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE)
                    .addComponent(info, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(info))
        );
    }// </editor-fold>//GEN-END:initComponents

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable dataView;
    private javax.swing.JLabel info;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    private javax.swing.table.DefaultTableModel data;

    private class RefreshTask extends Task {
        RefreshTask() {
            super(LPRMSApp.getApplication());
        }
        @SuppressWarnings("unchecked")
        @Override protected Void doInBackground() {
            setMessage("Refreshing Entries");
            data.setRowCount(0);
            data.setDataVector(null, COLS);
            SQL_Library.load_actualItems();
            ArrayList<Item> items = SQL_Library.getActualItems();
            for (int i = 0; i < items.size(); i++)
            {
                data.addRow(items.get(i).getItemInfo());
                this.setProgress(i, 0, items.size());
            }
            info.setText("Number of items: "+items.size());
            return null;
        }
        @Override protected void finished() {
            setMessage("Done");
        }
    }

    public void refresh()
    {
        RefreshTask task = new RefreshTask();
        TaskService ts = LPRMSApp.getInstance().getContext().getTaskService();
        ts.execute(task);

    }

    public void processInput(String input)
    {
        if (input.length() != 7) return;
        int iid = 0;
        try {
            iid = Integer.parseInt(input.substring(1));
        } catch (NumberFormatException e) { System.err.println("Invalid ID!"); }
        if (iid != 0)
        {
            int row = lprms.sql.SQL_Library.findItem(iid);
            if (row != -1)
            {
                dataView.setRowSelectionInterval(row, row);
                scrollToVisible(row);
            }
        }
    }

    public void scrollToVisible(int rowIndex) {
        if (!(dataView.getParent() instanceof JViewport)) {
            return;
        }
        JViewport viewport = (JViewport)dataView.getParent();

        // This rectangle is relative to the table where the
        // northwest corner of cell (0,0) is always (0,0).
        Rectangle rect = dataView.getCellRect(rowIndex, 0, true);

        // The location of the viewport relative to the table
        Point pt = viewport.getViewPosition();

        // Translate the cell location so that it is relative
        // to the view, assuming the northwest corner of the
        // view is (0,0)
        rect.setLocation(rect.x-pt.x, rect.y-pt.y);

        // Scroll the area into view
        viewport.scrollRectToVisible(rect);
    }

    public static final String[] COLS = {"ID", "Owner", "Borrower", "Status"};
}


text:
package com.nrinaudo.fetch.facebook

import com.nrinaudo.fetch._
import com.nrinaudo.fetch.Request.HttpEngine
import com.nrinaudo.fetch.QueryString._
import org.json4s.JsonAST.JValue
import com.nrinaudo.fetch.json4s._

class GraphApi(val req: Request[JValue]) {
  def me: JValue = (req / "me").apply()
}

object GraphApi {
  val RootUri = Protocol.Https :/ "graph.facebook.com"

  def apply(token: String)(implicit engine: HttpEngine) =
    new GraphApi(RootUri.accept(MediaType.Json).map {
      case res @ Status.Success(_) => res.body.as[JValue]
      case res                     => throw new FacebookException(res.body.as[JValue] \ "error")
    } & "access_token" -> token)
}


text:
package com.github.hoqhuuep.islandcraft.api;

/**
 * Controls the distribution of biomes in an IslandCraft island.
 */
public interface IslandGenerator {
    /**
     * Returns an array of biomes for the whole island with the given dimensions
     * and random seed.
     *
     * @param xSize
     *            the width of the island (measured in blocks)
     * @param zSize
     *            the length of the island (measured in blocks)
     * @param islandSeed
     *            the random seed of the island
     * @return an ICBiome[xSize * zSize] containing the biomes for the whole
     *         island such that each element is at index [x + z * xSize]
     */
    ICBiome[] generate(int xSize, int zSize, long islandSeed);
}


text:
var { Color,Indicators,Resource,Directions } = require('./util/consts.js')
var Resources = require('./cards/Resources.js')
var { flatten,extend,sum } = require('./util/util.js')
var { Wonder } = require('./cards/Wonder.js')
var Technics = require('./cards/Technics.js')
var {
    InfrastructureCard,
    GuildCard,
    WarCard,
    TechnicCard,
    TradeFuncCard,
    TradeResCard,
    TradeResOwnCard,
    TradeCard,
    ResourceCard
}  = require('./cards/Card.js')

class Player {
    constructor(options) {
        var defaultCards = {...Color}
        Object.keys(defaultCards).forEach( key => defaultCards[key] = [])
        var defaultOptions = {
            money:3,
            wonder:null,
            cards:defaultCards,
            leftPlayer:null,
            rightPlayer:null,
            score:0,
            conflict:[]
        }
        extend(this,{
            ...defaultOptions,
            ...options,
        })
        if(this.wonder) {
            this.wonder = new Wonder(this.wonder)
        }
    }
    get allCards() {
        return flatten(Object.keys(this.cards).map(key => this.cards[key]))
    }
    get freeBuilds() {
        return this.allCards.reduce((sum,card) => sum.concat(card.freeBuilds),[])
    }
    get cardsName(){
        return this.allCards.reduce((sum,card) => sum.concat(card.name),[])
    }
    get ownRes(){
        let res = []
        let orRes = []
        this.allCards.forEach(card => {
            card.res && res.push(card.res)
            card.orRes && orRes.push(card.orRes)
        })
        // 增加奇迹提供的资源
        res.push(this.wonder.res)
        orRes = orRes.concat(this.wonder.orRes)

        // return {
        //     res:new Resources({
        //         Wood:100,
        //         Brick:100,
        //         Stone:100,
        //         Mineral:100,
        //         Cloth:100,
        //         Glass:100,
        //         Paper:100
        //     }),
        //     orRes
        // }

        return {
            res:Resources.sum(res),
            orRes
        }
    }
    get sellRes(){
        let res = []
        let orRes = []
        this.allCards.forEach(card => {
            // 只能出售资源牌,贸易牌提供的不能出售
            if(card.color === Color.Brown || card.color === Color.Grey) {
                card.res && res.push(card.res)
                card.orRes && orRes.push(card.orRes)
            }
        })
        res.push(this.wonder.res)
        return {
            res:Resources.sum(res),
            orRes
        }
    }
    get publicInfo(){
        return {
            cards:this.cards,
            money:this.money,
            score:this.score,
            wonder:this.wonder,
            conflict:this.conflict
        }
    }
    get privateInfo(){
        return {
            cards:this.cards,
            money:this.money,
            score:this.score,
            wonder:this.wonder,
            conflict:this.conflict
        }
    }
    get arms(){
        let cardArms = sum(this.cards[Color.Red],'arms')
        let wonderArms = this.wonder.arms
        return cardArms + wonderArms
    }
    get technics(){
        let technics = this.cards[Color.Green].map(card => card.technics)
        let cardOrTechnics = this.cards[Color.Purple].filter(card => card.orTechnics).map(card => card.orTechnics)
        let orTechnics = this.wonder.orTechnics.concat(cardOrTechnics)
        return {
            technics,
            orTechnics
        }
    }
    costPerRes(direction){
        let defaultCostPerRes = {...Resource}
        Object.keys(Resource).forEach((key) => {
            defaultCostPerRes[key] = 2
        })

        let discount = card => card.buyRes && card.directions
        let cards = this.allCards.filter(discount)
        let wonder = this.wonder.currentStages.filter(discount)
        let discounts = cards.concat(wonder)
        discounts.forEach(discount => {
            if(discount.directions.filter(x => x === direction).length > 0) {
                discount.buyRes.forEach(key => {
                    defaultCostPerRes[key] = 1
                })
            }
        })
        return defaultCostPerRes
    }

    build(card) {
        this.cards[card.color].push(card)
        if(card.caculateMoney) {
            // 计算这张卡增加的money
            this.money += card.caculateMoney([this.leftPlayer,this,this.rightPlayer])
        }
    }
    canBuild(card,choice) {
        if(this.cardsName[card.name]) {
            // 同名建筑
            return false
        } else {
            // 免费建设链
            if(this.freeBuilds.filter(x => x === card.name).length > 0) {
                return true
            } else {
                return this.isDeal(card,choice)
            }
        }
        return false
    }
    buildWonder(card) {
        let wonder = this.wonder
        let currentStage = wonder.currentStage
        wonder.current.stageLevel += 1
        if(currentStage.money) {
            // 计算这张卡增加的money
            this.money += currentStage.money
        }
    }
    canBuildWonder(){
        let wonder = this.wonder.current
        return this.isDeal(wonder,choice)
    }
    isDeal(cardOrWonder,choice) {
        let costMoney = 0
        let cardCostMoney = cardOrWonder.costMoney || 0
        let trade = choice.trade
        let tradeResSum = new Resources()
        if(trade instanceof Array && trade.length === 2) {
            trade[0].player = this.leftPlayer
            trade[1].player = this.rightPlayer
            trade.forEach(t => t.res = new Resources(t.res))
            let result = this.canTrade(trade)
            if(result.success) {
                costMoney = result.costMoney
                tradeResSum = Resources.sum(result.trades.map(trade => trade.res))
            }
        }

        if(this.money < (costMoney + cardCostMoney)) { // 不够钱
            return false
        }
        // 增加了购买的资源
        let ownRes = this.ownRes
        let nowRes = {
            res:ownRes.res.plus(tradeResSum),
            orRes:ownRes.orRes
        }
        if(Resources.hasRes(nowRes,cardOrWonder.costs).result) {
            // 交易成功
            this.money -= (costMoney + cardCostMoney)
            if(trade instanceof Array && trade.length === 2) {
                // 有交易,加钱
                this.leftPlayer.money += trade[0].costMoney
                this.rightPlayer.money += trade[1].costMoney
            }
            return true
        } else {
            return false // 资源不够
        }
    }

    // 弃掉一张,+3元
    discard(){
        this.money += 3
    }

    canTrade(trades) {
        let index = 0
        let result = trades.reduce((result,trade) => {
            if(result.success) { // 任何一个失败代表交易不可行
                let res = trade.res
                let player = trade.player
                let costMoney = this.caculateTrade(res,player,index === 0 ? Directions.Left:Directions.Right)
                if(costMoney >= 0) {
                    trade.costMoney = costMoney
                    result.trades.push(trade)
                } else {
                    // 交易验证失败,没有这么多资源
                    result.success = false
                }
            }
            index += 1
            return result
        },{success:true,trades:[]})
        if(result.success) {
            // 钱够不够
            let costMoney = trades.reduce((sum,trade) => sum + (trade.costMoney || 0),0)
            result.success = this.money >= costMoney
            if(result.success) {
                result.costMoney = costMoney
            }
        }
        return result
    }

    caculateTrade(tradeRes,toPlayer,direction){
        if(Resources.hasRes(toPlayer.sellRes,tradeRes).result) {
            // 计算花费,TODO:考虑Trade贸易卡
            let costPerRes = this.costPerRes(direction)
            let costMoney = tradeRes.mul(costPerRes)
            return costMoney
        } else {
            return -1
        }
    }
    updateScore(){
        let blueScore = sum(this.cards[Color.Blue],'score')
        let moneyScore = this.money / 3
        let wonderScore = this.wonder.score
        // 计算黄色、紫色卡牌等需要计算左右两边的卡牌的分数
        let indicatorsCards = this.cards[Color.Yellow].concat(this.cards[Color.Purple])
        let indicatorsScore = indicatorsCards.reduce((sum,card) => {
            return sum + card.caculateScore([this.leftPlayer,this,this.rightPlayer])
        },0)
        // 计算科技牌
        let technicsObj = this.technics
        let technicsScore = Technics.caculateScore(technicsObj.technics,technicsObj.orTechnics)
        // 计算冲突
        let conflictScore = sum(this.conflict)
        this.score =  blueScore + moneyScore + wonderScore + indicatorsScore + technicsScore + conflictScore
        this.score = Math.floor(this.score)
    }
}

// Player中需要向Card暴露的方法,用于计算卡片的分数
Object.keys(Color).forEach(color => {
    Player.prototype[color] = function(){
        return this.cards[color].length
    }
})
Player.prototype[Indicators.Wonders] = function(){
    return this.wonder.current.stageLevel
}
Player.prototype[Indicators.Lose] = function(){
    return this.lose
}

module.exports = Player


text:
{% load i18n %}
{% load bootstrap3 %}
{% load base_tags %}
{% load djspikeval_tags %}
{% load sorting_tags %}

<form class="form-inline" method="GET">

    <input id="scope" type="text" name="scope" class="form-control"
           value="{{ scope|default_if_none:"" }}"/>

      <button type="submit" class="btn btn-default" value="Search">
        {% trans "Search" %}
      </button>
      {% if scope %}
        Clear
      {% endif %}

</form>

      {% sort_th "Name" "name" %}
      {% sort_th "User" "user" %}
      {% sort_th "Date" "created" %}
      {% trans "Version" %}

    {% for obj in object_list %}

          {{ obj.name }}

          {% fa_text obj.user.username "user" link=obj.user.get_absolute_url %}

          {% fa_text obj.modified|date "clock-o" %}

          {{ obj.version }}

    {% empty %}

        There are no algorithms available for this filter.

    {% endfor %}

  {% include "base/_pagination.html" %}


text:
require_relative '../../spec_helper'
require_relative 'fixtures/classes'

# Why do we not test that finalizers are run by the GC? The documentation
# says that finalizers are never guaranteed to be run, so we can't
# spec that they are. On some implementations of Ruby the finalizers may
# run asynchronously, meaning that we can't predict when they'll run,
# even if they were guaranteed to do so. Even on MRI finalizers can be
# very unpredictable, due to conservative stack scanning and references
# left in unused memory.

describe "ObjectSpace.define_finalizer" do
  it "raises an ArgumentError if the action does not respond to call" do
    -> {
      ObjectSpace.define_finalizer(Object.new, mock("ObjectSpace.define_finalizer no #call"))
    }.should raise_error(ArgumentError)
  end

  it "accepts an object and a proc" do
    handler = -> id { id }
    ObjectSpace.define_finalizer(Object.new, handler).should == [0, handler]
  end

  it "accepts an object and a bound method" do
    handler = mock("callable")
    def handler.finalize(id) end
    finalize = handler.method(:finalize)
    ObjectSpace.define_finalizer(Object.new, finalize).should == [0, finalize]
  end

  it "accepts an object and a callable" do
    handler = mock("callable")
    def handler.call(id) end
    ObjectSpace.define_finalizer(Object.new, handler).should == [0, handler]
  end

  it "accepts an object and a block" do
    handler = -> id { id }
    ObjectSpace.define_finalizer(Object.new, &handler).should == [0, handler]
  end

  it "raises ArgumentError trying to define a finalizer on a non-reference" do
    -> {
      ObjectSpace.define_finalizer(:blah) { 1 }
    }.should raise_error(ArgumentError)
  end

  # see [ruby-core:24095]
  it "calls finalizer on process termination" do
    code = <<-RUBY
      def scoped
        Proc.new { puts "finalizer run" }
      end
      handler = scoped
      obj = "Test"
      ObjectSpace.define_finalizer(obj, handler)
      exit 0
    RUBY

    ruby_exe(code, :args => "2>&1").should include("finalizer run\n")
  end

  ruby_version_is "3.0" do
    it "warns if the finalizer has the object as the receiver" do
      code = <<-RUBY
        class CapturesSelf
          def initialize
            ObjectSpace.define_finalizer(self, proc {
              puts "finalizer run"
            })
          end
        end
        CapturesSelf.new
        exit 0
      RUBY

      ruby_exe(code, :args => "2>&1").should include("warning: finalizer references object to be finalized\n")
    end

    it "warns if the finalizer is a method bound to the receiver" do
      code = <<-RUBY
        class CapturesSelf
          def initialize
            ObjectSpace.define_finalizer(self, method(:finalize))
          end
          def finalize(id)
            puts "finalizer run"
          end
        end
        CapturesSelf.new
        exit 0
      RUBY

      ruby_exe(code, :args => "2>&1").should include("warning: finalizer references object to be finalized\n")
    end

    it "warns if the finalizer was a block in the receiver" do
      code = <<-RUBY
        class CapturesSelf
          def initialize
            ObjectSpace.define_finalizer(self) do
              puts "finalizer run"
            end
          end
        end
        CapturesSelf.new
        exit 0
      RUBY

      ruby_exe(code, :args => "2>&1").should include("warning: finalizer references object to be finalized\n")
    end
  end

  it "calls a finalizer at exit even if it is self-referencing" do
    code = <<-RUBY
      obj = "Test"
      handler = Proc.new { puts "finalizer run" }
      ObjectSpace.define_finalizer(obj, handler)
      exit 0
    RUBY

    ruby_exe(code).should include("finalizer run\n")
  end

  it "calls a finalizer at exit even if it is indirectly self-referencing" do
    code = <<-RUBY
      class CapturesSelf
        def initialize
          ObjectSpace.define_finalizer(self, finalizer(self))
        end
        def finalizer(zelf)
          proc do
            puts "finalizer run"
          end
        end
      end
      CapturesSelf.new
      exit 0
    RUBY

    ruby_exe(code, :args => "2>&1").should include("finalizer run\n")
  end

  it "calls a finalizer defined in a finalizer running at exit" do
    code = <<-RUBY
      obj = "Test"
      handler = Proc.new do
        obj2 = "Test"
        handler2 = Proc.new { puts "finalizer 2 run" }
        ObjectSpace.define_finalizer(obj2, handler2)
        exit 0
      end
      ObjectSpace.define_finalizer(obj, handler)
      exit 0
    RUBY

    ruby_exe(code, :args => "2>&1").should include("finalizer 2 run\n")
  end

  it "allows multiple finalizers with different 'callables' to be defined" do
    code = <<-RUBY
      obj = Object.new

      ObjectSpace.define_finalizer(obj, Proc.new { STDOUT.write "finalized1\n" })
      ObjectSpace.define_finalizer(obj, Proc.new { STDOUT.write "finalized2\n" })

      exit 0
    RUBY

    ruby_exe(code).lines.sort.should == ["finalized1\n", "finalized2\n"]
  end
end


text:
<refentry xmlns="http://docbook.org/ns/docbook"
          xmlns:xlink="http://www.w3.org/1999/xlink"
          xmlns:xi="http://www.w3.org/2001/XInclude"
          xmlns:src="http://nwalsh.com/xmlns/litprog/fragment"
          xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
          version="5.0" xml:id="page.margin.inner">
<refmeta>
<refentrytitle>page.margin.inner</refentrytitle>
<refmiscinfo class="other" otherclass="datatype">length</refmiscinfo>
</refmeta>
<refnamediv>
<refname>page.margin.inner</refname>
<refpurpose>The inner page margin</refpurpose>
</refnamediv>

<refsynopsisdiv>
<src:fragment xml:id="page.margin.inner.frag"><xsl:param name="page.margin.inner">
  <xsl:choose>
    <xsl:when test="$double.sided != 0">1.25in</xsl:when>
    <xsl:otherwise>1in</xsl:otherwise>
  </xsl:choose>
</xsl:param></src:fragment>
</refsynopsisdiv>

<refsection><info><title>Description</title></info>

<para>The inner page margin is the distance from bound edge of the
page to the first column of text. </para>

<para>The inner page margin is the distance from bound edge of the
page to the outer edge of the first column of text.</para>

<para>In left-to-right text direction,
this is the left margin of recto (front side) pages.
For single-sided output, it is the left margin
of all pages.</para>

<para>In right-to-left text direction,
this is the right margin of recto pages.
For single-sided output, this is the
right margin of all pages.</para>

<note>
<para>Current versions (at least as of version 4.13)
of the XEP XSL-FO processor do not
correctly handle these margin settings for documents
with right-to-left text direction.
The workaround in that situation is to reverse
the values for <parameter>page.margin.inner</parameter>
and <parameter>page.margin.outer</parameter>, until
this bug is fixed by RenderX.  It does not affect documents
with left-to-right text direction.</para>
</note>

</refsection>
</refentry>


text:
package com.install.wallapopcomics.view.master.view;

import android.view.View;

class ViewHolderFactory {

    ComicViewHolder createComicViewHolder(View view) {
        return new ComicViewHolder(view);
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--  Copyright (C) 2017 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
 -->

<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="ws_navigation_drawer_content_description" msgid="777117228299084604">"ନେଭିଗେଶନ୍ ପ୍ୟାନେଲ୍"</string>
    <string name="ws_action_drawer_content_description" msgid="8863821639144537553">"କାର୍ଯ୍ୟକାରୀ ପ୍ୟାନେଲ୍"</string>
    <string name="confirmation_overlay_a11y_description_success" msgid="2936753235333429892">"ସଫଳ ହୋଇଛି"</string>
    <string name="confirmation_overlay_a11y_description_fail" msgid="6412144553299494336">"ବିଫଳ ହୋଇଛି"</string>
    <string name="confirmation_overlay_a11y_description_phone" msgid="8809042819843332546">"ଆପଣଙ୍କ ଫୋନରେ ଖୋଲାଯାଇଛି"</string>
</resources>


text:
using namespace ackward::logging;

struct ExampleFilterImpl
{
    int filter(const LogRecord& r) {
        // only emit Records from even levels.
        if (r.levelno % 2)
            return 1;
        else
            return 0;
    }
};

typedef UserFilter<ExampleFilterImpl> ExampleFilter;

int main(int, char**)
{
    Py_Initialize();
    ackward::logging::initialize();

    Logger l = getLogger(L"my_logger");
    ExampleFilter f;
    l.addFilter(f);

    l.error(L"They've shut down the main reactor. We'll be destroyed for sure.");

    return 0;
}


text:
from rest_framework import serializers

from assets.models import PersonInfoSerializer
from controk_webservice.suppliers.models import Supplier

class SupplierSerializer(serializers.ModelSerializer):
    class Meta:
        model = Supplier
        fields = ['id', 'email', 'cnpj', 'trading_name']

class SupplierInfoSerializer(PersonInfoSerializer):
    class Meta(PersonInfoSerializer.Meta):
        model = Supplier


text:
package li.strolch.service.parameter;

import li.strolch.model.Locator;
import li.strolch.model.ParameterizedElement;
import li.strolch.model.StrolchRootElement;
import li.strolch.model.parameter.Parameter;
import li.strolch.persistence.api.StrolchTransaction;
import li.strolch.persistence.api.TxUpdateStrolchRootElementVisitor;
import li.strolch.service.api.AbstractService;
import li.strolch.service.api.ServiceArgument;
import li.strolch.service.api.ServiceResult;
import li.strolch.service.api.ServiceResultState;
import li.strolch.service.parameter.AddParameterService.AddParameterArg;

/**
 * @author Robert von Burg <eitch@eitchnet.ch>
 */
public class AddParameterService extends AbstractService<AddParameterArg, ServiceResult> {

	@Override
	protected ServiceResult getResultInstance() {
		return new ServiceResult(ServiceResultState.FAILED);
	}

	@Override
	public AddParameterArg getArgumentInstance() {
		return new AddParameterArg();
	}

	@Override
	protected ServiceResult internalDoService(AddParameterArg arg) {

		try (StrolchTransaction tx = openArgOrUserTx(arg)) {

			ParameterizedElement element = tx.findElement(arg.locator);
			element.addParameter(arg.parameter);

			StrolchRootElement rootElement = element.getRootElement();
			rootElement.accept(new TxUpdateStrolchRootElementVisitor(tx));

			tx.commitOnClose();
		}

		return ServiceResult.success();
	}

	public static class AddParameterArg extends ServiceArgument {

		public Locator locator;
		public Parameter<?> parameter;
	}
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">

001
018
019package org.apache.hadoop.mapreduce.lib.output;
020
021import java.io.IOException;
022
023import org.apache.hadoop.fs.FileSystem;
024import org.apache.hadoop.fs.Path;
025
026import org.apache.hadoop.io.SequenceFile;
027import org.apache.hadoop.io.SequenceFile.CompressionType;
028import org.apache.hadoop.io.compress.CompressionCodec;
029import org.apache.hadoop.io.compress.DefaultCodec;
030import org.apache.hadoop.mapreduce.Job;
031import org.apache.hadoop.mapreduce.JobContext;
032import org.apache.hadoop.mapreduce.OutputFormat;
033import org.apache.hadoop.mapreduce.RecordWriter;
034import org.apache.hadoop.mapreduce.TaskAttemptContext;
035import org.apache.hadoop.util.ReflectionUtils;
036import org.apache.hadoop.classification.InterfaceAudience;
037import org.apache.hadoop.classification.InterfaceStability;
038import org.apache.hadoop.conf.Configuration;
039
040/** An {@link OutputFormat} that writes {@link SequenceFile}s. */
041@InterfaceAudience.Public
042@InterfaceStability.Stable
043public class SequenceFileOutputFormat <K,V> extends FileOutputFormat<K, V> {
044
045  protected SequenceFile.Writer getSequenceWriter(TaskAttemptContext context,
046      Class<?> keyClass, Class<?> valueClass)
047      throws IOException {
048    Configuration conf = context.getConfiguration();
049
050    CompressionCodec codec = null;
051    CompressionType compressionType = CompressionType.NONE;
052    if (getCompressOutput(context)) {
053      // find the kind of compression to do
054      compressionType = getOutputCompressionType(context);
055      // find the right codec
056      Class<?> codecClass = getOutputCompressorClass(context,
057                                                     DefaultCodec.class);
058      codec = (CompressionCodec)
059        ReflectionUtils.newInstance(codecClass, conf);
060    }
061    // get the path of the temporary output file
062    Path file = getDefaultWorkFile(context, "");
063    FileSystem fs = file.getFileSystem(conf);
064    return SequenceFile.createWriter(fs, conf, file,
065             keyClass,
066             valueClass,
067             compressionType,
068             codec,
069             context);
070  }
071
072  public RecordWriter<K, V>
073         getRecordWriter(TaskAttemptContext context
074                         ) throws IOException, InterruptedException {
075    final SequenceFile.Writer out = getSequenceWriter(context,
076      context.getOutputKeyClass(), context.getOutputValueClass());
077
078    return new RecordWriter<K, V>() {
079
080        public void write(K key, V value)
081          throws IOException {
082
083          out.append(key, value);
084        }
085
086        public void close(TaskAttemptContext context) throws IOException {
087          out.close();
088        }
089      };
090  }
091
092  /**
093   * Get the {@link CompressionType} for the output {@link SequenceFile}.
094   * @param job the {@link Job}
095   * @return the {@link CompressionType} for the output {@link SequenceFile},
096   *         defaulting to {@link CompressionType#RECORD}
097   */
098  public static CompressionType getOutputCompressionType(JobContext job) {
099    String val = job.getConfiguration().get(FileOutputFormat.COMPRESS_TYPE,
100                                            CompressionType.RECORD.toString());
101    return CompressionType.valueOf(val);
102  }
103
104  /**
105   * Set the {@link CompressionType} for the output {@link SequenceFile}.
106   * @param job the {@link Job} to modify
107   * @param style the {@link CompressionType} for the output
108   *              {@link SequenceFile}
109   */
110  public static void setOutputCompressionType(Job job,
111                                                          CompressionType style) {
112    setCompressOutput(job, true);
113    job.getConfiguration().set(FileOutputFormat.COMPRESS_TYPE,
114                               style.toString());
115  }
116
117}
118


text: <%= lblOther %>


text:
<?php
/**
 * Comment.php
 * @author Revin Roman
 * @link https://rmrevin.ru
 */

namespace frontend\models;

/**
 * Class Comment
 * @package rmrevin\yii\module\Comments\models
 *
 * @property integer $id
 * @property string $entity
 * @property string $from
 * @property string $text
 * @property integer $deleted
 * @property integer $created_by
 * @property integer $updated_by
 * @property integer $created_at
 * @property integer $updated_at
 * @property integer $course_id
 * @property integer $delete_flag
 * @property integer $verifyCode
 *
 * @property \yii\db\ActiveRecord $author
 * @property \yii\db\ActiveRecord $lastUpdateAuthor
 *
 */
class Comment extends \yii\db\ActiveRecord
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            \yii\behaviors\BlameableBehavior::className(),
            \yii\behaviors\TimestampBehavior::className(),
        ];
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['text'], 'required'],
            [['from', 'text'], 'string'],
            [['created_by', 'updated_by', 'created_at', 'updated_at','course_id'], 'integer'],
            [['deleted'], 'boolean'],
            [['deleted'], 'default', 'value' => self::NOT_DELETED],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => \Yii::t('app', 'ID'),
            'entity' => \Yii::t('app', 'Entity'),
            'from' => \Yii::t('app', 'Comment author'),
            'text' => \Yii::t('app', 'Text'),
            'created_by' => \Yii::t('app', 'Created by'),
            'updated_by' => \Yii::t('app', 'Updated by'),
            'created_at' => \Yii::t('app', 'Created at'),
            'updated_at' => \Yii::t('app', 'Updated at'),
        ];
    }

    /**
     * @return bool
     */
    public function isEdited()
    {
        return $this->created_at !== $this->updated_at;
    }

    /**
     * @return bool
     */
    public function isDeleted()
    {
        return $this->deleted === self::DELETED;
    }

    /**
     * @return bool
     */
    public static function canCreate()
    {
        return Comments\Module::instance()->useRbac === true
            ? \Yii::$app->getUser()->can(Comments\Permission::CREATE)
            : true;
    }

    /**
     * @return bool
     */
    public function canUpdate()
    {
        $User = \Yii::$app->getUser();

        return Comments\Module::instance()->useRbac === true
            ? \Yii::$app->getUser()->can(Comments\Permission::UPDATE) || \Yii::$app->getUser()->can(Comments\Permission::UPDATE_OWN, ['Comment' => $this])
            : $User->isGuest ? false : $this->created_by === $User->id;
    }

    /**
     * @return bool
     */
    public function canDelete()
    {
        $User = \Yii::$app->getUser();

        return Comments\Module::instance()->useRbac === true
            ? \Yii::$app->getUser()->can(Comments\Permission::DELETE) || \Yii::$app->getUser()->can(Comments\Permission::DELETE_OWN, ['Comment' => $this])
            : $User->isGuest ? false : $this->created_by === $User->id;
    }

    /**
     * @return queries\CommentQuery
     */
    public function getAuthor()
    {
        return $this->hasOne(Comments\Module::instance()->userIdentityClass, ['id' => 'created_by']);
    }

    /**
     * @return queries\CommentQuery
     */
    public function getLastUpdateAuthor()
    {
        return $this->hasOne(Comments\Module::instance()->userIdentityClass, ['id' => 'updated_by']);
    }

    /**
     * @return queries\CommentQuery
     */
    public static function find()
    {
        return \Yii::createObject(
            Comments\Module::instance()->model('commentQuery'),
            [get_called_class()]
        );
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%comment}}';
    }

    const NOT_DELETED = 0;
    const DELETED = 1;
}


text:
comments: true
date: 2012-06-15 15:02:16
layout: post
slug: wow-i-really-understand-mapreduce-now
title: Wow, I really understand MapReduce now!
wordpress_id: 605
categories:
- Code
- tech
- top
tags:
- hadoop
- hive
---

Here at the [Hadoop session at WindyCityDB](http://windycitydb.org/sessions/#segel)

**Really high level MapReduce**

1) Take one input, process into many outputs

2) Process those many outputs, and generate one output

Why? Because our data sets are so huge, we've split up the tasks to make it more efficient.  The data is split across many nodes on the HDFS system. That is, MapReduce is a way of processing data so huge you can't do it a more conventional way.

**Slightly lower level**

Using the 'Hello World' of MapReduce, the WordCount algorithm, per Dean Wampler

* Mapping Phase

1) Input all of Shakespeare

2) Break up all the words (i.e. map them into key value pairs, e.g. 'wanton' => 1, where wanton has a count of 1)

3) Sort them

* Shuffle phase

1) Send all the mapped 'wanton' key/value pairs to the same reducer node, joining on the values e.g. 'wanton' => [1,1,1,1,1] where for each occurrence of 'wanton', we are aggregating it's count of 1

* Reducing Phase

1) Count up all the values for the each word, so the e.g. 'wanton' appears 5 times

Also see: [http://www.thinkbiganalytics.com/services_educate](http://www.thinkbiganalytics.com/services_educate)


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.celexus</groupId>
    <artifactId>JPolo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>JPolo - A missing Poloniex API for Java</name>
    <url>http://www.github.com/ccook</url>
    <description>A missing Poloniex API for Java</description>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>
    <developers>
        <developer>
            <id>ckcook</id>
            <name>Cam Cook</name>
            <email>cam.cook@linux.com</email>
            <url>http://www.github.com/ccook</url>
            <roles>
                <role>developer</role>
            </roles>
        </developer>
    </developers>
    <licenses>
        <license>
            <name>The Apache Software License, Version 2.0</name>
            <url>http://www.apache.org/licenses/LICENSE-2.0.txt</url>
            <distribution>repo</distribution>
            <comments>A business-friendly OSS license</comments>
        </license>
    </licenses>
    <dependencies>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.9</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
BOOL CGStallShopName::Read( SocketInputStream& iStream )
{
    __ENTER_FUNCTION

        iStream.Read( (CHAR*)(&m_StallNameSize), sizeof(BYTE));
        if( m_StallNameSize>=MAX_STALL_NAME ) m_StallNameSize=MAX_STALL_NAME-1 ;
        iStream.Read( (CHAR*)(m_StallName), sizeof(CHAR)*m_StallNameSize ) ;
        m_StallName[m_StallNameSize] = 0 ;

        return TRUE ;

    __LEAVE_FUNCTION

        return FALSE ;
}

BOOL CGStallShopName::Write( SocketOutputStream& oStream )const
{
    __ENTER_FUNCTION

        oStream.Write( (CHAR*)(&m_StallNameSize), sizeof(BYTE));
        oStream.Write( (CHAR*)(m_StallName), sizeof(CHAR)*m_StallNameSize ) ;

        return TRUE ;

    __LEAVE_FUNCTION

        return FALSE ;
}

UINT CGStallShopName::Execute( Player* pPlayer )
{
    __ENTER_FUNCTION

        return CGStallShopNameHandler::Execute( this, pPlayer ) ;

    __LEAVE_FUNCTION

        return FALSE ;
}


text:
package ru.job4j.tracker.start;

import java.util.ArrayList;

/**
 * Класс ValidateInput.
 *
 * @author Aleksey Slivko
 * @version $1.0$
 * @since 12.05.2017
 */
public class ValidateInput extends ConsoleInput {
    /**
     * Метод с обработкой ошибок.
     * @param question - строка с вопросом.
     * @param range - цифровой интервал.
     * @return - возвращает выбор поль
     */
    public int ask(String question, ArrayList<Integer> range) {
        boolean invalid = true;
        int value = -1;
        do {
            try {
                value = super.ask(question, range);
                invalid = false;
            } catch (MenuOutException moe) {
                System.out.println("Please select key from menu.");
            } catch (NumberFormatException nfe) {
                System.out.println("Please inter validate data again.");
            }
        } while (invalid);
        return value;
    }
}


text:
/* eslint no-unused-vars: 0 */
/* eslint no-constant-condition: "off" */

(function() {
  'use strict';

  angular.module('app')
    .run(init);

  /** @ngInject */
  function init($window, gettextCatalog, gettext) {
    // prepend [MISSING] to untranslated strings
    gettextCatalog.debug = false;

    gettextCatalog.loadAndSet = function(lang) {
      if (lang) {
        lang = lang.replace('_', '-');
        gettextCatalog.setCurrentLanguage(lang);
        if (lang !== 'en') {
          gettextCatalog.loadRemote("gettext/json/" + lang + "/manageiq-ui-service.json");
        }
      }
    };

    $window.N_ = gettext;
    $window.__ = gettextCatalog.getString.bind(gettextCatalog);
  }
})();

if (false) {
  // 'locale_name' will be translated into locale name in every translation
  // For example, in german translation it will be 'Deutsch', in slovak 'Slovensky', etc.
  // The localized locale name will then be presented to the user to select from in the UI.
  var localeName = __('locale_name');
}


text:
GEOShapeSymbol::~GEOShapeSymbol() {
  delete _shape;

#ifdef JAVA_CODE
  super.dispose();
#endif

}

bool GEOShapeSymbol::symbolize(const G3MRenderContext* rc,
                               const GEOSymbolizer*    symbolizer,
                               MeshRenderer*           meshRenderer,
                               ShapesRenderer*         shapesRenderer,
                               MarksRenderer*          marksRenderer,
                               GEOTileRasterizer*      geoTileRasterizer) const {
  if (_shape != NULL) {
    if (shapesRenderer == NULL) {
      ILogger::instance()->logError("Can't simbolize with Shape, ShapesRenderer was not set");
      delete _shape;
    }
    else {
      shapesRenderer->addShape(_shape);
    }
    _shape = NULL;
  }
  return true;
}


text:
📣📣 Important: Printer can only print console logs if you're running an app in the Simulator. If you're running in a real device it will not print any of the logs in console, however, you can always access all logs using [PrinterViewController](#printerviewcontroller) within your app. Printer is using `print` function internally which is more [effective and speedy](https://stackoverflow.com/questions/25951195/swift-print-vs-println-vs-nslog) then `NSLog`.

![Fancy Logo](https://github.com/hemangshah/printer/blob/master/PrinterExampleApp/PrinterExampleApp/printer-logo.png)

[![Build Status](https://travis-ci.org/hemangshah/printer.svg?branch=master)](https://travis-ci.org/hemangshah/printer)
![License](https://img.shields.io/badge/License-MIT-lightgrey.svg)
![Platform](https://img.shields.io/badge/Platforms-iOS-red.svg)
![Swift 4.x](https://img.shields.io/badge/Swift-4.x-blue.svg)
![CocoaPods](https://img.shields.io/cocoapods/dt/printer-logger.svg)
![MadeWithLove](https://img.shields.io/badge/Made%20with%20%E2%9D%A4-India-green.svg)
[![Awesome-Swift](https://cdn.rawgit.com/sindresorhus/awesome/d7305f38d29fed78fa85652e3a63e154dd8e8829/media/badge.svg)](https://github.com/matteocrippa/awesome-swift/)

## You can print the following types of logs with Printer.

  - ✅ Success
  - ❌ Error
  - 🚧 Warning
  - 📣 Information
  - 🚨 Alert

> With each type, it will print a particular emoji and titles which will help you to easily identify what the log is. Moreover, it will look cool too.

## Installation

1.**Manually** - Add Printer folder to your Project. All set. If you don't want [PrinterViewController](#printerviewcontroller) only add `Printer.swift`.

2.**CocoaPods**:

    pod 'printer-logger'

3.**Carthage** [Coming soon]. [Reference](https://medium.com/@filippotosetto/how-to-create-a-carthage-framework-8d9d65f98ac2)

> You can read the [CHANGELOG](https://github.com/hemangshah/printer/blob/master/CHANGELOG.md) file for a particular release.

## Features

1.	[Different ways to print Logs](#different-ways-to-print-logs)
3.	[Plain Logs](#plainlog)
4.	[Tracing](#tracing)
5.	[All Logs for Print](#all-logs-for-print)
6.	[All Logs for Use](#all-logs-for-use)
7.  [PrinterViewController](#printerviewcontroller)
7.	[Save Logs to a file](#save-logs-to-a-file)
8.	[Flush](#flush)
9.	[Customize Printer](#customize-printer)
10.	[Filter Logs](#filter-logs-filter-by-log-types)
11.	[Disable Logs](#disable-logs)
12.	[Completion Block](#completion-block)
14. [Background or Foreground Logs](#background-or-foreground-logs)
13.	[Shipping to AppStore?](#ready-to-ship-your-app)

## Extras

1. [ToDos](#todos)
2. [Credits](#credits)
3. [Thanks](#thank-you)
4. [License](#license)

## Let's see what you can do with Printer.

Printer has a singleton, you should always use it with its singleton.

    Printer.log.show(id: "001", details: "This is a Success message.", logType: .success)

See the output. Isn't it cool?

    [✅ Success] [⌚04-27-2017 10:39:26] [🆔 101] ➞ ✹✹This is a Success message.✹✹

Here are other options you can do with Printer.

    Printer.log.show(id: "002", details: "This is a Error message.", logType: .error)
    Printer.log.show(id: "003", details: "This is an Information message.", logType: .information)
    Printer.log.show(id: "004", details: "This is a Warning message.", logType: .warning)
    Printer.log.show(id: "005", details: "This is an Alert message.", logType: .alert)

Output:

    [❌ Error] [⌚04-27-2017 10:41:39] [🆔 102] ➞ ✹✹This is a Error message.✹✹
    [🚧 Warning] [⌚04-27-2017 10:41:39] [🆔 103] ➞ ✹✹This is a Warning message.✹✹
    [📣 Information] [⌚04-27-2017 10:41:39] [🆔 104] ➞ ✹✹This is an Information message.✹✹
    [🚨 Alert] [⌚04-27-2017 10:41:39] [🆔 105] ➞ ✹✹This is an Alert message.✹✹

## Different ways to print logs.

Don't want to specify the logType everytime? No problem, we have function for that too.

    Printer.log.success(id: "101", details: "This is a Success message. No need to specify logType.")
    Printer.log.error(id: "102", details: "This is an Error message. No need to specify logType.")
    Printer.log.warning(id: "103", details: "This is a Warning message. No need to specify logType.")
    Printer.log.information(id: "104", details: "This is an Information message. No need to specify logType.")
    Printer.log.alert(id: "105", details: "This is an Alert message. No need to specify logType.")

Don't want to specify IDs? We have taken care of that too.

    Printer.log.success(details: "This is a Success message without ID.")
    Printer.log.error(details: "This is an Error message without ID.")
    Printer.log.warning(details: "This is a Warning message without ID.")
    Printer.log.information(details: "This is an Information message without ID.")
    Printer.log.alert(details: "This is an Alert message without ID.")

We have overrided the 'show' function.

    Printer.log.show(details: "This is a Success message.", logType: .success)
    Printer.log.show(details: "This is an Alert message.", logType: .alert)

Show a future log.

    Printer.log.showInFuture(id: "006", details: "This is a future Success message.", logType: .success, afterSeconds: 3)

> This will print a log after specified seconds. In this case, success log after three (3) seconds.

## plainLog

Don't like the fancy logs? No worries, we have a plain log option.

> **DEFAULT**: `false`
> **IMPORTANT**: Should be called in advance.

    Printer.log.plainLog = true

Example when `plainLog` is set to `true`.

    [04-27-2017 10:50:30] ID ➞ 001 Details ➞ This is a Success message.
    [04-27-2017 10:50:30] ID ➞ 002 Details ➞ This is a Error message.
    [04-27-2017 10:50:30] ID ➞ 003 Details ➞ This is an Information message.
    [04-27-2017 10:50:30] ID ➞ 004 Details ➞ This is a Warning message.
    [04-27-2017 10:50:30] ID ➞ 005 Details ➞ This is an Alert message.

We have a new`.plain` type added with show() function.

    Printer.log.show(id: "001", details: "This is a Plain message.", logType: .plain)

> This is useful when you only want a few plain logs.

> **IMPORTANT**: Any properties you're setting should be set in advance or before printing any logs to get the exact effect.

> **SUGGESTION**: You can always set all the properties to customize the **Printer** in `AppDelegate.swift` file,

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
            // Override point for customization after application launch.

            //set the properties and call the specific function as per the need.

            //Printer.log.plainLog = true
            Printer.log.addLineAfterEachPrint = true
            Printer.log.capitalizeTitles = true
            Printer.log.capitalizeDetails = true
            Printer.log.printOnlyIfDebugMode = true

           //Applied filters to only print success and alert type logs.
           //Printer.log.filterLogs = [.success, .alert]

            Printer.log.onLogCompletion = { (log) in
              //print(log)
              //print(log.0)
            }

            //Printer.log.hideTitles()
            //Printer.log.hideEmojis()

            return true
        }

> This will set the properties globally and will be available for the entire app life cycle.

## Tracing

 Want to print the file name, function name and line number?

> **IMPORTANT**: Should be call everytime when you want to print a trace.

    Printer.log.trace()

    Printer.Trace ➞ [05-02-2017 14:58:38] ViewController.swift ➞ viewDidLoad() #40

## Auto Tracing

> **DEFAULT**: `true`
> **IMPORTANT**: `keepAutoTracing` should set to `true` before logging.

This would print same trace as if you call trace(). If you don't like it, just set `keepAutoTracing` to `false`.

## All Logs for Print

Want to print all the logs for a different use case?

> **IMPORTANT**: `keepTracking` should be set to `true` before logging. Even if `keepAutoTracing` is set to `false`; if you pass `showTrace` to `true`, you will see the traced info. This is helpful if you don't want to trace while logging.

    Printer.log.all(showTrace: true)

    [All Logs] [Success] [05-15-2017 14:28:03] Id:001 Details:This is a Success message.
    [Trace] ➞ ViewController.swift ➞ viewDidLoad() #58
    [All Logs] [Error] [05-15-2017 14:28:03] Id:002 Details:This is a Error message.
    [Trace] ➞ ViewController.swift ➞ viewDidLoad() #59
    [All Logs] [Information] [05-15-2017 14:28:03] Id:003 Details:This is an Information message.
    [Trace] ➞ ViewController.swift ➞ viewDidLoad() #60
    [All Logs] [Warning] [05-15-2017 14:28:03] Id:004 Details:This is a Warning message.
    [Trace] ➞ ViewController.swift ➞ viewDidLoad() #61
    [All Logs] [Alert] [05-15-2017 14:28:03] Id:005 Details:This is an Alert message.
    [Trace] ➞ ViewController.swift ➞ viewDidLoad() #62

You can filter them as well.

    Printer.log.all(filterLogTypes: [.alert], showTrace: true)

> This will only print `.alert` type tracked logs with tracing info.

    [All Logs] [Alert] [05-15-2017 14:28:03] Id:005 Details:This is an Alert message.
    [Trace] ➞ ViewController.swift ➞ viewDidLoad() #62

> all() function will always print plain logs. No fancy logs.

## All Logs for Use

Want to get all the logs?

    //let array = Printer.log.getAllLogs()
    let array = Printer.log.getAllLogs(filterLogTypes: [.success])
    if !array.isEmpty {
        array.forEach({ (log) in
             print(log.details)
            //or do something else.
        })
    }

Use cases:
- To store it somewhere.
- To make API calls with log details.
- To do anything which [Printer] isn't supports.

# PrinterViewController

See all the printer logs in  `PrinterViewController`. You can also filter the logs within the view controller.

> **IMPORTANT**: `PrinterViewController` is based on the set properties for `Printer` and works exactly the same, so please be mindful of the properties that you have set.

Use cases:
- To see all the logs inside your application while testing the app either on iDevice or a Simulator.
- No need to check Xcode or Console.

Features:
- Filter Logs based on types.
- Copy a particular log.
- Easy to setup.

- [x] Search Logs.

[**Upcoming**]

- [ ] Send a Log file over email.
- [ ] Set Properties within the log file. Example: Plain Log [Switch On/Off] *Like that!*
- [ ] Clear logs.
- [ ] Air Print.
- [ ] See all the log files.
- [ ] Log files management.
- [ ] Export Text Log files to a PDF.

How to use?

If you prefer manual installation.

> You can always use Printer without PrinterViewController. But it's suggestible to add this class for better logging.

1. Add `PrinterTableViewCell.swift`, `PrinterViewController.swift`, `Printer.storyboard` and `Printer.swift` in your Project. You can simply add **Printer** folder as well.
2. Everything is added, so now copy and paste the code below to present `PrinterViewController` from your app.

> Always add it to someplace (example: navigation bar, side menu, tabbar, app settings) from where you can always present it during development.

        let printerStoryboard = UIStoryboard.init(name: "Printer", bundle: Bundle.main)
        let navcontroller = UINavigationController.init(rootViewController: (printerStoryboard.instantiateViewController(withIdentifier: "PrinterViewControllerID")))
        self.present(navcontroller, animated: true, completion: nil)

## Save Logs to a File

Want to create a log file for use? We have covered it too.

    let array = Printer.log.getAllLogs()
    if !array.isEmpty {
        Printer.log.saveLogToFile(logs: array)
    }

> All your logs will be created in a separate file under Printer folder.

Delete all Log files?

    Printer.log.deleteLogFiles()

## Flush

Want to delete all the log files and free up some space?

    Printer.log.flush()

## Customize Printer

You can add a line after each logs.

> **DEFAULT**: `false`
> **IMPORTANT**: Should be called in advance.

    Printer.log.addLineAfterEachPrint = true

Example: when addLineAfterEachPrint is set to `true`.

    [✅ Success] [⌚04-27-2017 10:53:28] [🆔 001] ➞ ✹✹This is a Success message.✹✹
    ________________________________________________________________________________________
    [❌ Error] [⌚04-27-2017 10:53:28] [🆔 002] ➞ ✹✹This is a Error message.✹✹
    ________________________________________________________________________________________
    [📣 Information] [⌚04-27-2017 10:53:28] [🆔 003] ➞ ✹✹This is an Information message.✹✹
    ________________________________________________________________________________________
    [🚧 Warning] [⌚04-27-2017 10:53:28] [🆔 004] ➞ ✹✹This is a Warning message.✹✹
    ________________________________________________________________________________________
    [🚨 Alert] [⌚04-27-2017 10:53:28] [🆔 005] ➞ ✹✹This is an Alert message.✹✹
    ________________________________________________________________________________________

## Capitalize Titles & Details

You can even capitalize the title and details of logs.

> **DEFAULT**: `false`
> **IMPORTANT**: Should be called in advance.

    Printer.log.capitalizeTitles = true

> **DEFAULT**: `false`
> **IMPORTANT**: Should be called in advance.

    Printer.log.capitalizeDetails = true

Example: when capitalizeTitles and capitalizeDetails are set to `true`.

    [✅ SUCCESS] [⌚04-27-2017 11:09:37] [🆔 001] ➞ ✹✹THIS IS A SUCCESS MESSAGE.✹✹

Don't want to show Emojis?

> **IMPORTANT**: Should be called in advance.

    Printer.log.hideEmojis()

Example: when `hideEmojis()` called.

    [Success] [04-27-2017 11:08:45] [001] ➞ ✹✹This is a Success message.✹✹
    [Error] [04-27-2017 11:08:45] [002] ➞ ✹✹This is a Error message.✹✹
    [Information] [04-27-2017 11:08:45] [003] ➞ ✹✹This is an Information message.✹✹
    [Warning] [04-27-2017 11:08:45] [004] ➞ ✹✹This is a Warning message.✹✹
    [Alert] [04-27-2017 11:08:45] [005] ➞ ✹✹This is an Alert message.✹✹

Don't want to show Titles?

> **IMPORTANT**: Should be called in advance.

    Printer.log.hideTitles()

Don't want to show Log Time?

> **DEFAULT**: `false`
> **IMPORTANT**: Should be called in advance.

    Printer.log.hideLogsTime = true

## Customize Emojis

Don't like the current Emojis? You can override the default Emojis with your favorite Emojis.

> **IMPORTANT**: Should be called in advance.

    Printer.log.successEmojiSymbol = "🎃"

Other properties for Emoji customization.

> **IMPORTANT**: Should be called in advance.

    Printer.log.errorEmojiSymbol = "<SetNew>"
    Printer.log.warningEmojiSymbol = "<SetNew>"
    Printer.log.infoEmojiSymbol = "<SetNew>"
    Printer.log.alertEmojiSymbol = "<SetNew>"

## Customize Titles

Don't like the current Titles or localize Titles? Want to set your own? You can do this.

> **IMPORTANT**: Should be called in advance.

    Printer.log.successLogTitle = "Hurray!!"

Other properties for Titles customization.

> **IMPORTANT**: Should be called in advance.

    Printer.log.errorLogTitle = "<SetNew>"
    Printer.log.warningLogTitle = "<SetNew>"
    Printer.log.infoLogTitle = "<SetNew>"
    Printer.log.alertLogTitle = "<SetNew>"

## Customize Symbols

Don't like the current Symbols? Want to set your own? You can do this.

> **IMPORTANT**: Should be called in advance.

    Printer.log.arrowSymbol = "⇨"

Other properties for Symbol customization.

> **IMPORTANT**: Should be called in advance.

    Printer.log.starSymbol = "<SetNew>"

Don't like the date format in logs? You can change it too.

> **DEFAULT**: `MM-dd-yyyy HH:mm:ss`
> **IMPORTANT**: Should be called in advance.

    Printer.log.logDateFormat = "hh:mm:ss a"

Example when logDateFormat is set to a different format.

    [✅ Success] [⌚11:12:23 AM] [🆔 001] ➞ ✹✹This is a Success message.✹✹

## Filter Logs: Filter by Log Types
Show specific logs with filter.

    Printer.log.filterLogs = [.success, .alert]

> This should only print logs of the specified types. I.e. Succes and Alert. All other logs will be ignored.

## Filter Logs: Filter by File
Written Printer logs everywhere? Want to Skip logging for  `LoginViewController.swift` for security?

To Skip logs for a file: `Printer.log.skipFile()`
To Add logs for a file:  `Printer.log.addFile()`

> **IMPORTANT**: You should call `addFile()` to start printing logs for the same file for which you have called `skipFile()`. This is other than the `disable` property which completely disables logging for all the files.

## Disable Logs
To disable all logs.

> **DEFAULT**: `false`
> **IMPORTANT**: You can set this anywhere and it should not print logs from where it was set.

    Printer.log.disable = true

## Completion Block
Let you will notified in advance before any logging events.

> **IMPORTANT**: This block will ignore all the filters applied for Printer, meaning, it will always notify you for any logs that will print or not print.

        Printer.log.onLogCompletion = { (log) in
            print(log)
            //print(log.0)
        }

Will return current log, file name, function name, and line number. You can access it with log.0, log.1 and so on.

Use cases:

- To notify in advance before a log event.
- To print logs even if you've applied any filter.
- To call your APIs to store log information. Only code at one place. No dependencies.

> You will not get notified if `disable` is set to `true` or `printOnlyIfDebugMode` is set to `true` and if your app is in `release` mode.

## Background or Foreground Logs

Want to see a log of when your app goes to the background or foreground?

    Printer.log.addAppEventsHandler()

    [📣 INFORMATION] [⌚05-17-2017 13:17:38]  ➞ ✹✹App is in foreground now.✹✹
    ________________________________________________________________________________________

Stop logging for background or foreground events?

    Printer.log.removeAppEventsHandler()

> This is helpful when you're checking all the logs and want to see what happended after app went to background or comes to foreground?

## Ready to ship your app?

Don't want to print the logs in RELEASE mode?

> **DEFAULT**: `true`
> **IMPORTANT**: Should be called in advance.

    Printer.log.printOnlyIfDebugMode = false

## To-Do List

- [x] Filter Logs.
- [x] Disable Logs.
- [x] Manual Tracing.
- [x] Auto Tracing.
- [x] All logs - Track all logs and print them all at once.
- [x] Future Logs – A function which will print a log after a certain time.
- [x] Skipping logs for a particular file.
- [x] Delegate calls to let you know the Printer logged.
- [x] Maintain a log file separately.
- [x] Improve README file with following: Features List for direct link to a particular point.
- [x] Log application events. Example: Background/Foreground events.
- [x] Open a ViewController to show up all the logs.
- [ ] Upcoming features of [PrinterViewController](#printerviewcontroller).

Have an idea for improvements of this class?
Please open an [issue](https://github.com/hemangshah/printer/issues/new).

## Credits

[Hemang Shah](https://about.me/hemang.shah)

**You can shoot me an [email](http://www.google.com/recaptcha/mailhide/d?k=01IzGihUsyfigse2G9z80rBw==&c=vU7vyAaau8BctOAIJFwHVbKfgtIqQ4QLJaL73yhnB3k=) to contact.**

## Thank You!!

See the [contributions](https://github.com/hemangshah/printer/blob/master/CONTRIBUTIONS.md) for details.

## License

The MIT License (MIT)

> Read the [LICENSE](https://github.com/hemangshah/printer/blob/master/LICENSE) file for details.


text:
<?php
namespace Faker\Components\Engine\Common\Datasource;

use Faker\ExtensionInterface;
use Faker\Components\Engine\EngineException as FakerException;

/**
  *  Repository of Builders for Datasource's
  *
  *  @author Lewis Dyer <getintouch@icomefromthenet.com>
  *  @since 1.0.5
  */
class DatasourceRepository implements ExtensionInterface
{

    /**
      *  @var 'name' => 'class'
      */
    static $types = array(
          //  'filesource'    => '\\Faker\\Components\\Engine\\Common\\Datasource\\FileDatasourceDefinition',
            'phpsource'     => '\\Faker\\Components\\Engine\\Common\\Datasource\\PHPSourceDefinition',
        //    'sqlsource'    => '\\Faker\\Components\\Engine\\Common\\Datasource\\SQLSourceDefinition',
    );

    /**
      *  Find a type by a given short name
      *
      *  @access public
      *  @return string a class name
      *  @param string $name the alias in lowercase
      */
    public function find($name)
    {
        $result = null;

        if(isset(self::$types[$name])) {
            $result = self::$types[$name];
        }

        return $result;
    }

    //  ----------------------------------------------------------------------------
    # Registration

    /**
      *  Register an new config or overrite and existing
      *
      *  @param string $key lowercase key
      *  @param string $ns the namespace
      *  @access public
      */
    public static function registerExtension($key,$ns)
    {
        $key = strtolower((string)$key);
        self::$types[$key] = $ns;
    }

    /**
      *  Register an new config or overrite and existing
      *
      *  @param array $ext associate array with key and namespace as value
      *  @access public
      */
    public static function registerExtensions(array $ext)
    {
        foreach($ext as $key => $ns) {
            self::registerExtension($key,$ns);
        }
    }

    /**
      *  Clear the extension list
      *
      *  @access public
      *  @return null
      */
    public static function clearExtensions()
    {
        self::$types = array();
    }

}
/* End of File */


text:
#include "system.h"

#include "mtick.h"
#include "hw-wdt.h"
#include "hw-uart.h"
#include "mstring.h"
#include "mcode-config.h"

#include <avr/wdt.h>
#include <avr/boot.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>

void reboot(void)
{
  mprintstrln(PSTR("System reboot has been requested."));
  wdt_reboot();
}

#ifdef MCODE_BOOTLOADER
void bootloader(void)
{
  mprintstrln(PSTR("Enter bootloader mode."));
#ifdef MCODE_WDT
  wdt_stop();
#endif /* MCODE_WDT */
  void (*bl_main)(void) = (void *)MCODE_BOOTLOADER_BASE;
  bl_main();
#ifdef MCODE_WDT
  wdt_start();
#endif /* MCODE_WDT */
}
#endif /* MCODE_BOOTLOADER */


text:
namespace SoftuniDatabase.Models
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public partial class Department
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public Department()
        {
            this.Employees = new HashSet<Employee>();
        }

        public int DepartmentID { get; set; }

        [Required]
        [StringLength(50)]
        public string Name { get; set; }

        public int ManagerID { get; set; }

        public virtual Employee Employee { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<Employee> Employees { get; set; }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<spring:beans xmlns="http://www.citrusframework.org/schema/testcase"
              xmlns:spring="http://www.springframework.org/schema/beans"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                                  http://www.citrusframework.org/schema/testcase http://www.citrusframework.org/schema/testcase/citrus-testcase.xsd">

  <testcase name="VertxSyncEndpointIT">
    <meta-info>
      <author>Christoph Deppisch</author>
      <creationdate>2014-05-17</creationdate>
      <status>FINAL</status>
      <last-updated-by>Christoph Deppisch</last-updated-by>
      <last-updated-on>2014-05-17T00:00:00</last-updated-on>
    </meta-info>

    <description>Test synchronously sends and receives messages to/from Vert.x event bus.</description>

    <actions>
      <echo>
        <message>Test: Send Vert.x message on event bus and receive synchronous reply</message>
      </echo>

      <send endpoint="vertxHelloEndpoint" fork="true">
        <message type="plaintext">
          <data>Hello from Citrus!</data>
        </message>
      </send>

      <receive endpoint="vertxReplyEndpoint">
        <message type="plaintext">
          <data>Hello from Citrus!</data>
        </message>
        <header>
          <element name="citrus_vertx_address" value="hello"/>
        </header>
      </receive>

      <send endpoint="vertxReplyEndpoint">
        <message type="plaintext">
          <data>Hello from Vert.x!</data>
        </message>
      </send>

      <receive endpoint="vertxHelloEndpoint">
        <message type="plaintext">
          <data>Hello from Vert.x!</data>
        </message>
      </receive>

    </actions>
  </testcase>
</spring:beans>


text:
RSpec.describe "Auto-registration / Components with mixed namespaces" do
  before do
    class Test::Container < Dry::System::Container
      configure do |config|
        config.root = SPEC_ROOT.join("fixtures/mixed_namespaces").realpath

        config.component_dirs.add "lib" do |dir|
          dir.namespaces.add "test/my_app", key: nil
        end
      end
    end
  end

  it "loads components with and without the default namespace (lazy loading)" do
    aggregate_failures do
      expect(Test::Container["app_component"]).to be_an_instance_of Test::MyApp::AppComponent
      expect(Test::Container["test.external.external_component"]).to be_an_instance_of Test::External::ExternalComponent
    end
  end

  it "loads components with and without the default namespace (finalizing)" do
    Test::Container.finalize!

    aggregate_failures do
      expect(Test::Container["app_component"]).to be_an_instance_of Test::MyApp::AppComponent
      expect(Test::Container["test.external.external_component"]).to be_an_instance_of Test::External::ExternalComponent
    end
  end
end


text:
<?php
namespace Monitor\Error;

use Cake\Error\ErrorHandler as CoreErrorHandler;
use ErrorException;
use Exception;

class ErrorHandler extends CoreErrorHandler
{
    /**
     * Set as the default error handler by CakePHP.
     *
     * @param int $code Code of error
     * @param string $description Error description
     * @param string|null $file File on which error occurred
     * @param int|null $line Line that triggered the error
     * @param array|null $context Context
     * @return bool True if error was handled
     */
    public function handleError($code, $description, $file = null, $line = null, $context = null)
    {
        $exception = new ErrorException($description, 0, $code, $file, $line);
        $sentryHandler = new SentryHandler();
        $sentryHandler->handle($exception);
        return parent::handleError($code, $description, $file, $line, $context);
    }

    /**
     * Handle uncaught exceptions.
     *
     * @param \Exception $exception Exception instance.
     * @return void
     * @throws \Exception When renderer class not found
     * @see http://php.net/manual/en/function.set-exception-handler.php
     */
    public function handleException(Exception $exception)
    {
        $sentryHandler = new SentryHandler();
        $sentryHandler->handle($exception);
        return parent::handleException($exception);
    }
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:background="@color/feed_bg"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.maximos.mobile.challengeapp.LoginActivity">

    <!-- Login progress -->
    <ProgressBar
        android:id="@+id/login_progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:visibility="gone"/>

    <ScrollView
        android:id="@+id/login_form"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <com.google.android.gms.common.SignInButton
                android:id="@+id/plus_sign_in_button"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="32dp"/>

            <LinearLayout
                android:id="@+id/plus_sign_out_buttons"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:visibility="gone"
                android:weightSum="2">

                <Button
                    android:id="@+id/plus_sign_out_button"
                    style="?android:textAppearanceSmall"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="@string/plus_sign_out"/>

                <Button
                    android:id="@+id/plus_disconnect_button"
                    style="?android:textAppearanceSmall"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:text="@string/plus_disconnect"/>

            </LinearLayout>

            <LinearLayout
                android:id="@+id/email_login_form"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">

                <AutoCompleteTextView
                    android:id="@+id/email"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/prompt_email"
                    android:inputType="textEmailAddress"
                    android:textColor="@color/black"
                    android:maxLines="1"
                    android:singleLine="true"/>

                <EditText
                    android:id="@+id/password"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:hint="@string/prompt_password"
                    android:imeActionId="@+id/login"
                    android:imeActionLabel="@string/action_sign_in_short"
                    android:imeOptions="actionUnspecified"
                    android:inputType="textPassword"
                    android:textColor="@color/black"
                    android:maxLines="1"
                    android:singleLine="true"/>

                <Button
                    android:id="@+id/email_sign_in_button"
                    style="?android:textAppearanceSmall"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:text="@string/action_sign_in"
                    android:textStyle="bold"/>
                <com.facebook.widget.LoginButton
                    android:id="@+id/fb_login_button"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="5dp"
                    facebook:confirm_logout="false"
                    facebook:fetch_user_info="true"
                    />

            </LinearLayout>
        </LinearLayout>
    </ScrollView>

</LinearLayout>