text:
#include "inc/hw_memmap.h"
#include "inc/hw_ssi.h"
#include "inc/hw_types.h"
#include "driverlib/ssi.h"
#include "driverlib/gpio.h"
#include "driverlib/sysctl.h"
#include "utils/uartstdio.h"

//*****************************************************************************
//
//! \addtogroup ssi_examples_list
//!
SPI Master (spi_master)

//!
//! This example shows how to configure the SSI0 as SPI Master.  The code will
//! send three characters on the master Tx then polls the receive FIFO until
//! 3 characters are received on the master Rx.
//!
//! This example uses the following peripherals and I/O signals.  You must
//! review these and change as needed for your own board:
//! - SSI0 peripheral
//! - GPIO Port A peripheral (for SSI0 pins)
//! - SSI0CLK - PA2
//! - SSI0Fss - PA3
//! - SSI0Rx  - PA4
//! - SSI0Tx  - PA5
//!
//! The following UART signals are configured only for displaying console
//! messages for this example.  These are not required for operation of SSI0.
//! - UART0 peripheral
//! - GPIO Port A peripheral (for UART0 pins)
//! - UART0RX - PA0
//! - UART0TX - PA1
//!
//! This example uses the following interrupt handlers.  To use this example
//! in your own application you must add these interrupt handlers to your
//! vector table.
//! - None.
//!
//
//*****************************************************************************

//*****************************************************************************
//
// Number of bytes to send and receive.
//
//*****************************************************************************
#define NUM_SSI_DATA 3

//*****************************************************************************
//
// This function sets up UART0 to be used for a console to display information
// as the example is running.
//
//*****************************************************************************
void
InitConsole(void)
{
    //
    // Enable GPIO port A which is used for UART0 pins.
    // TODO: change this to whichever GPIO port you are using.
    //
    SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);

    //
    // Configure the pin muxing for UART0 functions on port A0 and A1.
    // This step is not necessary if your part does not support pin muxing.
    // TODO: change this to select the port/pin you are using.
    //
    GPIOPinConfigure(GPIO_PA0_U0RX);
    GPIOPinConfigure(GPIO_PA1_U0TX);

    //
    // Select the alternate (UART) function for these pins.
    // TODO: change this to select the port/pin you are using.
    //
    GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);

    //
    // Initialize the UART for console I/O.
    //
    UARTStdioInit(0);
}

//*****************************************************************************
//
// Configure SSI0 in master Freescale (SPI) mode.  This example will send out
// 3 bytes of data, then wait for 3 bytes of data to come in.  This will all be
// done using the polling method.
//
//*****************************************************************************
int
main(void)
{
    unsigned long ulDataTx[NUM_SSI_DATA];
    unsigned long ulDataRx[NUM_SSI_DATA];
    unsigned long ulindex;

    //
    // Set the clocking to run directly from the external crystal/oscillator.
    // TODO: The SYSCTL_XTAL_ value must be changed to match the value of the
    // crystal on your board.
    //
    SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN |
                   SYSCTL_XTAL_16MHZ);

    //
    // Set up the serial console to use for displaying messages.  This is
    // just for this example program and is not needed for SSI operation.
    //
    InitConsole();

    //
    // Display the setup on the console.
    //
    UARTprintf("SSI ->\n");
    UARTprintf("  Mode: SPI\n");
    UARTprintf("  Data: 8-bit\n\n");

    //
    // The SSI0 peripheral must be enabled for use.
    //
    SysCtlPeripheralEnable(SYSCTL_PERIPH_SSI0);

    //
    // For this example SSI0 is used with PortA[5:2].  The actual port and pins
    // used may be different on your part, consult the data sheet for more
    // information.  GPIO port A needs to be enabled so these pins can be used.
    // TODO: change this to whichever GPIO port you are using.
    //
    SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);

    //
    // Configure the pin muxing for SSI0 functions on port A2, A3, A4, and A5.
    // This step is not necessary if your part does not support pin muxing.
    // TODO: change this to select the port/pin you are using.
    //
    GPIOPinConfigure(GPIO_PA2_SSI0CLK);
    GPIOPinConfigure(GPIO_PA3_SSI0FSS);
    GPIOPinConfigure(GPIO_PA4_SSI0RX);
    GPIOPinConfigure(GPIO_PA5_SSI0TX);

    //
    // Configure the GPIO settings for the SSI pins.  This function also gives
    // control of these pins to the SSI hardware.  Consult the data sheet to
    // see which functions are allocated per pin.
    // The pins are assigned as follows:
    //      PA5 - SSI0Tx
    //      PA4 - SSI0Rx
    //      PA3 - SSI0Fss
    //      PA2 - SSI0CLK
    // TODO: change this to select the port/pin you are using.
    //
    GPIOPinTypeSSI(GPIO_PORTA_BASE, GPIO_PIN_5 | GPIO_PIN_4 | GPIO_PIN_3 |
                   GPIO_PIN_2);

    //
    // Configure and enable the SSI port for SPI master mode.  Use SSI0,
    // system clock supply, idle clock level low and active low clock in
    // freescale SPI mode, master mode, 1MHz SSI frequency, and 8-bit data.
    // For SPI mode, you can set the polarity of the SSI clock when the SSI
    // unit is idle.  You can also configure what clock edge you want to
    // capture data on.  Please reference the datasheet for more information on
    // the different SPI modes.
    //
    SSIConfigSetExpClk(SSI0_BASE, SysCtlClockGet(), SSI_FRF_MOTO_MODE_0,
                       SSI_MODE_MASTER, 1000000, 8);

    //
    // Enable the SSI0 module.
    //
    SSIEnable(SSI0_BASE);

    //
    // Read any residual data from the SSI port.  This makes sure the receive
    // FIFOs are empty, so we don't read any unwanted junk.  This is done here
    // because the SPI SSI mode is full-duplex, which allows you to send and
    // receive at the same time.  The SSIDataGetNonBlocking function returns
    // "true" when data was returned, and "false" when no data was returned.
    // The "non-blocking" function checks if there is any data in the receive
    // FIFO and does not "hang" if there isn't.
    //
    while(SSIDataGetNonBlocking(SSI0_BASE, &ulDataRx[0]))
    {
    }

    //
    // Initialize the data to send.
    //
    ulDataTx[0] = 's';
    ulDataTx[1] = 'p';
    ulDataTx[2] = 'i';

    //
    // Display indication that the SSI is transmitting data.
    //
    UARTprintf("Sent:\n  ");

    //
    // Send 3 bytes of data.
    //
    for(ulindex = 0; ulindex < NUM_SSI_DATA; ulindex++)
    {
        //
        // Display the data that SSI is transferring.
        //
        UARTprintf("'%c' ", ulDataTx[ulindex]);

        //
        // Send the data using the "blocking" put function.  This function
        // will wait until there is room in the send FIFO before returning.
        // This allows you to assure that all the data you send makes it into
        // the send FIFO.
        //
        SSIDataPut(SSI0_BASE, ulDataTx[ulindex]);
    }

    //
    // Wait until SSI0 is done transferring all the data in the transmit FIFO.
    //
    while(SSIBusy(SSI0_BASE))
    {
    }

    //
    // Display indication that the SSI is receiving data.
    //
    UARTprintf("\nReceived:\n  ");

    //
    // Receive 3 bytes of data.
    //
    for(ulindex = 0; ulindex < NUM_SSI_DATA; ulindex++)
    {
        //
        // Receive the data using the "blocking" Get function. This function
        // will wait until there is data in the receive FIFO before returning.
        //
        SSIDataGet(SSI0_BASE, &ulDataRx[ulindex]);

        //
        // Since we are using 8-bit data, mask off the MSB.
        //
        ulDataRx[ulindex] &= 0x00FF;

        //
        // Display the data that SSI0 received.
        //
        UARTprintf("'%c' ", ulDataRx[ulindex]);
    }

    //
    // Return no errors
    //
    return(0);
}


text:
package mse.alg.ex3.PicsiSWT.gui;

import mse.alg.ex3.PicsiSWT.files.Document;
import mse.alg.ex3.PicsiSWT.files.PNM;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

// Swing style editor
public class Editor extends JFrame {
    {
        //Set Look & Feel
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    private static final long serialVersionUID = 1L;
    private JTextArea m_textPane;
    private JToolBar jToolBar;
    private JButton jSaveBtn;
    private JButton jSaveAsBtn;
    private JSlider jFontSizeSld;
    private String m_path;
    private boolean m_save;
    private MainWindow m_mainWnd;

    public Editor(MainWindow mainWnd) {
        m_mainWnd = mainWnd;
        {
            jToolBar = new JToolBar();
            jToolBar.setFloatable(false);
            {
                jSaveBtn = new JButton();
                jSaveBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/saveHS.png")));
                jSaveBtn.setToolTipText("Save");
                jSaveBtn.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        //System.out.println("jSaveBtn.actionPerformed, event="+evt);
                        saveFile(m_path == null);
                    }
                });
            }
            {
                jSaveAsBtn = new JButton();
                jSaveAsBtn.setIcon(new ImageIcon(getClass().getClassLoader().getResource("images/saveAsHS.png")));
                jSaveAsBtn.setToolTipText("Save As");
                jSaveAsBtn.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent evt) {
                        //System.out.println("jSaveAsBtn.actionPerformed, event="+evt);
                        saveFile(true);
                    }
                });
            }
            {
                // font size slider
                jFontSizeSld = new JSlider(JSlider.HORIZONTAL, 8, 36, 11);
                jFontSizeSld.setMaximumSize(new Dimension(100, 20));
                jFontSizeSld.setToolTipText("Font Size");
                jFontSizeSld.addChangeListener(new ChangeListener() {
                    public void stateChanged(ChangeEvent evt) {
                        //System.out.println("jFontSizeSld.stateChanged, event="+((JSlider)evt.getSource()).getValue());
                        m_textPane.setFont(m_textPane.getFont().deriveFont((float)((JSlider)evt.getSource()).getValue()));

                    }
                });
            }
            jToolBar.add(jSaveBtn);
            jToolBar.add(jSaveAsBtn);
            jToolBar.add(jFontSizeSld);
        }
        m_textPane = new JTextArea();
        m_textPane.setEditable(true);
        m_textPane.setOpaque(true);
        add(new JScrollPane(m_textPane), BorderLayout.CENTER);
        setBounds(100, 100, 700, 500);
        add(jToolBar, BorderLayout.PAGE_START);
    }

    public void openFile(String path) {
        m_path = path;
        setTitle(m_path);
        try {
            m_textPane.setText("");
            m_textPane.read(new FileReader(m_path), m_path);
        } catch(IOException e) {
            JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void openBinaryFile(Document doc, Image image, String path) {
        m_path = path;
        setTitle(m_path);
        m_textPane.setText("");
        m_mainWnd.displayTextOfBinaryImage(doc, image, m_textPane);
    }

    public void newFile() {
        m_path = null;
        setTitle("New Image");
        m_textPane.setText("");
    }

    private void saveFile(boolean createNew) {
        m_save = true;
        if (createNew) {
            // this Swing thread doesn't have direct access to SWT display thread, hence we need syncEcec
            Display.getDefault().syncExec(new Runnable() {
                public void run() {
                    MainWindow.StringInt si = m_mainWnd.chooseFileName();
                    if (si != null) {
                        m_path = si.filename;
                    } else {
                        m_save = false;
                    }
                }
            });
        }

        if (m_save) {
            try {
                // save image in ASCII format
                m_textPane.write(new FileWriter(m_path));

                // read header of written file and check validity
                if (! new PNM().checkHeader(m_path)) {
                    JOptionPane.showMessageDialog(this, "Invalid header.\nHeader has to be a valid PBM, PGM, or PPM image header (ASCII format).", "Error", JOptionPane.ERROR_MESSAGE);
                    return;
                }

                setTitle(m_path);

                // this Swing thread doesn't have direct access to SWT display thread, hence we need syncEcec
                Display.getDefault().syncExec(new Runnable() {
                    public void run() {
                        m_mainWnd.updateFile(m_path);
                    }
                });
            } catch(IOException e) {
                JOptionPane.showMessageDialog(this, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package mock

import (
	"bytes"
	"context"

	"github.com/blacklightcms/recurly"
)

var _ recurly.InvoicesService = &InvoicesService{}

// InvoicesService manages the interactions for invoices.
type InvoicesService struct {
	OnList      func(opts *recurly.PagerOptions) recurly.Pager
	ListInvoked bool

	OnListAccount      func(accountCode string, opts *recurly.PagerOptions) recurly.Pager
	ListAccountInvoked bool

	OnGet      func(ctx context.Context, invoiceNumber int) (*recurly.Invoice, error)
	GetInvoked bool

	OnGetPDF      func(ctx context.Context, invoiceNumber int, language string) (*bytes.Buffer, error)
	GetPDFInvoked bool

	OnPreview      func(ctx context.Context, accountCode string) (*recurly.Invoice, error)
	PreviewInvoked bool

	OnCreate      func(ctx context.Context, accountCode string, invoice recurly.Invoice) (*recurly.Invoice, error)
	CreateInvoked bool

	OnCollect      func(ctx context.Context, invoiceNumber int, collectInvoice recurly.CollectInvoice) (*recurly.Invoice, error)
	CollectInvoked bool

	OnMarkPaid      func(ctx context.Context, invoiceNumber int) (*recurly.Invoice, error)
	MarkPaidInvoked bool

	OnMarkFailed      func(ctx context.Context, invoiceNumber int) (*recurly.Invoice, error)
	MarkFailedInvoked bool

	OnRefundVoidLineItems      func(ctx context.Context, invoiceNumber int, refund recurly.InvoiceLineItemsRefund) (*recurly.Invoice, error)
	RefundVoidLineItemsInvoked bool

	OnRefundVoidOpenAmount      func(ctx context.Context, invoiceNumber int, refund recurly.InvoiceRefund) (*recurly.Invoice, error)
	RefundVoidOpenAmountInvoked bool

	OnVoidCreditInvoice      func(ctx context.Context, invoiceNumber int) (*recurly.Invoice, error)
	VoidCreditInvoiceInvoked bool

	OnRecordPayment      func(ctx context.Context, pmt recurly.OfflinePayment) (*recurly.Transaction, error)
	RecordPaymentInvoked bool
}

func (m *InvoicesService) List(opts *recurly.PagerOptions) recurly.Pager {
	m.ListInvoked = true
	return m.OnList(opts)
}

func (m *InvoicesService) ListAccount(accountCode string, opts *recurly.PagerOptions) recurly.Pager {
	m.ListAccountInvoked = true
	return m.OnListAccount(accountCode, opts)
}

func (m *InvoicesService) Get(ctx context.Context, invoiceNumber int) (*recurly.Invoice, error) {
	m.GetInvoked = true
	return m.OnGet(ctx, invoiceNumber)
}

func (m *InvoicesService) GetPDF(ctx context.Context, invoiceNumber int, language string) (*bytes.Buffer, error) {
	m.GetPDFInvoked = true
	return m.OnGetPDF(ctx, invoiceNumber, language)
}

func (m *InvoicesService) Preview(ctx context.Context, accountCode string) (*recurly.Invoice, error) {
	m.PreviewInvoked = true
	return m.OnPreview(ctx, accountCode)
}

func (m *InvoicesService) Create(ctx context.Context, accountCode string, invoice recurly.Invoice) (*recurly.Invoice, error) {
	m.CreateInvoked = true
	return m.OnCreate(ctx, accountCode, invoice)
}

func (m *InvoicesService) Collect(ctx context.Context, invoiceNumber int, collectInvoice recurly.CollectInvoice) (*recurly.Invoice, error) {
	m.CollectInvoked = true
	return m.OnCollect(ctx, invoiceNumber, collectInvoice)
}

func (m *InvoicesService) MarkPaid(ctx context.Context, invoiceNumber int) (*recurly.Invoice, error) {
	m.MarkPaidInvoked = true
	return m.OnMarkPaid(ctx, invoiceNumber)
}

func (m *InvoicesService) MarkFailed(ctx context.Context, invoiceNumber int) (*recurly.Invoice, error) {
	m.MarkFailedInvoked = true
	return m.OnMarkFailed(ctx, invoiceNumber)
}

func (m *InvoicesService) RefundVoidLineItems(ctx context.Context, invoiceNumber int, refund recurly.InvoiceLineItemsRefund) (*recurly.Invoice, error) {
	m.RefundVoidLineItemsInvoked = true
	return m.OnRefundVoidLineItems(ctx, invoiceNumber, refund)
}

func (m *InvoicesService) RefundVoidOpenAmount(ctx context.Context, invoiceNumber int, refund recurly.InvoiceRefund) (*recurly.Invoice, error) {
	m.RefundVoidOpenAmountInvoked = true
	return m.OnRefundVoidOpenAmount(ctx, invoiceNumber, refund)
}

func (m *InvoicesService) VoidCreditInvoice(ctx context.Context, invoiceNumber int) (*recurly.Invoice, error) {
	m.VoidCreditInvoiceInvoked = true
	return m.OnVoidCreditInvoice(ctx, invoiceNumber)
}

func (m *InvoicesService) RecordPayment(ctx context.Context, pmt recurly.OfflinePayment) (*recurly.Transaction, error) {
	m.RecordPaymentInvoked = true
	return m.OnRecordPayment(ctx, pmt)
}


text:
package org.oep.usermgt.service.impl;

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

import org.oep.usermgt.model.WorkingUnit;
import org.oep.usermgt.service.base.WorkingUnitLocalServiceBaseImpl;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.search.Indexable;
import com.liferay.portal.kernel.search.IndexableType;
import com.liferay.portal.model.ResourceConstants;
import com.liferay.portal.service.ServiceContext;

/**
 * The implementation of the Working Unit local service.
 *
 *

 * All custom service methods should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link org.oep.usermgt.service.WorkingUnitLocalService} interface.
 *
 *

 * This is a local service. Methods of this service will not have security checks based on the propagated JAAS credentials because this service can only be accessed from within the same VM.
 *

 *
 * @author NQMINH
 * @see org.oep.usermgt.service.base.WorkingUnitLocalServiceBaseImpl
 * @see org.oep.usermgt.service.WorkingUnitLocalServiceUtil
 */
public class WorkingUnitLocalServiceImpl extends WorkingUnitLocalServiceBaseImpl {
	/*
	 * NOTE FOR DEVELOPERS:
	 *
	 * Never reference this interface directly. Always use {@link org.oep.usermgt.service.WorkingUnitLocalServiceUtil} to access the Working Unit local service.
	 */
	/**
	 * Thêm mới mới đơn vị
	 *
	 * Version: OEP 2.0
	 *
	 * History:
	 *   DATE        AUTHOR      DESCRIPTION
	 *  -------------------------------------------------
	 *  21-September-2015  nqminh    Tạo mới
	 * @param userId:
	 * @param groupId:
	 * @param companyId:
	 * @param createDate:Ngày tạo
	 * @param modifiedDate:Ngay sửa
	 * @param organizationId:Tổ chức trong cổng
	 * @param govAgencyId:Cơ quan định danh
	 * @param name:Tên cơ đơn vị
	 * @param enName:Tên đơn vị tiếng anh
	 * @param parentWorkingUnitId:Đơn vị cấp trên
	 * @param address:Địa chỉ
	 * @param cityNo:
	 * @param cityName:Tỉnh/Thành phố
	 * @param districtNo:
	 * @param districtName:Quận/Huyện
	 * @param wardNo:
	 * @param wardName:Xã/Phường
	 * @param gpsPosition:Tọa độ
	 * @param telNo:Điện thoại
	 * @param fax:Fax
	 * @param email:Email
	 * @param website:Website
	 */
	@Indexable(type = IndexableType.REINDEX)
	public WorkingUnit addWorkingUnit(
			long organizationId,
			String govAgencyId,
			String name,
			String enName,
			long parentWorkingUnitId,
			String address,
			String cityNo,
			String cityName,
			String districtNo,
			String districtName,
			String wardNo,
			String wardName,
			String gpsPosition,
			String telNo,
			String fax,
			String email,
			String website,
			long localSiteId,
			int isEmployer,
			ServiceContext serviceContext) throws SystemException, PortalException {
		//validate(collectionName, dataCode, title, status);
		long id = counterLocalService.increment();
		WorkingUnit workingUnit = workingUnitPersistence.create(id);
		Date now = new Date();
		workingUnit.setOrganizationId(organizationId);
		workingUnit.setGovAgencyId(govAgencyId);
		workingUnit.setName(name);
		workingUnit.setEnName(enName);
		workingUnit.setParentWorkingUnitId(parentWorkingUnitId);
		workingUnit.setAddress(address);
		workingUnit.setCityNo(cityNo);
		workingUnit.setCityName(cityName);
		workingUnit.setDistrictNo(districtNo);
		workingUnit.setDistrictName(districtName);
		workingUnit.setWardNo(wardNo);
		workingUnit.setWardName(wardName);
		workingUnit.setGpsPosition(gpsPosition);
		workingUnit.setTelNo(telNo);
		workingUnit.setFax(fax);
		workingUnit.setEmail(email);
		workingUnit.setWebsite(website);
		workingUnit.setLocalSiteId(localSiteId);
		workingUnit.setIsEmployer(isEmployer);

		workingUnit.setCompanyId(serviceContext.getCompanyId());
		workingUnit.setGroupId(serviceContext.getScopeGroupId());
		workingUnit.setUserId(serviceContext.getUserId());
		workingUnit.setCreateDate(serviceContext.getCreateDate(now));
		workingUnit.setModifiedDate(serviceContext.getCreateDate(now));

		workingUnitPersistence.update(workingUnit);
		if (_log.isInfoEnabled()) {
			_log.info("Create new application " + id);
		}

		if (serviceContext.isAddGroupPermissions() || serviceContext.isAddGuestPermissions()) {
			_log.info("Create new application  1" + id);
			addWorkingUnitResources(workingUnit, serviceContext.isAddGroupPermissions(), serviceContext.isAddGuestPermissions(), serviceContext);

		}
		else {
			_log.info("Create new application 2" + id);
			addWorkingUnitResources(workingUnit, serviceContext.getGroupPermissions(), serviceContext.getGuestPermissions(), serviceContext);

		}
		return getWorkingUnit(id);
	}

	public WorkingUnit updateWorkingUnit(
			long workingUnitId,
			long organizationId,
			String govAgencyId,
			String name,
			String enName,
			long parentWorkingUnitId,
			String address,
			String cityNo,
			String cityName,
			String districtNo,
			String districtName,
			String wardNo,
			String wardName,
			String gpsPosition,
			String telNo,
			String fax,
			String email,
			String website,
			long localSiteId,
			int isEmployer,
			ServiceContext serviceContext)
		throws PortalException, SystemException {
		WorkingUnit workingUnit = workingUnitPersistence.findByPrimaryKey(workingUnitId);
		workingUnit.setOrganizationId(organizationId);
		workingUnit.setGovAgencyId(govAgencyId);
		workingUnit.setName(name);
		workingUnit.setEnName(enName);
		workingUnit.setParentWorkingUnitId(parentWorkingUnitId);
		workingUnit.setAddress(address);
		workingUnit.setCityNo(cityNo);
		workingUnit.setCityName(cityName);
		workingUnit.setDistrictNo(districtNo);
		workingUnit.setDistrictName(districtName);
		workingUnit.setWardNo(wardNo);
		workingUnit.setWardName(wardName);
		workingUnit.setGpsPosition(gpsPosition);
		workingUnit.setTelNo(telNo);
		workingUnit.setFax(fax);
		workingUnit.setEmail(email);
		workingUnit.setWebsite(website);
		workingUnit.setLocalSiteId(localSiteId);
		workingUnit.setIsEmployer(isEmployer);
		Date now = new Date();
		workingUnit.setModifiedDate(serviceContext.getModifiedDate(now));
		workingUnitPersistence.update(workingUnit);

		if ((serviceContext.getGroupPermissions() != null) ||
			(serviceContext.getGuestPermissions() != null)) {

			updateWorkingUnitResources(
				workingUnit, serviceContext.getGroupPermissions(),
				serviceContext.getGuestPermissions(), serviceContext);
		}

		return getWorkingUnit(workingUnit.getWorkingUnitId());
	}
	public WorkingUnit saveWorkingUnit(WorkingUnit workingUnit, ServiceContext serviceContext) throws PortalException, SystemException {
		return updateWorkingUnit(workingUnit.getWorkingUnitId(),
				workingUnit.getOrganizationId(),
				workingUnit.getGovAgencyId(),
				workingUnit.getName(),
				workingUnit.getEnName(),
				workingUnit.getParentWorkingUnitId(),
				workingUnit.getAddress(),
				workingUnit.getCityNo(),
				workingUnit.getCityName(),
				workingUnit.getDistrictNo(),
				workingUnit.getDistrictName(),
				workingUnit.getWardNo(),
				workingUnit.getWardName(),
				workingUnit.getGpsPosition(),
				workingUnit.getTelNo(),
				workingUnit.getFax(),
				workingUnit.getEmail(),
				workingUnit.getWebsite(),
				workingUnit.getLocalSiteId(),
				workingUnit.getIsEmployer(),
				serviceContext);
	}

	public void updateWorkingUnitResources(
			WorkingUnit workingUnit, String[] groupPermissions,
			String[] guestPermissions, ServiceContext serviceContext)
		throws PortalException, SystemException {

		resourceLocalService.updateResources(
			workingUnit.getCompanyId(), serviceContext.getGuestOrUserId(),
			WorkingUnit.class.getName(), workingUnit.getWorkingUnitId(), groupPermissions,
			guestPermissions);
	}
	public void removeWorkingUnit(WorkingUnit workingUnit) throws PortalException, SystemException {
		workingUnitPersistence.remove(workingUnit);
		resourceLocalService.deleteResource(workingUnit.getCompanyId(), WorkingUnit.class.getName(), ResourceConstants.SCOPE_INDIVIDUAL, workingUnit.getWorkingUnitId());
	}

	public void removeWorkingUnit(long id) throws PortalException, SystemException {
		WorkingUnit workingUnit = workingUnitPersistence.findByPrimaryKey(id);
		removeWorkingUnit(workingUnit);
	}

	public WorkingUnit getWorkingUnit(long id) throws PortalException, SystemException {
		return workingUnitPersistence.findByPrimaryKey(id);
	}

	public void addWorkingUnitResources(WorkingUnit workingUnit, boolean addGroupPermission, boolean addGuestPermission, ServiceContext serviceContext) throws PortalException, SystemException {
		resourceLocalService.addResources(workingUnit.getCompanyId(), serviceContext.getScopeGroupId(), serviceContext.getUserId(), WorkingUnit.class.getName(), workingUnit.getWorkingUnitId(), false, addGroupPermission, addGuestPermission);
	}

	public void addWorkingUnitResources(WorkingUnit workingUnit, String[] groupPermissions, String[] guestPermissions, ServiceContext serviceContext) throws PortalException, SystemException {
		resourceLocalService.addModelResources(workingUnit.getCompanyId(), serviceContext.getScopeGroupId(), serviceContext.getUserId(), WorkingUnit.class.getName(), workingUnit.getWorkingUnitId(), groupPermissions, guestPermissions);
	}

	public void addWorkingUnitResources(long id, String[] groupPermissions, String[] guestPermissions, ServiceContext serviceContext) throws PortalException, SystemException {
		WorkingUnit workingUnit = workingUnitPersistence.findByPrimaryKey(id);
		addWorkingUnitResources(workingUnit, groupPermissions, guestPermissions, serviceContext);
	}
	/* Company */
	public int countWorkingUnitByCompany(ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.countByC(serviceContext.getCompanyId());
	}

	public List<WorkingUnit> getByCompany(ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.findByC(serviceContext.getCompanyId());
	}

	public List<WorkingUnit> getByCompany(int start, int end, ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.findByC(serviceContext.getCompanyId(), start, end);
	}

	/* Company AND parentWorkingUnit*/
	public int countWorkingUnitByCompanyParentWorkingUnit(long parentWorkingUnitId,ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.countByC_PW(serviceContext.getCompanyId(),parentWorkingUnitId);
	}

	public List<WorkingUnit> getByCompanyParentWorkingUnit(long parentWorkingUnitId, ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.findByC_PW(serviceContext.getCompanyId(),parentWorkingUnitId);
	}

	public List<WorkingUnit> getByCompanyParentWorkingUnit(long parentWorkingUnitId, int start, int end, ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.findByC_PW(serviceContext.getCompanyId(),parentWorkingUnitId, start, end);
	}

	/* Group  */
	public int countWorkingUnitByGroup(ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.countByG(serviceContext.getScopeGroupId());
	}

	public List<WorkingUnit> getByGroup(ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.findByG(serviceContext.getScopeGroupId());
	}

	public List<WorkingUnit> getByGroup(int start, int end, ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.findByC(serviceContext.getScopeGroupId(), start, end);
	}
	/* Group AND parentWorkingUnit*/
	public int countWorkingUnitByGroupParentWorkingUnit(long parentWorkingUnitId,ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.countByG_PW(serviceContext.getScopeGroupId(),parentWorkingUnitId);
	}

	public List<WorkingUnit> getByGroupParentWorkingUnit(long parentWorkingUnitId, ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.findByG_PW(serviceContext.getScopeGroupId(),parentWorkingUnitId);
	}

	public List<WorkingUnit> getByGroupParentWorkingUnit(long parentWorkingUnitId, int start, int end, ServiceContext serviceContext) throws PortalException, SystemException {
		return workingUnitPersistence.findByG_PW(serviceContext.getScopeGroupId(),parentWorkingUnitId, start, end);
	}

	/* Tim theo ten */
	public int countWorkingUnitByLikeName(String textSearch, long parentWorkingUnitId, ServiceContext serviceContext) throws SystemException {
		return workingUnitFinder.countByLikeName(textSearch,parentWorkingUnitId,serviceContext);
	}

	public List<WorkingUnit> finderByLikeName(String textSearch, long parentWorkingUnitId,ServiceContext serviceContext) throws SystemException {
		return workingUnitFinder.findByLikeName(textSearch, parentWorkingUnitId, serviceContext);
	}

	public List<Object[]> finderByLikeNameShort(String textSearch, long parentWorkingUnitId,ServiceContext serviceContext) throws SystemException {
		return workingUnitFinder.findByLikeNameShort(textSearch, parentWorkingUnitId, serviceContext);
	}

	public List<WorkingUnit> finderByLikeName(String textSearch, long parentWorkingUnitId,int startIndex, int endIndex, ServiceContext serviceContext) throws SystemException {
		return workingUnitFinder.findByLikeName(textSearch, parentWorkingUnitId, startIndex, endIndex, serviceContext);
	}

	public List<Object[]> finderByLikeNameShort(String textSearch, long parentWorkingUnitId,int startIndex, int endIndex, ServiceContext serviceContext) throws SystemException {
		return workingUnitFinder.findByLikeNameShort(textSearch, parentWorkingUnitId, startIndex, endIndex, serviceContext);
	}

	public List<WorkingUnit> getByCompanyTree (ServiceContext serviceContext) throws SystemException {
		ArrayList<WorkingUnit> kq = new ArrayList<WorkingUnit>();

		List<WorkingUnit> luu = workingUnitPersistence.findByC_PW(serviceContext.getCompanyId(),0);
		//System.out.println(" rrrrrrrrrrr " + luu.size());
		int i = 0;
		 kq.addAll(luu);
		 while (i < kq.size()){
			 List<WorkingUnit> tg = workingUnitPersistence.findByC_PW(serviceContext.getCompanyId(),kq.get(i).getWorkingUnitId());
			// System.out.println(" ttttttt " + tg.size());
			 i++;
			 if (tg.size() > 0)  kq.addAll(i, tg);
		 }
		return kq;
	}
	private static Log _log = LogFactoryUtil.getLog(WorkingUnitLocalServiceImpl.class);
}


text:
apt-get update

# Install development components.
apt-get install -y --no-install-recommends build-essential make

# Clean up system
apt-get clean
rm -rf /tmp/* /var/tmp/*
rm -rf /var/lib/apt/lists/*

# Create a default user
useradd -s /bin/bash -m devbase
# Set password for the user
echo "devbase:devbase" | chpasswd
echo "devbase ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers


text:
package com.amazonaws.services.simpleemail.model;
import com.amazonaws.AmazonWebServiceRequest;

/**
 * Container for the parameters to the {@link com.amazonaws.services.simpleemail.AmazonSimpleEmailService#getSendStatistics(GetSendStatisticsRequest) GetSendStatistics operation}.
 *

 * Returns the user's sending statistics. The result is a list of data
 * points, representing the last two weeks of sending activity.
 *

 *

 * Each data point in the list contains statistics for a 15-minute
 * interval.
 *

 *
 * @see com.amazonaws.services.simpleemail.AmazonSimpleEmailService#getSendStatistics(GetSendStatisticsRequest)
 */
public class GetSendStatisticsRequest extends AmazonWebServiceRequest {

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        sb.append("}");
        return sb.toString();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketBase.Command;

namespace SuperSocket.SocketBase
{
    /// <summary>
    /// Command Executing Context
    /// </summary>
    public class CommandExecutingContext
    {
        /// <summary>
        /// Gets the session.
        /// </summary>
        public IAppSession Session { get; private set; }

        /// <summary>
        /// Gets the request info.
        /// </summary>
        public IRequestInfo RequestInfo { get; private set; }

        /// <summary>
        /// Gets the current command.
        /// </summary>
        public ICommand CurrentCommand { get; private set; }

        /// <summary>
        /// Gets or sets a value indicating whether this command executing is cancelled.
        /// </summary>
        /// <value>
        ///   <c>true</c> if cancel; otherwise, <c>false</c>.
        /// </value>
        public bool Cancel { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="CommandExecutingContext"/> class.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="requestInfo">The request info.</param>
        /// <param name="command">The command.</param>
        public CommandExecutingContext(IAppSession session, IRequestInfo requestInfo, ICommand command)
        {
            Session = session;
            RequestInfo = requestInfo;
            CurrentCommand = command;
        }
    }
}


text:
import Car from './car';
import NetworkCoordinator from './networkcoordinator';
import {Observable} from '@reactivex/rxjs';

class ExchangeProxy
{
  private networkCoordinator: NetworkCoordinator;

  constructor ()
  {
    this.networkCoordinator = new NetworkCoordinator();
  }

  public commissionInfo$ (): Observable<any>
  {
    // Observables rely on a shared network request loop which they use to repeatedly retrieve values on timers via web API.

    return Observable.timer(0, 3000).concatMap((x) => { return Observable.of(x) }); //placeholder
  }

  public inventory$ (): Observable<Array<Car>>
  {
    return Observable.timer(0, 2000).concatMap(() => { return Observable.of([new Car(), new Car(), new Car()]) }); //placeholder
  }
}

export default ExchangeProxy;


text:
<?php

namespace ejonasson\SunlightAPI\API;

use GuzzleHttp;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Exception\RequestException;
use Cache;
use Carbon\Carbon;

use ejonasson\SunlightAPI\Exception\SunlightAPIException;
use ejonasson\SunlightAPI\Response\SunlightAPIResponse;

abstract class APIRequest
{
    protected $api_key;
    protected $response;
    protected $endpoint;
    protected $args;
    protected $request_type;

    public function __construct($endpoint = '', $args = array())
    {
        $this->api_key = config('sunlightapi.sunlight_api_key');
        $this->endpoint = $endpoint;
        $this->args = $this->setInitialArgs($args);
    }

    abstract public function getUrl();
    abstract public function getPrevious();
    abstract public function getNext();

    public function get()
    {
        return $this->getResponse();
    }

    public function getApiKey()
    {
        return $this->api_key;
    }

    public function getResponse()
    {
        if ($this->checkCache()) {
            $this->response = $this->getCachedResult();
            return $this->response;
        }

        if (!$this->response) {
            $this->response = $this->request();
        }

        $this->cacheResponse();
        return $this->response;
    }

    public function request($args = array(), $use_cache = true)
    {
        if (empty($this->endpoint)) {
            throw new SunlightAPIException('Cannot make API Request: No Endpoint set.');
        }

        if (empty($args)) {
            $args = $this->args;
        }
        $url = $this->getUrl() . $this->endpoint . $this->encodeArgs($args);
        $client = new GuzzleHttp\Client(['base_uri' => $url]);
        try {
            $res = $client->request('GET', '', [
                'headers' => [
                            'X-APIKEY' => $this->getApiKey()
                            ]
                ]);
            if ($this->responseIsJSON($res)) {
                $data = json_decode($res->getBody());
                $this->response = new SunlightAPIResponse($data);
                return $this->response;
            } else {
                throw new SunlightAPIException('Valid JSON not retreived by API');
            }
        } catch (RequestException $e) {
            throw new SunlightAPIException($e->getMessage());
        }
    }

    public function addParams(array $params)
    {
        $this->args = array_merge($params, $this->args);
        return $this;
    }

    public function getParams()
    {
        return $this->args;
    }

    public function setEndpoint($endpoint)
    {
        $this->endpoint = $endpoint;
        return $this;
    }

    /**
     * Reset Parameters to the default Argusments
     * @return $this
     */
    public function resetParams()
    {
        $this->args = [];
        $this->args = $this->setInitialArgs($this->args);
        return $this;
    }

    protected function encodeArgs($args)
    {
        $output = '?';
        foreach ($args as $key => $value) {
            $string = $key . '=' . $value . '&';
            $output .= $string;
        }
        return $output;
    }

    protected function responseIsJson($response)
    {
        $results = json_decode($response->getBody());
        if (json_last_error() == JSON_ERROR_NONE) {
            return true;
        }
        return false;
    }

    /**
     * Set any default arguments for this API Here
     * Override this function in the parent if there are additional default args
     * @param array $args
     */
    protected function setInitialArgs($args)
    {
        return $args;
    }

    /* --------------------------------------------------------------------
        Caching Functionality for API Responses
    ------------------------------------------------------------------------------*/
    protected function checkCache()
    {
        $cache_name = $this->getCacheName();
        return Cache::has($cache_name);
    }

    protected function getCachedResult()
    {
        $cache_name = $this->getCacheName();
        return Cache::get($cache_name);
    }

    protected function cacheResponse()
    {
        $cache_name = $this->getCacheName();
        $cache_duration = config('sunlightapi.cache_duration', 60);
        $expires = Carbon::now()->addMinutes($cache_duration);
        if ($cache_duration > 0) {
            Cache::put($cache_name, $this->response, $expires);
        }

        return $this->response;
    }

    protected function getCacheName()
    {
        // Generate a MD5 hash as a cache name
        // This hash combines a serialization of the $args array, along with the endpoint name
        // Along with the endpoint URL
        // So identical requests should match this hash
        $args_string = serialize($this->args);
        $hash_string = $this->url . $args_string . $this->endpoint;
        $cache_name = 'SunlightAPIRequest_' . md5($hash_string);
        return $cache_name;
    }
}


text:
[![Android Studio](https://img.shields.io/badge/Android%20Studio-3.0-brightgreen.svg?style=flat)](https://developer.android.com/studio/index.html)

Android sample project shows new stuff about support library, architecture, etc.

## Get ready

* Download dependencies (using curl): OpenCV4Android.

```
$ cd DroidTurbo/
$ ./get_ready.sh
```

Besides, you could checkout `master-cuda` to use CUDA.

The samples marked by "\*" means having cuda implementations.

## Sample modules

### Menu

* Terminal
* Transparent StatusBar
* Snake SurfaceView
* Grayscale *

[PNG](https://github.com/joinAero/DroidTurbo/blob/master/images/menu/menu.png?raw=true)

### Widget

Samples about new APIs in support libraries.

#### Support

* All Apps: Show all apps in list or grid. [GIF](https://raw.githubusercontent.com/joinAero/DroidTurbo/master/app/src/main/assets/all_apps.gif?raw=true)
* Rx Apps: Show all apps with RxJava. [GIF](https://raw.githubusercontent.com/joinAero/DroidTurbo/master/app/src/main/assets/rx_apps.gif?raw=true)

[PNG](https://github.com/joinAero/DroidTurbo/blob/master/images/widget/support.png?raw=true)

#### Design

* Bottom Sheet: How to using bottom sheet.

[PNG](https://github.com/joinAero/DroidTurbo/blob/master/images/widget/design.png?raw=true)

#### Hardware

* Camera2 Basic: How to use basic functionalities of Camera2 API.
* Camera2 Image: How to capture image without preview using Camera2 API.

#### Custom

[PNG](https://github.com/joinAero/DroidTurbo/blob/master/images/widget/custom.png?raw=true)

#### Extras

* Toolbar, TabLayout. [GIF](https://github.com/joinAero/DroidTurbo/blob/master/images/toolbar.gif?raw=true)

### Fever

Samples about fever things.

#### OpenGL ES

* Hello GL2: Draws a triangle using GLES 2.0 API.
* Hello Cube: Draws a cube using GLES 1.x API.
* San Angeles: San Angeles Observation OpenGL ES version example.

[PNG](https://github.com/joinAero/DroidTurbo/blob/master/images/fever/gles.png?raw=true)

#### OpenCV

* Tutorial 1: OpenCV Tutorial 1: Camera Preview.
* Tutorial 2: OpenCV Tutorial 2: Mixed Processing.
* Tutorial 3: OpenCV Tutorial 3: Camera Control.
* Camera Calibration: OpenCV Camera Calibration.
* Face Detection: OpenCV Face Detection.
* OpenCV Grayscale: OpenCV Grayscale Sample. *
* OpenCV ORB: OpenCV ORB Sample. *

[PNG](https://github.com/joinAero/DroidTurbo/blob/master/images/fever/ocv.png?raw=true)

### Arch

Samples about latest architectures.

#### References

* [Android Architecture Blueprints](https://github.com/googlesamples/android-architecture)
* [Android Architecture Components](https://developer.android.com/topic/libraries/architecture/index.html)
* [Android Architecture Components samples](https://github.com/googlesamples/android-architecture-components)

## Third Party

* [Butter Knife](https://github.com/JakeWharton/butterknife)
* [RxAndroid](https://github.com/ReactiveX/RxAndroid)
* [android-gif-drawable](https://github.com/koral--/android-gif-drawable)

## License

    Copyright 2015 joinAero

    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.

[Studio Keymaps]: http://www.developerphil.com/android-studio-tips-tricks-moving-around/


text:
static const void * TouchUpInSideBlockKey = @"TouchUpInSideBlockKey";
static const void *  Indentifier = @"indentifier";
@implementation UIButton (Click)
- (void)setClickAction:(void (^)(UIButton *))clickAction{
//    object:与谁关联,通常传self
//    key:唯一键,在获取值时通过该键获取,通常使用static const void * 来声明
//    value:关联所设置的值
//    policy:内存管理策略,比如使用copy
//        OBJC_ASSOCIATION_ASSIGN = 0,  表示弱引用关联,通常是基本数据类型,如int、float
//
//        OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, 表示强(strong)引用关联
//
//        OBJC_ASSOCIATION_COPY_NONATOMIC = 3,表示关联对象copy
//
//        OBJC_ASSOCIATION_RETAIN = 01401,  表示强(strong)引用关联对象,线程安全
//
//        OBJC_ASSOCIATION_COPY = 01403  表示关联对象copy 线程安全
//    OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy);

    objc_setAssociatedObject(self, TouchUpInSideBlockKey, clickAction, OBJC_ASSOCIATION_COPY);
    if (clickAction) {
        [self addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    }
}
-(void (^)(UIButton *))clickAction{
    return objc_getAssociatedObject(self, TouchUpInSideBlockKey);
}
- (void)buttonClicked:(UIButton *)sender{
    if (self.clickAction) {
        self.clickAction(sender);
    }
}
-(void)setIndentifier:(NSString *)indentifier{
    objc_setAssociatedObject(self, Indentifier, indentifier, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSString *)indentifier{
    return objc_getAssociatedObject(self, Indentifier);
}
@end


text:
'use strict';

module.exports = {
    dateFormat: 'D MMMM YYYY',
    user: {
        wrongPasswordOrNameMessage: 'Неверное имя пользователя или пароль.',
        passwordRequiredMessage: 'Введите пароль.',
        alreadyExistsPattern: username => `${username} уже зарегистрирован`,
        incorrectEmail: 'Некорректный email',
        emailRegEx: /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+.[A-Za-z]{2,4}/im,
        emptySignUpField: 'Для регистрации необходимо ввести email, username, password',
        saltRounds: 10
    },
    comment: {
        maxLength: 300
    }
};


text:
CFWL_MessageKey::CFWL_MessageKey(CFWL_Widget* pDstTarget,
                                 FWL_KeyCommand cmd,
                                 uint32_t flags,
                                 uint32_t keycode)
    : CFWL_Message(CFWL_Message::Type::Key, nullptr, pDstTarget),
      m_dwCmd(cmd),
      m_dwFlags(flags),
      m_dwKeyCode(keycode) {}

CFWL_MessageKey::~CFWL_MessageKey() = default;


text:
<!DOCTYPE HTML>

Tests invalidation on align-items style change. Passes if there is no red.


text:
// vim:filetype=java:ts=4

package junit.com.mcdermottroe.exemplar.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;

import com.mcdermottroe.exemplar.output.OutputException;
import com.mcdermottroe.exemplar.output.OutputUtils;
import com.mcdermottroe.exemplar.utils.Files;

import junit.com.mcdermottroe.exemplar.UtilityClassTestCase;

/** Test class for {@link com.mcdermottroe.exemplar.utils.Files}.

	@author	Conor McDermottroe
	@since	0.2
*/
public class FilesTest
extends UtilityClassTestCase<Files>
{
	/** A root directory for this test. */
	private File testDirectory;

	/** {@inheritDoc} */
	@Override public void setUp()
	throws Exception
	{
		super.setUp();
		testDirectory = new File(TMP, getClass().getName());
	}

	/** Test {@link Files#findDirectories(File)}. */
	public void testFindDirectories() {
		// Give a clean test directory
		removeTestTree();
		createTestTree();

		// Create the expected set
		File fooDir = new File(testDirectory, "foo");
		File barDir = new File(fooDir, "bar");
		Collection<File> expected = new ArrayList<File>();
		expected.add(testDirectory);
		expected.add(fooDir);
		expected.add(barDir);

		// Do the test.
		Collection<File> found = Files.findDirectories(testDirectory);
		assertTrue(
			"Expected directory list did not match found directory list",
			expected.containsAll(found) && found.containsAll(expected)
		);

		// Clean up
		removeTestTree();
	}

	/** Test {@link Files#findFiles(File)}. */
	public void testFindFiles() {
		// Give a clean test directory
		removeTestTree();
		createTestTree();

		// Create the expected set
		File fooDir = new File(testDirectory, "foo");
		File barDir = new File(fooDir, "bar");
		File bazFile = new File(fooDir, "baz");
		File quuxFile = new File(barDir, "quux");
		Collection<File> expected = new ArrayList<File>();
		expected.add(bazFile);
		expected.add(quuxFile);

		// Do the test.
		Collection<File> found = Files.findFiles(testDirectory);
		assertTrue(
			"Expected directory list did not match found directory list",
			expected.containsAll(found) && found.containsAll(expected)
		);

		// Clean up
		removeTestTree();
	}

	/** Test {@link Files#removeTree(File)}. */
	public void testRemoveTree() {
		removeTestTree();
		createTestTree();
		Files.removeTree(testDirectory);
		assertFalse("Test directory still exists", testDirectory.exists());
	}

	/** Test {@link Files#readFile(String, File)}. */
	public void testReadFile() {
		removeTestTree();
		createTestTree();
		String[] strings = {
			new File(new File(testDirectory, "foo"), "baz").getAbsolutePath(),
			"baz",
		};
		File[] files = {
			null,
			new File(testDirectory, "foo"),
		};

		assertEquals("Broken test data", strings.length, files.length);
		for (int i = 0; i < strings.length; i++) {
			try {
				InputStream result = Files.readFile(strings[i], files[i]);
				result.close();
				assertNotNull("readFile returned null", result);
			} catch (IOException e) {
				assertNotNull("IOException was null", e);
				e.printStackTrace();
				fail("readFile threw an exception");
			}
		}
	}

	/** Test {@link Files#readFile(String, File)}. */
	public void testReadFileNegative() {
		removeTestTree();
		createTestTree();
		String[] strings = {
			null,
			"foo",
			"foo",
			"http://non.existant.url.this.does.not.exist.com/nothere.html",
		};
		File[] files = {
			null,
			testDirectory,
			new File("foo"),
			null,
		};

		assertEquals("Broken test data", strings.length, files.length);
		for (int i = 0; i < strings.length; i++) {
			try {
				InputStream result = null;
				boolean failed = false;
				try {
					result = Files.readFile(strings[i], files[i]);
					assertNotNull("readFile returned null", result);
				} catch (AssertionError e) {
					failed = true;
					assertNotNull("AssertionError was null", e);
				}
				if (!failed) {
					fail("readFile fell through");
				}
			} catch (IOException e) {
				assertNotNull("IOException was null", e);
			}
		}
	}

	/** Create a test tree of files and directories. */
	private void createTestTree() {
		File fooDir = new File(testDirectory, "foo");
		File barDir = new File(fooDir, "bar");
		File bazFile = new File(fooDir, "baz");
		File quuxFile = new File(barDir, "quux");

		// Make the directories
		assertFalse("Test directory already exists", testDirectory.exists());
		testDirectory.mkdirs();
		assertTrue("Test directory did not create", testDirectory.exists());
		fooDir.mkdirs();
		assertTrue("foo directory did not create", fooDir.exists());
		barDir.mkdirs();
		assertTrue("bar directory did not create", barDir.exists());

		// Make the files
		try {
			OutputUtils.writeStringToFile("baz", bazFile);
			OutputUtils.writeStringToFile("quux", quuxFile);
		} catch (OutputException e) {
			assertNotNull("OutputException was null", e);
			fail("OutputException thrown when writing files");
		}
	}

	/** Remove the test tree created by {@link #createTestTree()}. */
	private void removeTestTree() {
		File fooDir = new File(testDirectory, "foo");
		File barDir = new File(fooDir, "bar");
		File bazFile = new File(fooDir, "baz");
		File quuxFile = new File(barDir, "quux");

		File[] filesToDelete = {
			quuxFile,
			bazFile,
			barDir,
			fooDir,
			testDirectory,
		};
		for (File f : filesToDelete) {
			if (f.exists()) {
				f.delete();
				assertFalse(
					"File still exists: " + f.getAbsolutePath(),
					f.exists()
				);
			}
		}
	}

	/** Test {@link Files#tempDir(String)}. */
	public void testTempDir() {
		File systemTempDir = new File(System.getProperty("java.io.tmpdir"));
		String[] args = {
			null,
			"",
			"foo",
			"foo",
		};
		File[] result = {
			null,
			null,
			new File(systemTempDir, "foo"),
			new File(systemTempDir, "foo"),
		};

		for (int i = 0; i < args.length; i++) {
			assertEquals(
				"Output did not match expected",
				result[i],
				Files.tempDir(args[i])
			);
		}
		for (File f : result) {
			if (f != null) {
				Files.removeTree(f);
			}
		}
	}
}


text:
require 'rspec'
require File.dirname(__FILE__) + '/calc.rb'

describe 'CALC' do

  it 'should retrieve 0 if input is EMPTY string' do
    calc = CALC.new
    expect(calc.add('')).to eq 0
  end

  it 'should retrieve the same if input is one number' do
    calc = CALC.new
    expect(calc.add('1')).to eq 1
  end

  it 'should retrieve sum of two entered numbers' do
    calc = CALC.new
    expect(calc.add('1,2')).to eq 3
  end

  it 'should retrieve sum of 5 entered numbers' do
    calc = CALC.new
    expect(calc.add('1,2,3,4,5')).to eq 15
  end

  it 'should retrieve sum of 10 entered numbers' do
    calc = CALC.new
    expect(calc.add('1,2,3,4,5,6,7,8,9,10')).to eq 55
  end

  it 'should retrieve sum of entered numbers even if delimiter is "\n"' do
    calc = CALC.new
    expect(calc.add('1\n2,3')).to eq 6
  end

  it 'should retrieve the same entered numbers even if string contains "\n"' do
    calc = CALC.new
    expect(calc.add('1,\n')).to eq 1
  end

  it 'should retrieve sum of entered numbers even if delimiter is ";" and string contains "\n" or other rubbish' do
    calc = CALC.new
    expect(calc.add('//;\n1;2')).to eq 3
  end

  it 'should throw an exception if there is a negative value' do
    calc = CALC.new
    expect{calc.add('-1,2')}.to raise_error(RuntimeError)
  end

  it 'should throw an exception if there are negatives with values' do
    calc = CALC.new
    expect{calc.add('-1,-2,4,5,-3')}.to raise_error(RuntimeError, 'Negatives not allowed: -1,-2,-3')
  end

  it 'all values more than 1000 have to be ignored' do
    calc = CALC.new
    expect(calc.add('2,1001')).to eq 2
  end

end


text:
package org.wildfly.swarm.management.runtime;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.wildfly.swarm.config.management.HTTPInterfaceManagementInterface;
import org.wildfly.swarm.config.runtime.AttributeDocumentation;
import org.wildfly.swarm.management.ManagementFraction;
import org.wildfly.swarm.spi.api.Customizer;
import org.wildfly.swarm.spi.api.Defaultable;
import org.wildfly.swarm.spi.api.SocketBinding;
import org.wildfly.swarm.spi.api.SocketBindingGroup;
import org.wildfly.swarm.spi.api.annotations.Configurable;
import org.wildfly.swarm.spi.runtime.annotations.Pre;

import static org.wildfly.swarm.spi.api.Defaultable.string;

/**
 * @author Bob McWhirter
 */
@Pre
@ApplicationScoped
public class ManagementSocketBindingsCustomizer implements Customizer {

    @Inject
    @Named("standard-sockets")
    private SocketBindingGroup group;

    @Inject
    ManagementFraction fraction;

    public void customize() {
        this.group.socketBinding(
                new SocketBinding("management-http")
                        .iface(iface.get())
                        .port(fraction.httpPort()));
        this.group.socketBinding(new SocketBinding("management-https")
                .port(fraction.httpsPort()));

        if (fraction.isHttpDisable()) {
            fraction.httpInterfaceManagementInterface((HTTPInterfaceManagementInterface<?>) null);
        }
    }

    @AttributeDocumentation("Interface to bind for the management ports")
    @Configurable("thorntail.management.bind.interface")
    private Defaultable<String> iface = string("management");
}


text:
<!DOCTYPE html>

    <meta content='text/html; charset=utf-8' http-equiv='Content-Type' />
    <meta content='en' name='lang' />
    <meta name='viewport' content='width=device-width' />
    <meta name="description" content="Information about Anchovy (Other)." />
    <meta name="keywords" content="fish, guide, sustainability, Anchovy (Other)" />
    <title>Anchovy (Other)</title>
    <link href='../css/screen.css' media='all' rel='stylesheet' type='text/css' />

    <link href='i/favicon.png' id='favicon' rel='icon' type='image/png' />
    <link href='i/touch.png' id='touch' rel='apple-touch-icon' />
    <link href='i/retina.png' id='retina' rel='apple-touch-icon' sizes='114x114' />

        Anchovy (Other)

Small fish, known for their strong flavour when cured.

      ← Back to list of fishes

Sources:

Marine Conservation Society

Monterey Bay Aquarium

FDA Mercury Table

      The MCS rates Atlantic anchovy as 2-3, and is currently evaluating other fisheries. The Monterey Bay Aquarium states that anchovy from the Black and Mediterranean seas is unsustainable.


text:
package lib.morkim.examples.backendimpl;

import dagger.Module;
import dagger.Provides;
import lib.morkim.examples.backendinterfaces.BackEndCall;

@Module
public class BackEndModule {

	@Provides
	BackEndCall providesBackEndCall() {
		return new BackEndCallImpl();
	}
}


text:
#ifndef __OPENCV_EMD_L1_HPP__
#define __OPENCV_EMD_L1_HPP__

#include BOSS_OPENCV_U_opencv2__core_hpp //original-code:"opencv2/core.hpp"

namespace cv
{
/****************************************************************************************\
*                                   EMDL1 Function                                      *
\****************************************************************************************/

//! @addtogroup shape
//! @{

/** @brief Computes the "minimal work" distance between two weighted point configurations base on the papers
"EMD-L1: An efficient and Robust Algorithm for comparing histogram-based descriptors", by Haibin
Ling and Kazunori Okuda; and "The Earth Mover's Distance is the Mallows Distance: Some Insights from
Statistics", by Elizaveta Levina and Peter Bickel.

@param signature1 First signature, a single column floating-point matrix. Each row is the value of
the histogram in each bin.
@param signature2 Second signature of the same format and size as signature1.
 */
CV_EXPORTS float EMDL1(InputArray signature1, InputArray signature2);

//! @}

}//namespace cv

#endif


text:
export VERSIONER_PYTHON_PREFER_32_BIT=yes

ride.py


text:
package lodVader.spring.REST.models.dataset;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.UnknownHostException;

import org.apache.jena.riot.RiotException;

import lodVader.Manager;
import lodVader.exceptions.LODVaderFormatNotAcceptedException;
import lodVader.exceptions.LODVaderLODGeneralException;
import lodVader.exceptions.LODVaderNoDatasetFoundException;
import lodVader.parsers.descriptionfileparser.CLODFileParser;
import lodVader.parsers.descriptionfileparser.DataIDVoIDFileParser;
import lodVader.spring.REST.models.RESTMsg;

public class AddDatasetCLODModel extends RESTMsg implements Runnable {

//	private String datasetURI = "http://localhost/dbpedia/urls";
	private String datasetURI = "http://cirola2000.cloudapp.net/files/urls";
	private String format = "nt";

	private String apiCall;

	private Boolean error = false;

	public AddDatasetCLODModel() {
		// TODO Auto-generated constructor stub
	}

	public void addDatasetsCLOD() {

		CLODFileParser inputRDFParser = new CLODFileParser();
		try {
			setCoreMsgSuccess();

			// read and parse description file
			inputRDFParser.readModel(datasetURI, format);

			if (inputRDFParser.distributionsLinks.size() > 0) {
				setParserMsg(
						inputRDFParser.distributionsLinks.size() + " distributions found. We are processing them!");

				// stream distributions
				Manager m = new Manager(inputRDFParser.distributionsLinks);
			} else {
				setParserMsg("No datasets found.");

			}
		} catch (LODVaderNoDatasetFoundException e) {
			setParserMsg(e.getMessage());
			error = true;
			e.printStackTrace();

		} catch (RiotException e) {
			setParserMsg("Bad file format.");
			error = true;
			e.printStackTrace();
		}  catch (FileNotFoundException e) {
			setParserMsg("Impossible to reach the file: " + e.getMessage());
			error = true;
			e.printStackTrace();

		} catch (UnknownHostException e) {
			setParserMsg("Unknown Host: " + e.getMessage());
			error = true;
			e.printStackTrace();
		} catch (IOException e) {
			setParserMsg(e.getMessage());
			error = true;
			e.printStackTrace();
		}

	}

	public void run() {
		addDatasetsCLOD();
	}

	public String getDatasetURI() {
		return datasetURI;
	}

	public void setDatasetURI(String datasetURI) {
		this.datasetURI = datasetURI;
	}

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	public Boolean getError() {
		return error;
	}

	public void setError(Boolean error) {
		this.error = error;
	}

	public String getApiCall() {
		return apiCall;
	}

	public void setApiCall(String apiCall) {
		this.apiCall = apiCall;
	}

}


text:
module Octoparts
  module Model
    class PartResponse
      attr_accessor :part_id, :id, :cookies,
        :status_code, :mime_type, :charset,
        :cache_control, :contents, :warnings,
        :errors, :retrieved_from_cache
    end
  end
end


text:
layout: post
title: "[Action needed] [Patch available] Vulnerability in GoCD - Java deserialization and Apache commons-collections"
status: public
type: post
published: true
author: GoCD Team
---

This post contains information about a security patch available for GoCD 15.2 (and soon, earlier versions). If you're using GoCD 15.2 in production, and especially if it is available over the internet, it is highly recommended to apply this patch immediately.

[Any updates to this post are available starting [here](#updates)]

### What is the vulnerability?

As a part of AppSecCali 2015, a [talk](http://www.securitytube.net/video/13271) highlighted a
[vulnerability](http://foxglovesecurity.com/2015/11/06/what-do-weblogic-websphere-jboss-jenkins-opennms-and-your-application-have-in-common-this-vulnerability/)
using Java deserialization with Apache commons-collections, a very commonly used library in Java-based
applications. Though the talk focused on other applications, GoCD is affected too.

### Impact:

This is a potentially serious issue and applying the patch is recommended, since it is a remote code execution
vulnerability in Java deserialization (exploited using Apache commons-collections).

The impact is reduced a bit, because as far as we are able to determine, this attack on the server is possible only by
having the authentication certificate of an already-registered and enabled Go Agent, because of the way the GoCD Server
and GoCD Agent communicate using a secure connection.

So, even if you have a GoCD server exposed to the internet, you're not immediately vulnerable, as far as we have been
able to determine (and we have given it a lot of thought).

### Risks of applying this patch:

This patch removes the known vector for this attack, as recommended by the vulnerability report. But, given the urgency,
this patch hasn't been extensively tested. There is a small potential for the Go Server to fail. However, given that the
patch is just a replaced JAR file, you can replace the original JAR file, if that happens and contact us on the
[GoCD community mailing list](https://groups.google.com/d/topic/go-cd/DIj1RjQRuMo/discussion) or at support@thoughtworks.com (if you need a private way to reach some of the committers).

We have been using this patch on https://build.go.cd and it has been fine. We will update this post if anything new is
found.

### Risks of not applying this patch:

The GoCD server will be open to arbitrary remote code execution from anyone who has access to a *registered* Go Agent (or
the agent.jks file of such an agent). This is true of an agent which was once registered and then disabled as well.

### How do I apply this patch?

Steps to apply the patch:

1. Download the appropriate go.jar file mentioned below, for your version of the Go Server and verify its checksums.

2. Find out the location of your go.jar file and take a backup. On different ways of installation of Go, this can be in different places:
    - On Windows: It is usually in `C:\Program Files (x86)\Go Server\go.jar`
    - On Debian and RPM based installations: It is usually in `/usr/share/go-server/go.jar`
    - On zip installers: It is in the base directory where you start the Go Server from.

3. Now that you have a backup of go.jar, stop the Go Server and replace go.jar with the one you downloaded.

4. Restart the Go Server.

All of your agents will now fetch the new agent JAR as well, and restart themselves. Depending on the number of agents
you have, this might take a little while (same as an upgrade of the Go Server).

The different patches available are:

#### 15.2.0-2248:

* JAR file: `https://download.go.cd/local/patches/15.2.0-2015_11_09/go.jar`
* MD5 checksum: `0872e4eefceaaf842a69d8b55ec6a2d0`
* SHA256 sum: `eecee2b04c9bd46e74c5c999585683daf164fe41b39151dfcc3f0642561fd4c5`
* GPG signature: `https://download.go.cd/local/patches/15.2.0-2015_11_09/go.jar.asc`

#### 15.1.0-1863:

* JAR file: `https://download.go.cd/local/patches/15.1.0-2015_11_10/go.jar`
* MD5 checksum: `5981fee0fbd4e7be51a9d0351694bd13`
* SHA256 sum: `8ffe0461ab7d0f5ab5aaf1c4a10f8519c7acf7d808bff987614a8e867edee152`
* GPG signature: `https://download.go.cd/local/patches/15.1.0-2015_11_10/go.jar.asc`

#### 14.4.0-1356:

* JAR file: `https://download.go.cd/local/patches/14.4.0-2015_11_10/go.jar`
* MD5 checksum: `72409fb8ee9a305b03439747043752bd`
* SHA256 sum: `452c1cb7518d9654b000d18068729cd9a2072ce8bc262dededebc002f88141f8`
* GPG signature: `https://download.go.cd/local/patches/14.4.0-2015_11_10/go.jar.asc`

#### 14.3.0-1186:

* JAR file: `https://download.go.cd/local/patches/14.3.0-2015_11_10/go.jar`
* MD5 checksum: `64de38f7363a9345cad5e9c39aaa468e`
* SHA256 sum: `80d98e12d0b18107840951b2c067edf554a966131373ab0015a585021f46538f`
* GPG signature: `https://download.go.cd/local/patches/14.3.0-2015_11_10/go.jar.asc`

#### 14.2.0-377:

* JAR file: `https://download.go.cd/local/patches/14.2.0-2015_11_10/go.jar`
* MD5 checksum: `68a711227d7a2cd663f304cf04c87139`
* SHA256 sum: `6212eb9d0ab59d626e8ea3ec70ae0c34689f0de233502bd2f034fc91017c08f7`
* GPG signature: `https://download.go.cd/local/patches/14.2.0-2015_11_10/go.jar.asc`

The JAR files above are signed using the usual key used to sign the RPM and DEB installers. The signature file provided can be used to verify it.
The public key is available on [MIT PGP Public Key Server](http://pgp.mit.edu/pks/lookup?search=0x9149B0A6173454C7&op=index) and
[GoCD's bintray page](https://bintray.com/gocd). When verified, you'll see that it is signed by the GoCD team:

```
$ gpg --verify go.jar.asc go.jar
gpg: Signature made Mon Nov  9 12:13:21 2015 EST
gpg:                using RSA key 0x9149B0A6173454C7
gpg: Good signature from "Go CD (GPG key for signing bintray downloads) <go-cd@googlegroups.com>" [full]
Primary key fingerprint: 9A43 9A18 CBD0 7C3F F81B  CE75 9149 B0A6 1734 54C7
```

### I don't trust you. How do I generate this patched go.jar myself?

Glad you asked. Take a look at [this](/misc/generate-patched-jar-for-deserialization-vulnerability.html).

### Updates:

#### Update 1: 9th Nov, 2015 - 1830 EST

This patch fixes one of the known vectors, but there could be one other, TemplatesImpl, which *might* be vulnerable. From an early analysis, it doesn't seem to be, since it has some security and expects a JDK property to be set, before it is used. If we find more about it, this post will be updated. Even if it is vulnerable, there might not be much that can be done, because that is a class provided by the Java Runtime Environment itself. The long-term fix for issues such as this is to move away from Java serialization.

See these articles for more information: [InfoQ: Remotely Exploitable Java Zero Day Exploits through Deserialization](http://www.infoq.com/news/2015/11/commons-exploit) and
[The Java Deserialization Bug](http://fishbowl.pastiche.org/2015/11/09/java_serialization_bug/).

#### Update 2: 10th Nov, 2015 - 1900 EST

* Updated the "How do I apply this patch?" section with information about patches for older, supported versions.
* Removed the shell script for generating the patched version. It was too much information on this page. It is
  [linked](/misc/generate-patched-jar-for-deserialization-vulnerability.html).
* Go is not vulnerable to the TemplatesImpl payload.

**Note**: This post will be updated with more information, as we find it and with information about patches for older, supported
installers. If you need help, please email the [GoCD community mailing list](https://groups.google.com/d/topic/go-cd/DIj1RjQRuMo/discussion)
or for a private channel, support@thoughtworks.com.


text:
//  This file is part of YamlDotNet - A .NET library for YAML.
//  Copyright (c) Antoine Aubry and contributors

//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to
//  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
//  of the Software, and to permit persons to whom the Software is furnished to do
//  so, subject to the following conditions:

//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.

//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.

using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using System.ComponentModel.Composition;
using YamlDotNetEditor.CommandHandlers;

namespace YamlDotNetEditor
{
	[Export(typeof(IVsTextViewCreationListener))]
	[ContentType("yaml")]
	[TextViewRole(PredefinedTextViewRoles.Editable)]
	public sealed class CommandService : IVsTextViewCreationListener
	{
		[Import]
		internal IVsEditorAdaptersFactoryService EditorAdaptersFactoryService = null; // Set via MEF

		[Import]
		internal ITextUndoHistoryRegistry TextUndoHistoryRegistry = null; // Set via MEF

		public void VsTextViewCreated(IVsTextView textViewAdapter)
		{
			ITextView textView = EditorAdaptersFactoryService.GetWpfTextView(textViewAdapter);
			if (textView == null)
				return;

			var dispatcher = new CommandHandlerDispatcher(textViewAdapter, textView, TextUndoHistoryRegistry,
				new CommentSelectionCommandHandler(),
				new UncommentSelectionCommandHandler(),
				new FormatDocumentCommandHandler()
			);

			textView.Properties.AddProperty(typeof(CommandHandlerDispatcher), dispatcher);
		}
	}
}


text:
#ifndef HEADER_CURL_MD4_H
#define HEADER_CURL_MD4_H

#include BOSS_CURL_U_curl_setup_h //original-code:"curl_setup.h"

/* NSS and OS/400 crypto library do not provide the MD4 hash algorithm, so
 * that we have a local implementation of it */
#if defined(USE_NSS) || defined(USE_OS400CRYPTO)

void Curl_md4it(unsigned char *output, const unsigned char *input, size_t len);

#endif /* defined(USE_NSS) || defined(USE_OS400CRYPTO) */

#endif /* HEADER_CURL_MD4_H */


text:
This demo uses indico's Sentiment Analysis, Emotions, and Keywords API to analyze tweets from gamers discussing Fortnite and PUBG on Twitter.

Check out the tutorial for more information.

Receive 10k Free API calls per month to continue experimenting with indico. Sign up here.

Get started with Custom Collection on our docs!


text:
import cn from 'classnames'
import React from 'react'
import Button, { Props as ButtonProps } from './Button'

interface Props extends ButtonProps {
  className?: string
  children?: any
}
function InputAddon({ className, ...props }: Props) {
  return (
    <Button
      {...props}
      className={cn(className, 'rw-input-addon rw-picker-btn')}
    />
  )
}

export default InputAddon


text:
<?php

abstract class ClassMath
{
	/*** dos numeros del tipo protected ***/
	protected $num_one;

	protected $num_two;

	/**
	* @access protected
	* @param $num_one número a asignar
	*
	**/

	abstract protected function getNumberOne();

	/**
	* @access protected
	* @param $num_two número a asignar
	*
	**/

	abstract protected function getNumberTwo();

	/**
	* @access protected
	* @param $num_one número a asignar
	*
	**/

	abstract protected function setNumberOne($num_one);

	/**
	* @access protected
	* @param $num_two número a asignar
	*
	**/

	abstract protected function setNumberTwo($num_two);

	/**
	* Sumando dos numeros
	* @access protected
	*
	**/
	abstract protected function addTwoNumber();

	/**
	* Dividiendo dos numeros
	* @access protected
	*
	**/
	abstract protected function divideTwoNumber();

}


text:
var keystone = require('keystone'),
	Types = keystone.Field.Types;

// model
var Link = new keystone.List('Link', {
	track: true,
	autokey: {
		path: 'slug',
		from: 'title',
		unique: true
	},
	map: { name: 'title' },
	defaultColumns: 'title|55%, priority|15%, publish|15%, createdBy|15%',
	defaultSort: '-publish'
});
Link.add({
	title: {
		type: Types.Text,
		initial: true,
		required: true
	},
	url: {
		type: Types.Url,
		initial: true,
		required: true
	},
	author: {
		type: Types.Text,
		initial: true,
		required: true
	},
	blurb: {
		type: Types.Textarea,
		initial: true,
		required: true
	},
	category: {
		type: Types.Relationship,
		ref: 'LinkCategory',
		initial: true,
		required: true,
		index: true
	},
	publish: {
		type: Types.Date,
		initial: true,
		required: true,
		index: true
	},
	priority: {
		type: Types.Number,
		initial: true
	}
});

Link.register();


text:
WebRTC welcomes patches/pulls for features and bug fixes.

For contributors external to Google, follow the instructions given in the [Google Individual Contributor License Agreement](https://cla.developers.google.com/about/google-individual).

In all cases, contributors must sign a contributor license agreement before a contribution can be accepted. Please complete the agreement for an [individual](https://developers.google.com/open-source/cla/individual) or a [corporation](https://developers.google.com/open-source/cla/corporate) as appropriate.

If you plan to add a significant component or large chunk of code, we recommend you bring this up on the [webrtc-discuss group](https://groups.google.com/forum/#!forum/discuss-webrtc) for a design discussion before writing code.

If appropriate, write a unit test which demonstrates that your code functions as expected. Tests are the best way to ensure that future contributors do not break your code accidentally.

To request a change or addition, you must [submit a pull request](https://help.github.com/categories/collaborating/).

WebRTC developers monitor outstanding pull requests. They may request changes to the pull request before accepting. They will also verify that a CLA has been signed.

The [Developer's Guide](https://bit.ly/webrtcdevguide) for this repo has more detailed information about code style, structure and validation.


text:
require 'page-object'

module AdminModule::Pages

class LoginPage400
  include PageObject

  page_url(:get_dynamic_url)

  def get_dynamic_url
    AdminModule.configuration.base_url
  end

  text_field(:username, :id => "txtUserName" )
  text_field(:password_mask, :id => "ctl00_cntPlh_txtPasswordMask" )
  text_field(:password, :id => "txtPassword" )
  button(:login, :id => "btnLogin" )

  def login_as(username, password)
    if !self.username? && current_url == AdminModule.configuration.base_url + '/AdminMain.aspx'
      # We're still logged in.
      return
    end

    raise ArgumentError.new("Missing username for login.\nHave you set the <CLIENT>_envname_USER environment variable?") if username.nil?

    raise ArgumentError.new("Missing password for login.\nHave you set the <CLIENT>_envname_PASSWORD environment variable?") if password.nil?

    unless current_url.downcase.include? get_dynamic_url.downcase
      navigate_to get_dynamic_url
    end

    self.username = username

    enable_login_button

    self.password = password
    login
  end

  def logout
    navigate_to get_dynamic_url + '/user/logout.aspx'
  end

  def enable_login_button
    # For 'unsupported' browsers (anything other than IE < v9), the login button
    # is disabled and hidden.
    #
    # Use JS to enable the button and make it visible.
    #
    enable_button_script = <<-EOS
      login_button = document.getElementById('btnLogin');
      login_button.disabled = false;
      login_button.style.visibility = 'visible';

      document.getElementById('lblBrowserCheck').textContent = "Automation courtesy of AdminModule"
    EOS

    @browser.execute_script(enable_button_script)
  end

end

end # module Pages


text:
using ProductCatalog.Notifications.Service;

namespace ProductCatalog.Notifications.Model
{
    public class GetFeedOfRecentEventsCommand : IRepositoryCommand
    {
        public static readonly IRepositoryCommand Instance = new GetFeedOfRecentEventsCommand();

        private GetFeedOfRecentEventsCommand()
        {
        }

        public IRepresentation Execute(IRepository repository)
        {
            return repository.GetFeedOfRecentEvents();
        }
    }
}


text:
package org.apache.sshd.common.io.nio2;

import java.io.IOException;
import java.net.SocketAddress;
import java.net.StandardSocketOptions;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.future.CloseFuture;
import org.apache.sshd.common.io.IoAcceptor;
import org.apache.sshd.common.io.IoHandler;

/**
 */
public class Nio2Acceptor extends Nio2Service implements IoAcceptor {

    private final Map<SocketAddress, AsynchronousServerSocketChannel> channels;
    private final Map<SocketAddress, AsynchronousServerSocketChannel> unbound;
    private int backlog = 50;

    public Nio2Acceptor(FactoryManager manager, IoHandler handler, AsynchronousChannelGroup group) {
        super(manager, handler, group);
        channels = new ConcurrentHashMap<SocketAddress, AsynchronousServerSocketChannel>();
        unbound = new ConcurrentHashMap<SocketAddress, AsynchronousServerSocketChannel>();
    }

    public void bind(Collection<? extends SocketAddress> addresses) throws IOException {
        for (SocketAddress address : addresses) {
            logger.debug("Binding Nio2Acceptor to address {}", address);
            AsynchronousServerSocketChannel socket = AsynchronousServerSocketChannel.open(group);
            socket.setOption(StandardSocketOptions.SO_REUSEADDR, Boolean.TRUE);
            socket.bind(address, backlog);
            SocketAddress local = socket.getLocalAddress();
            channels.put(local, socket);
            socket.accept(local, new AcceptCompletionHandler(socket));
        }
    }

    public void bind(SocketAddress address) throws IOException {
        bind(Collections.singleton(address));
    }

    public void unbind() {
        logger.debug("Unbinding");
        unbind(getBoundAddresses());
    }

    public void unbind(Collection<? extends SocketAddress> addresses) {
        for (SocketAddress address : addresses) {
            AsynchronousServerSocketChannel channel = channels.remove(address);
            if (channel != null) {
                unbound.put(address, channel);
            }
        }
    }

    public void unbind(SocketAddress address) {
        unbind(Collections.singleton(address));
    }

    public Set<SocketAddress> getBoundAddresses() {
        return new HashSet<SocketAddress>(channels.keySet());
    }

    @Override
    public CloseFuture close(boolean immediately) {
        unbind();
        return super.close(immediately);
    }

    public void doDispose() {
        for (SocketAddress address : channels.keySet()) {
            try {
                channels.get(address).close();
            } catch (IOException e) {
                logger.debug("Exception caught while closing channel", e);
            }
        }
        super.doDispose();
    }

    class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, SocketAddress> {
        private final AsynchronousServerSocketChannel socket;
        AcceptCompletionHandler(AsynchronousServerSocketChannel socket) {
            this.socket = socket;
        }
        public void completed(AsynchronousSocketChannel result, SocketAddress address) {
            // Verify that the address has not been unbound
            if (!channels.containsKey(address)) {
                try {
                    result.close();
                } catch (IOException e) {
                    logger.debug("Ignoring error closing accepted connection on unbound socket", e);
                }
                acceptorStopped(address);
                return;
            }
            try {
                // Create a session
                Nio2Session session = new Nio2Session(Nio2Acceptor.this, handler, result);
                handler.sessionCreated(session);
                sessions.put(session.getId(), session);
                session.startReading();
                // Accept new connections
                socket.accept(address, this);
            } catch (Throwable exc) {
                failed(exc, address);
            }
        }
        public void failed(Throwable exc, SocketAddress address) {
            if (!channels.containsKey(address)) {
                acceptorStopped(address);
            } else if (!disposing.get()) {
                logger.warn("Caught exception while accepting incoming connection", exc);
            }
        }
        protected void acceptorStopped(SocketAddress address) {
            // TODO: check remaining sessions on that address
            // TODO: and eventually close the server socket
        }
    }
}


text:
package org.smartloli.kafka.eagle.plugin.mysql;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartloli.kafka.eagle.common.util.SystemConfigUtils;
import org.smartloli.kafka.eagle.plugin.util.JConstants;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Initializing database scripts.
 *
 * @author smartloli.
 * <p>
 * Created by Aug 7, 2017
 */
public class MySqlRecordSchema {

    public static final Logger LOG = LoggerFactory.getLogger(MySqlRecordSchema.class);

    /**
     * Load database schema script.
     */
    public static void schema() {
        String url = SystemConfigUtils.getProperty("kafka.eagle.url");
        String username = SystemConfigUtils.getProperty("kafka.eagle.username");
        String password = SystemConfigUtils.getProperty("kafka.eagle.password");
        String host = url.split("//")[1].split("/")[0].split(":")[0];
        String port = url.split("//")[1].split("/")[0].split(":")[1];
        String db = url.split("//")[1].split("/")[1].split("\\?")[0];

        if (database(username, password, host, port, db)) {
            tables(username, password, host, port, db);
        }
    }

    private static void tables(String username, String password, String host, String port, String db) {
        Connection connection = MySqlStoragePlugin.getInstance(host + ":" + port + "/" + db, username, password);
        ResultSet rs = null;
        Statement stmt = null;
        List<String> tbls = new ArrayList<>();
        try {
            rs = connection.createStatement().executeQuery(JConstants.SHOW_TABLES);
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                for (int i = 1; i <= columnCount; i++) {
                    tbls.add(rs.getString(i));
                }
            }

            for (String tbl : JConstants.TBLS) {
                if (tbls.contains(tbl)) {
                    LOG.info("The [" + tbl + "] table already exists. Do not need to create it.");
                } else {
                    String key = "CREATE_TABLE_" + tbl.toUpperCase();
                    stmt = connection.createStatement();
                    if (JConstants.KEYS.containsKey(key)) {
                        stmt.addBatch(JConstants.KEYS.get(key).toString());
                    }
                    if (JConstants.KEYS.containsKey(key + "_INSERT")) {
                        stmt.addBatch(JConstants.KEYS.get(key + "_INSERT").toString());
                    }
                    // add index
                    if (JConstants.KEYS.containsKey(key + "_INDEX")) {
                        stmt.addBatch(JConstants.KEYS.get(key + "_INDEX").toString());
                    }
                    if (JConstants.KEYS.containsKey(key + "_INDEX_TM")) {
                        stmt.addBatch(JConstants.KEYS.get(key + "_INDEX_TM").toString());
                    }
                    if (JConstants.KEYS.containsKey(key + "_INDEX_TM_CLUSTER")) {
                        stmt.addBatch(JConstants.KEYS.get(key + "_INDEX_TM_CLUSTER").toString());
                    }
                    int[] code = stmt.executeBatch();
                    if (code.length > 0) {
                        LOG.info("Create [" + tbl + "] has successed.");
                    } else {
                        LOG.error("Create [" + tbl + "] has failed.");
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }

                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        MySqlStoragePlugin.close(connection);
    }

    private static boolean database(String username, String password, String host, String port, String db) {
        Connection connection = MySqlStoragePlugin.getInstance(host + ":" + port, username, password);
        ResultSet rs = null;
        List<String> dbs = new ArrayList<>();
        try {
            rs = connection.createStatement().executeQuery(JConstants.SHOW_DATABASES);
            ResultSetMetaData rsmd = rs.getMetaData();
            int columnCount = rsmd.getColumnCount();
            while (rs.next()) {
                for (int i = 1; i <= columnCount; i++) {
                    dbs.add(rs.getString(i));
                }
            }
            if (dbs.contains(db)) {
                LOG.info("The [" + db + "] database already exists. Do not need to create it.");
            } else {
                boolean status = connection.createStatement().execute(String.format(JConstants.CREATE_DB_SQL, db));
                if (!status) {
                    LOG.info("SQL statement affect the 0 records. Create [" + db + "] has successed.");
                } else {
                    LOG.error("Create [" + db + "] has failed.");
                }
            }
            return true;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        MySqlStoragePlugin.close(connection);
        return false;
    }
}


text:
const { isNodeType } = require('solidity-ast/utils');
const { slug } = require('./helpers');

module.exports.anchor = function anchor ({ item, contract }) {
  let res = '';
  if (contract) {
    res += contract.name + '-';
  }
  res += item.name;
  if ('parameters' in item) {
    const signature = item.parameters.parameters.map(v => v.typeName.typeDescriptions.typeString).join(',');
    res += slug('(' + signature + ')');
  }
  if (isNodeType('VariableDeclaration', item)) {
    res += '-' + slug(item.typeName.typeDescriptions.typeString);
  }
  return res;
};

module.exports.inheritance = function ({ item, build }) {
  if (!isNodeType('ContractDefinition', item)) {
    throw new Error('used inherited-items on non-contract');
  }

  return item.linearizedBaseContracts
    .map(id => build.deref('ContractDefinition', id))
    .filter((c, i) => c.name !== 'Context' || i === 0);
};

module.exports['has-functions'] = function ({ item }) {
  return item.inheritance.some(c => c.functions.length > 0);
};

module.exports['has-events'] = function ({ item }) {
  return item.inheritance.some(c => c.events.length > 0);
};

module.exports['inherited-functions'] = function ({ item }) {
  const { inheritance } = item;
  const baseFunctions = new Set(
    inheritance.flatMap(c => c.functions.flatMap(f => f.baseFunctions ?? [])),
  );
  return inheritance.map((contract, i) => ({
    contract,
    functions: contract.functions.filter(f =>
      !baseFunctions.has(f.id) && (f.name !== 'constructor' || i === 0),
    ),
  }));
};


text:
<?php
require(dirname(__FILE__) . '/vitals.inc.php');

/**
 * handbook toc printer
 * prints an unordered html list representation of the multidimensional array.
 * $pages    the array of items to print.
 * $section  the directory name of the files.
 */
function hb_print_toc($pages, $section) {
	global $_pages, $req_lang;
	echo '
';
	foreach ($pages as $page_key => $page_value) {
		echo '
';
		if (is_array($page_value)) {
			echo ''.$_pages[$page_key].'';
			hb_print_toc($page_value, $section);
		} else {
			echo ''.$_pages[$page_value].'';
		}
		echo '
';
	}
	echo '
';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="<?php if ($missing_lang) { echo 'en'; } else { echo $req_lang; } ?>">

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	<title><?php get_text('handbook_toc'); ?></title>
	<base target="body" />

<?php
require(dirname(__FILE__).'/../'.$section.'/pages.inc.php');
if (($req_lang != 'en') && (file_exists(dirname(__FILE__).'/../'.$section.'/'.$req_lang.'/pages.inc.php'))) {
	require(dirname(__FILE__).'/../'.$section.'/'.$req_lang.'/pages.inc.php');
}
if ($section == 'admin'){
	$pages = array(
				'introduction.php',
				'installation.php' => array(
											'requirements_recommendations.php',
											'new_installation.php',
											'upgrading.php'
											),
				'configuration.php' => array('my_account.php'),
				'system_preferences.php' => array(
												'default_preferences.php',
												'languages.php',
												'auto_enroll.php',
												'themes.php' => array(
																		'importing_themes.php',
																		'managing_existing_themes.php',
																		'creating_themes.php'
																		),
												'error_logging.php',
												'feeds.php',
												'google_key.php',
												'cron_setup.php'
												),
				'enrollment.php' => array(
									'enrollment_privileges.php',
									),
				'users.php' => array(
										'instructor_requests.php',
										'master_student_list.php',
										'email_users.php',
										'administrators.php'
										),
				'courses.php' => array(
										'forums.php',
										'creating_courses.php',
										'default_student_tools.php',
										'default_side_menu.php',
										'backups.php',
										'categories.php'
										),
				'modules.php',
				'basiclti_external_tools.php',
				'patcher.php' => array(
										'create_patches.php'
										),
				'troubleshooting.php',
			);

	hb_print_toc($pages, 'admin');

} else if ($section == 'instructor'){
	$pages = array(
			'introduction.php' => array('creating_courses.php','student_tools.php', 'fha_student_tools.php','side_menu.php'),
			'announcements.php',
			'assignments.php',
			'backups.php' => array(
									'creating_restoring.php',
									'downloading_uploading.php',
									'editing_deleting.php'
									),
			'chat.php',
			'content.php' => array(
									'creating_editing_content.php' => array(
				'content_edit.php',
				'content_properties.php',								'glossary_terms.php',
				'content_preview.php',
				'arrange_content.php',
				'content_alternatives.php',								'accessibility.php',
					'content_tests.php'
													),
									'content_packages.php',
									'content_usage.php',
									'tile_repository.php',
									'scorm_packages.php'
									),
			'course_email.php',
			'enrollment.php' => array(
									'enrollment_privileges.php',
									'enrollment_alumni.php',
									'enrollment_course_list.php'
										),
			'file_manager.php' => array(
									'managing_files_folders.php',
									'extracting_zip_archives.php'
									),
			'forums.php' => array(				'managing_threads.php' => 									array('managing_posts.php'),
									'forum_export.php'
									),
			'faq.php',
			'glossary.php',
			'groups.php',
			'links.php',
			'polls.php',
			'properties.php' => array('authenticated_access.php', 'delete_course.php'),
			'reading_list.php',
			'statistics.php',
			'tests_surveys.php' => array(
											'creating_tests_surveys.php',
											'question_database.php' => array('creating_questions.php'),
											'question_categories.php',
											'edit_delete_tests.php',
											'preview.php',
											'add_questions.php',
											'student_submissions.php',
											'test_statistics.php'
											),
			'feeds.php',
			'gradebook.php' => array(
							'gradebook_add.php',
							'gradebook_update.php',
							'gradebook_external_marks.php',
							'gradebook_edit_marks.php',
							'gradebook_scales.php'
							),
			'web_search.php',
			);
	hb_print_toc($pages, 'instructor');
} else {

	$pages = array(
				'introduction.php',
				'login.php',
				'register.php',
				'browse_courses.php',
				'password_reminder.php',
				'my_start_page.php' => array(
												'my_courses.php' => array('create_course.php'),
												'profile.php',
												'preferences.php',
												'inbox.php'
												),
				'inside_course.php' => array(
												'export_content.php',
												'packages.php',
												'tile.php',
												'file_storage.php',
												'fs_new_file.php'
												),
				'my_network.php' => array(
											'my_contacts.php',
											'my_groups.php',
											'my_profile.php',
											'my_gadgets.php',
											'my_settings.php'
											),
				'pa_index.php' => array(
											'pa_albums.php',
											'pa_photo.php',
											'pa_comments.php'
											)
			);
	hb_print_toc($pages, 'general');
} ?>


text:
//
//  CZLCategoryHeader.h
//  CZLPractice
//
//  Created by yuzeux on 2017/8/7.
//  Copyright © 2017年 DerenChen. All rights reserved.
//

#ifndef CZLCategoryHeader_h
#define CZLCategoryHeader_h

#import "UIColor+CZLCategory.h"
#import "UIView+CZLCategory.h"

#endif /* CZLCategoryHeader_h */