text:
package edu.gemini.spModel.gemini.flamingos2.blueprint;

import edu.gemini.spModel.gemini.flamingos2.Flamingos2.Disperser;
import edu.gemini.spModel.gemini.flamingos2.Flamingos2.Filter;
import edu.gemini.spModel.pio.ParamSet;
import edu.gemini.spModel.pio.Pio;
import edu.gemini.spModel.pio.PioFactory;

import java.util.List;

import static edu.gemini.spModel.template.SpBlueprintUtil.mkString;

public abstract class SpFlamingos2BlueprintSpectroscopyBase extends SpFlamingos2BlueprintBase {

    public static final String DISPERSER_PARAM_NAME = "disperser";

    public final Disperser disperser;

    protected SpFlamingos2BlueprintSpectroscopyBase(List<Filter> filters, Disperser disperser) {
        super(filters);
        this.disperser = disperser;
    }

    protected SpFlamingos2BlueprintSpectroscopyBase(ParamSet paramSet) {
        super(paramSet);
        disperser = Pio.getEnumValue(paramSet, DISPERSER_PARAM_NAME, Disperser.DEFAULT);
    }

    @Override
    public ParamSet toParamSet(PioFactory factory) {
        ParamSet paramSet = super.toParamSet(factory);
        Pio.addEnumParam(factory, paramSet, DISPERSER_PARAM_NAME, disperser);
        return paramSet;
    }

    @Override
    public boolean equals(Object o) {
        if (!super.equals(o)) return false;

        SpFlamingos2BlueprintSpectroscopyBase that = (SpFlamingos2BlueprintSpectroscopyBase) o;
        return disperser == that.disperser;
    }

    @Override
    public int hashCode() {
        int res = super.hashCode();
        res = res*31 + disperser.hashCode();
        return res;
    }
}


text:
package org.apache.calcite.sql.validate;

import org.apache.calcite.linq4j.Linq4j;
import org.apache.calcite.linq4j.function.Function1;
import org.apache.calcite.linq4j.function.Predicate1;
import org.apache.calcite.sql.SqlNode;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;

import java.util.List;
import java.util.Set;

/**
 * Implementation of {@link SqlValidatorScope} that can see all schemas in the
 * current catalog.
 *
 *
Occurs near the root of the scope stack; its parent is typically
 * {@link EmptyScope}.
 *
 *
Helps resolve {@code schema.table.column} column references, such as
 *
 *

select sales.emp.empno from sales.emp

 */
class CatalogScope extends DelegatingScope {
  /** Fully-qualified name of the catalog. Typically empty or ["CATALOG"]. */
  final ImmutableList<String> names;
  private final Set<List<String>> schemaNames;

  //~ Constructors -----------------------------------------------------------

  CatalogScope(SqlValidatorScope parent, List<String> names) {
    super(parent);
    this.names = ImmutableList.copyOf(names);
    this.schemaNames =
        Linq4j.asEnumerable(
            validator.getCatalogReader()
                .getAllSchemaObjectNames(ImmutableList.<String>of()))
            .where(
                new Predicate1<SqlMoniker>() {
                  public boolean apply(SqlMoniker input) {
                    return input.getType() == SqlMonikerType.SCHEMA;
                  }
                })
            .select(
                new Function1<SqlMoniker, List<String>>() {
                  public List<String> apply(SqlMoniker input) {
                    return input.getFullyQualifiedNames();
                  }
                })
            .into(Sets.<List<String>>newHashSet());
  }

  //~ Methods ----------------------------------------------------------------

  public SqlNode getNode() {
    throw new UnsupportedOperationException();
  }

  public SqlValidatorNamespace resolve(List<String> names,
      SqlValidatorScope[] ancestorOut, int[] offsetOut) {
    final ImmutableList<String> nameList =
        ImmutableList.<String>builder().addAll(this.names).addAll(names)
            .build();
    if (schemaNames.contains(nameList)) {
      return new SchemaNamespace(validator, nameList);
    }
    return null;
  }
}

// End CatalogScope.java

redpajama_set_name: RedPajamaGithub


text:
'''
Copyright © 2017 DELL Inc. or its subsidiaries.  All Rights Reserved.
Created on June 5, 2017
@author: Michael Regert
'''

import unittest
import sys
import logging
import config
from resttestms import http, json, log, test, parse

LOG = logging.getLogger(__name__)

# Leave as None to use default host
HOST_OVERRIDE = None

# Leave as None to use default json directory
DATA_OVERRIDE = None

# Leave as None to use default depth
DEPTH_OVERRIDE = None

def setUpModule():
    """Initialize data for all test cases using overrides"""
    LOG.info("Begin Firmware Update Tests")
    FirmwareUpdateTest.initialize_data(HOST_OVERRIDE, DATA_OVERRIDE, DEPTH_OVERRIDE)

class FirmwareUpdateTest(unittest.TestCase):
    """Collection of data to test the firmware update microservice"""

    PORT = '46010'
    JSON_NAME = 'data_firmwareupdate.json'

    @classmethod
    def initialize_data(cls, host_override, directory_override, depth_override):
        """Initialize base url, json file path, and depth"""
        cls.HOST = test.select_host(config.HOST, host_override)
        cls.DATA = test.select_directory(config.DATA, directory_override)
        cls.DEPTH = test.select_depth(config.DEPTH, depth_override)
        cls.BASE_URL = test.create_base_url(cls.HOST, cls.PORT)
        cls.JSON_FILE = test.create_json_reference(cls.DATA, cls.JSON_NAME)

###################################################################################################
# Comparer
###################################################################################################

class Comparer(FirmwareUpdateTest):
    """Tests for Comparer Endpoint"""

    ENDPOINT = 'comparer'

    def test_json(self):
        """COMPARER JSON TESTS"""
        test.auto_run_json_tests('POST', self)

###################################################################################################
# Comparer Catalog
###################################################################################################

class ComparerCatalog(FirmwareUpdateTest):
    """Tests for Comparer Catalog Endpoint"""

    ENDPOINT = 'comparer_catalog'

    def test_json(self):
        """COMPARER CATALOG JSON TESTS"""
        test.auto_run_json_tests('POST', self)

###################################################################################################
# Comparer Custom
###################################################################################################

class ComparerCustom(FirmwareUpdateTest):
    """Tests for Comparer Custom Endpoint"""

    ENDPOINT = 'comparer_custom'

    def test_json(self):
        """COMPARER CUSTOM JSON TESTS"""
        test.auto_run_json_tests('POST', self)

###################################################################################################
# Downloader
###################################################################################################

class Downloader(FirmwareUpdateTest):
    """Tests for Downloader Endpoint"""

    ENDPOINT = 'downloader'

    # def test_induce_error(self):
    #     """DOWNLOADER INDUCE ERROR TESTS"""
    #     test.induce_error('GET', self)

    def test_json(self):
        """DOWNLOADER JSON TESTS"""
        test.auto_run_json_tests('GET', self)

###################################################################################################
# UCI
###################################################################################################

class UCI(FirmwareUpdateTest):
    """Tests for UCI Endpoint"""

    ENDPOINT = 'uci'

    def test_json(self):
        """UCI JSON TESTS"""
        test.auto_run_json_tests('POST', self)

###################################################################################################
# UCI SI
###################################################################################################

class UCISI(FirmwareUpdateTest):
    """Tests for UCI SI Endpoint"""

    ENDPOINT = 'uci_si'

    def test_json(self):
        """UCI SI JSON TESTS"""
        test.auto_run_json_tests('POST', self)

###################################################################################################
# Updater
###################################################################################################

class Updater(FirmwareUpdateTest):
    """Tests for Updater Endpoint"""

    ENDPOINT = 'updater'

    def test_json(self):
        """UPDATER JSON TESTS"""
        test.auto_run_json_tests('POST', self)

###################################################################################################
# Updater DUP
###################################################################################################

class UpdaterDUP(FirmwareUpdateTest):
    """Tests for Updater DUP Endpoint"""

    ENDPOINT = 'updater_dup'

    def test_json(self):
        """UPDATER DUP JSON TESTS"""
        test.auto_run_json_tests('POST', self)

###################################################################################################
# Updater Status
###################################################################################################

class UpdaterStatus(FirmwareUpdateTest):
    """Tests for Updater Status Endpoint"""

    ENDPOINT = 'updater_status'

    def test_json(self):
        """UPDATER STATUS JSON TESTS"""
        test.auto_run_json_tests('POST', self)

###################################################################################################
# Updater TestCallback
###################################################################################################

class UpdaterTestCallback(FirmwareUpdateTest):
    """Tests for Updater TestCallback Endpoint"""

    ENDPOINT = 'updater_testCallback'

    def test_json(self):
        """UPDATER TESTCALLBACK JSON TESTS"""
        test.auto_run_json_tests('POST', self)

###################################################################################################
# Version
###################################################################################################

class Version(FirmwareUpdateTest):
    """Tests for Version Endpoint"""

    ENDPOINT = 'version'

    def test_json(self):
        """VERSION JSON TESTS"""
        test.auto_run_json_tests('GET', self)

###################################################################################################
# Test Sequences
###################################################################################################

class TestSequences(FirmwareUpdateTest):
    """Test Sequences for Firmware Update"""

    def test_placeholder(self):
        """PLACEHOLDER"""
        # test.run_json_test('POST', self, Export, "test_fitFile_export")
        pass

###################################################################################################
# RUN MODULE
###################################################################################################

if __name__ == "__main__":
    HOST, DATA, DEPTH = parse.single_microservice_args(sys.argv)
    HOST_OVERRIDE = HOST if HOST else HOST_OVERRIDE
    DATA_OVERRIDE = DATA if DATA else DATA_OVERRIDE
    DEPTH_OVERRIDE = DEPTH if DEPTH else DEPTH_OVERRIDE
    log.configure_logger_from_yaml('logs/logger_config.yml')
    unittest.main()


text:
#ifndef JUCE_OSCMESSAGE_H_INCLUDED
#define JUCE_OSCMESSAGE_H_INCLUDED

//==============================================================================
/**
    An OSC Message.

    An OSCMessage consists of an OSCAddressPattern and zero or more OSCArguments.

    OSC messages are the elementary objects that are used to exchange any data
    via OSC. An OSCSender can send OSCMessage objects to an OSCReceiver.
*/
class JUCE_API  OSCMessage
{
public:

    //==============================================================================
    /** Constructs an OSCMessage object with the given address pattern and no
        arguments.

        @param ap    the address pattern of the message. This must be a valid OSC
                     address (starting with a forward slash) and may contain
                     OSC wildcard expressions. You can pass in a string literal
                     or a juce String (they will be converted to an OSCAddressPattern
                     automatically).
    */
    OSCMessage (const OSCAddressPattern& ap) noexcept;

   #if JUCE_COMPILER_SUPPORTS_VARIADIC_TEMPLATES && JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
    /** Constructs an OSCMessage object with the given address pattern and list
        of arguments.

        @param ap    the address pattern of the message. This must be a valid OSC
                     address (starting with a forward slash) and may contain
                     OSC wildcard expressions. You can pass in a string literal
                     or a juce String (they will be converted to an OSCAddressPattern
                     automatically).

        @param arg1  the first argument of the message.
        @param args  an optional list of further arguments to add to the message.
    */
    template <typename Arg1, typename... Args>
    OSCMessage (const OSCAddressPattern& ap, Arg1&& arg1, Args&&... args);
   #endif

    /** Sets the address pattern of the OSCMessage.

        @param ap    the address pattern of the message. This must be a valid OSC
                     address (starting with a forward slash) and may contain
                     OSC wildcard expressions. You can pass in a string literal
                     or a juce String (they will be converted to an OSCAddressPattern
                     automatically).
    */
    void setAddressPattern (const OSCAddressPattern& ap) noexcept;

    /** Returns the address pattern of the OSCMessage. */
    OSCAddressPattern getAddressPattern() const noexcept;

    /** Returns the number of OSCArgument objects that belong to this OSCMessage. */
    int size() const noexcept;

    /** Returns true if the OSCMessage contains no OSCArgument objects; false otherwise. */
    bool empty() const noexcept;

    /** Returns a reference to the OSCArgument at index i in the OSCMessage object.
        This method does not check the range and results in undefined behavour
        in case i < 0 or i >= size().
    */
    OSCArgument& operator[] (const int i) const noexcept;

    /** Returns a pointer to the first OSCArgument in the OSCMessage object.
        This method is provided for compatibility with standard C++ iteration mechanisms.
    */
    OSCArgument* begin() const noexcept;

    /** Returns a pointer to the last OSCArgument in the OSCMessage object.
        This method is provided for compatibility with standard C++ iteration mechanisms.
    */
    OSCArgument* end() const noexcept;

    /** Removes all arguments from the OSCMessage. */
    void clear();

    //==============================================================================
    /** Creates a new OSCArgument of type int32 with a given value
        and adds it to the OSCMessage object.
    */
    void addInt32 (int32 value);

    /** Creates a new OSCArgument of type float32 with a given value
        and adds it to the OSCMessage object.
    */
    void addFloat32 (float value);

    /** Creates a new OSCArgument of type string with a given value
        and adds it to the OSCMessage object.
    */
    void addString (const String& value);

    /** Creates a new OSCArgument of type blob with binary data content copied from
        the given MemoryBlock.

        Note: if the argument passed is an lvalue, this may copy the binary data.
    */
    void addBlob (const MemoryBlock& blob);

    /** Adds the OSCArgument argument to the OSCMessage object.

        Note: This method will result in a copy of the OSCArgument object if it is passed
        as an lvalue. If the OSCArgument is of type blob, this will also copy the underlying
        binary data. In general, you should use addInt32, addFloat32, etc. instead.
    */
    void addArgument (OSCArgument argument);

private:

    //==============================================================================
   #if JUCE_COMPILER_SUPPORTS_VARIADIC_TEMPLATES && JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
    template <typename Arg1, typename... Args>
    void addArguments (Arg1&& arg1, Args&&... args)
    {
        addArgument (arg1);
        addArguments (std::forward<Args> (args)...);
    }

    void addArguments() {}
   #endif

    //==============================================================================
    OSCAddressPattern addressPattern;
    Array<OSCArgument> arguments;
};

//==================================================================================
#if JUCE_COMPILER_SUPPORTS_VARIADIC_TEMPLATES && JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
 template <typename Arg1, typename... Args>
 OSCMessage::OSCMessage (const OSCAddressPattern& ap, Arg1&& arg1, Args&&... args)
     : addressPattern (ap)
 {
     addArguments (std::forward<Arg1> (arg1), std::forward<Args> (args)...);
 }
#endif

#endif // JUCE_OSCMESSAGE_H_INCLUDED


text:
#ifndef CDBFILEREPRESYNCMANAGER_H
#define CDBFILEREPRESYNCMANAGER_H

#include "cdb/cdbfilerep.h"
#include "access/persistentfilesysobjname.h"
#include "cdb/cdbresynchronizechangetracking.h"

/*
 * Resync Hash Table located in shared memory keeps
 * track of files that are currently in resync.
 * One entry per file.
 * It has fixed MAX number of files to be resynced
 *
 */
typedef struct FileRepResyncHashEntry_s {

	char							fileName[MAXPGPATH+1];
	/*
	 * It identifies mirror relation path.
	 * It is key. It has to be first field in the structure.
	 */

	RelFileNode						relFileNode;

	int32							segmentFileNum;

	PersistentFileSysRelStorageMgr 	relStorageMgr;
	/* relationType (Buffer Pool or AppendOnly) */

	MirroredRelDataSynchronizationState mirrorDataSynchronizationState;
	/* relationOperation (Full, IncrPage or IncrScan) */

	int64							mirrorBufpoolResyncChangedPageCount;

	XLogRecPtr						mirrorBufpoolResyncCkptLoc;
	/* beginIncrResyncLSN */

	BlockNumber 					mirrorBufpoolResyncCkptBlockNum;

	int64							mirrorAppendOnlyLossEof;

	int64							mirrorAppendOnlyNewEof;

	ItemPointerData					persistentTid;

	int64							persistentSerialNum;

	FileRepResyncState_e			fileRepResyncState;

} FileRepResyncHashEntry_s;

extern Size FileRepResync_ShmemSize(void);

extern void FileRepResync_ShmemInit(void);

extern void FileRepResync_Cleanup(void);

extern void FileRepPrimary_StartResyncManager(void);

extern FileRepResyncHashEntry_s* FileRepPrimary_GetResyncEntry(ChangeTrackingRequest **request);

extern int FileRepResync_UpdateEntry(
									 FileRepResyncHashEntry_s*	entry);

extern XLogRecPtr FileRepResync_GetEndIncrResyncLSN(void);

extern XLogRecPtr FileRepResync_GetEndFullResyncLSN(void);

extern void FileRepResyncManager_SetEndResyncLSN(
												 XLogRecPtr endResyncLSN);

extern int FileRepResync_IncAppendOnlyCommitCount(void);

extern int FileRepResync_DecAppendOnlyCommitCount(int	count);

extern int FileRepResync_GetAppendOnlyCommitCount(void);

extern bool FileRepResync_IsReMirrorAllowed(void);

extern void FileRepResync_SetReMirrorAllowed(void);

extern void FileRepResync_ResetReMirrorAllowed(void);

extern int64 FileRepResync_GetBlocksSynchronized(void);

extern int64 FileRepResync_GetTotalBlocksToSynchronize(void);

extern void FileRepResync_SetTotalBlocksToSynchronize(int64 totalBlocksToSynchronize);

extern void FileRepResync_AddToTotalBlocksToSynchronize(int64 moreBlocksToSynchronize);

extern struct timeval FileRepResync_GetEstimateResyncCompletionTime(void);

extern void FileRepResyncManager_ResyncFlatFiles(void);

extern void FileRepResync_DecFsobjCount(void);

extern int FileRepResync_GetCurFsobjCount(void);

extern int FileRepResync_GetTotalFsobjCount(void);

#endif  /* CDBFILEREPRESYNCMANAGER_H */


text: <aside id=sidebar> <sidebarwidgets></sidebarwidgets> <menubar></menubar> </aside>


text:
package com.swfarm.biz.chain.web;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.ebay.apacshipping.api.EubShippingServiceClient;
import com.swfarm.biz.chain.srv.ChainManagementService;
import com.swfarm.biz.chain.srv.EubShippingService;
import com.swfarm.biz.chain.srv.OfflineEubShippingOrderGenerator;
import com.swfarm.biz.oa.bo.Role;
import com.swfarm.biz.oa.bo.User;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucher;
import com.swfarm.biz.warehouse.bo.AllocationProductVoucherList;
import com.swfarm.biz.warehouse.dto.AllocationProductVoucherDTO;
import com.swfarm.biz.warehouse.dto.SearchAllocationProductVouchersCriteria;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.framework.AppContext;
import com.swfarm.pub.framework.Env;
import com.swfarm.pub.utils.SpringUtils;

public class GenerateEubShippingOrderController extends AbstractController {

	private WarehouseService warehouseService;

	private EubShippingService eubShippingService;

	private ChainManagementService chainManagementService;

	public void setWarehouseService(WarehouseService warehouseService) {
		this.warehouseService = warehouseService;
	}

	public void setEubShippingService(EubShippingService eubShippingService) {
		this.eubShippingService = eubShippingService;
	}

	public void setChainManagementService(ChainManagementService chainManagementService) {
		this.chainManagementService = chainManagementService;
	}

	protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse res) throws Exception {
		String apvNo = req.getParameter("apvNo");
		String withAllocateTable = req.getParameter("withAllocateTable");
		logger.warn("apvNo [" + apvNo + "]");
		if (StringUtils.isNotEmpty(apvNo)) {
			String[] apvNos = StringUtils.split(apvNo, ",");
			if (apvNos.length > 1) {
				List<String> apvList = new ArrayList<String>();
				CollectionUtils.addAll(apvList, apvNos);
				SearchAllocationProductVouchersCriteria criteria = new SearchAllocationProductVouchersCriteria();
				criteria.setAllocationProductVoucherNos(apvList);
				List<AllocationProductVoucher> apvs = this.warehouseService.searchAllocationProductVouchers(criteria);
				if (CollectionUtils.isNotEmpty(apvs)) {
					Collections.sort(apvs, new Comparator<AllocationProductVoucher>() {
						public int compare(AllocationProductVoucher apv1, AllocationProductVoucher apv2) {
							return apv1.getAllocationProductVoucherNo().compareTo(apv2.getAllocationProductVoucherNo());
						}
					});
					List<AllocationProductVoucherDTO> apvDTOs = ChainFrontHelper.getApvDTOsFromApvs(apvs);
					logger.warn("apvs size >> " + apvs.size());
					String apvlNo = apvs.iterator().next().getAllocationProductVoucherList()
							.getAllocationProductVoucherListNo();
					String sfmCode = apvs.iterator().next().getShippingForwarderMethod();
					String pdfName = apvs.get(apvs.size() - 1).getAllocationProductVoucherNo() + " " + apvs.size()
							+ "_etc";
					String datePath = apvlNo.replaceFirst(Env.APVL_PREFIX, "").substring(0, 6);
					if ("true".equalsIgnoreCase(withAllocateTable)) {
						AppContext.getContextData().setPayload(true);
					} else {
						AppContext.getContextData().setPayload(false);
					}
					byte[] eubShippingLabel = null;
					String apvFilePath = null;
					String shippingOrderUrl = null;
					if ("线下EUB".equals(sfmCode)) {
						apvFilePath = Env.APP_REAL_PATH + "/apvs/" + datePath + "/offline_eub/" + apvlNo + "/" + pdfName
								+ ".pdf";
						shippingOrderUrl = "/apvs/" + datePath + "/offline_eub/" + apvlNo + "/" + pdfName + ".pdf";
						File apvFile = new File(apvFilePath);
						logger.warn("apvFilePath[" + apvFilePath + "]");
						if (!"true".equals(withAllocateTable)) {
							if (apvFile.exists() == true) {
								eubShippingLabel = IOUtils.toByteArray(new FileInputStream(apvFile));
								logger.warn("apvFile exist [" + eubShippingLabel + "]");
								if (eubShippingLabel == null || eubShippingLabel.length < 10 * 1024) {
									deleteFile(apvFilePath);
									eubShippingLabel = null;
									logger.warn("remove corrupted eub file");
								}
							}
						}
						if (eubShippingLabel == null) {
							OfflineEubShippingOrderGenerator generator = new OfflineEubShippingOrderGenerator();
							generator.setWarehouseService(warehouseService);
							generator.setEubShippingService(eubShippingService);
							logger.warn("generate eub apv file");
							ByteArrayOutputStream bos = generator.generateShippingOrderInfo(apvDTOs);
							logger.warn("generate eub apv file successfully");
							if (bos != null) {
								eubShippingLabel = bos.toByteArray();
								if (eubShippingLabel == null || eubShippingLabel.length < 10 * 1024) {
									for (AllocationProductVoucher apv : apvs) {
										this.chainManagementService
												.cancelOfflineEubAllocationProductVoucher(apv.getId());
										deleteFile(apvFilePath);
										this.eubShippingService.sendAllocationProductVoucherOrder(apv.getId());
									}
									bos = generator.generateShippingOrderInfo(apvDTOs);
									if (bos != null) {
										eubShippingLabel = bos.toByteArray();
									}
								}
								if (eubShippingLabel != null && eubShippingLabel.length >= 10 * 1024) {
									FileUtils.writeByteArrayToFile(apvFile, eubShippingLabel);
									logger.warn("retrieve eub file");
									for (AllocationProductVoucher apv : apvs) {
										populatePackingUserInfo(apv);
									}
								}
							}
						}
					} else {
						apvFilePath = Env.APP_REAL_PATH + "/apvs/" + datePath + "/eub/" + apvlNo + "/" + pdfName
								+ ".pdf";
						shippingOrderUrl = "/apvs/" + datePath + "/eub/" + apvlNo + "/" + pdfName + ".pdf";
						File apvFile = new File(apvFilePath);
						logger.warn("apvFilePath[" + apvFilePath + "]");
						if (!"true".equals(withAllocateTable)) {
							if (apvFile.exists() == true) {
								eubShippingLabel = IOUtils.toByteArray(new FileInputStream(apvFile));
								logger.warn("apvFile exist [" + eubShippingLabel + "]");
								if (eubShippingLabel == null || eubShippingLabel.length < 10 * 1024) {
									deleteFile(apvFilePath);
									eubShippingLabel = null;
									logger.warn("remove corrupted eub file");
								}
							}
						}
						if (eubShippingLabel == null) {
							EubShippingServiceClient eubShippingServiceClient = (EubShippingServiceClient) SpringUtils
									.getBean("eubShippingServiceClient");
							ByteArrayOutputStream bos = eubShippingServiceClient.getEubShippingLabels(apvs);
							eubShippingLabel = bos.toByteArray();
							logger.warn("generate eub apv file successfully");
							if (eubShippingLabel != null && eubShippingLabel.length >= 10 * 1024) {
								FileUtils.writeByteArrayToFile(apvFile, eubShippingLabel);
								logger.warn("retrieve eub file");
								for (AllocationProductVoucher apv : apvs) {
									populatePackingUserInfo(apv);
								}
							}
						}
					}
					if (eubShippingLabel != null && eubShippingLabel.length >= 10 * 1024) {
						return new ModelAndView("chain/preload_shippingorderbyarticlenumber", "shippingOrderUrl",
								shippingOrderUrl);
					}
				}
			} else if (apvNos.length == 1) {
				AllocationProductVoucher apv = this.warehouseService
						.findAllocationProductVoucherByAllocationProductVoucherNo(apvNo);
				if (apv != null) {
					AllocationProductVoucherDTO apvDTO = ChainFrontHelper.getApvDTOFromApv(apv);
					String sfmCode = apv.getShippingForwarderMethod();
					String apvlNo = apv.getAllocationProductVoucherList().getAllocationProductVoucherListNo();
					String datePath = apvlNo.replaceFirst(Env.APVL_PREFIX, "").substring(0, 6);
					if ("true".equalsIgnoreCase(withAllocateTable)) {
						AppContext.getContextData().setPayload(true);
					} else {
						AppContext.getContextData().setPayload(false);
					}
					byte[] eubShippingLabel = null;
					String apvFilePath = null;
					String shippingOrderUrl = null;
					if ("线下EUB".equals(sfmCode)) {
						apvFilePath = Env.APP_REAL_PATH + "/apvs/" + datePath + "/offline_eub/" + apvlNo + "/" + apvNo
								+ ".pdf";
						shippingOrderUrl = "/apvs/" + datePath + "/offline_eub/" + apvlNo + "/" + apvNo + ".pdf";
						File apvFile = new File(apvFilePath);
						logger.warn("apvFilePath[" + apvFilePath + "]");
						if (apvFile.exists() == true) {
							eubShippingLabel = IOUtils.toByteArray(new FileInputStream(apvFile));
							logger.warn("apvFile exist [" + eubShippingLabel + "]");
							if (eubShippingLabel == null || eubShippingLabel.length < 10 * 1024) {
								deleteFile(apvFilePath);
								eubShippingLabel = null;
								logger.warn("remove corrupted eub file");
							}
						}
						if (eubShippingLabel == null) {
							OfflineEubShippingOrderGenerator generator = new OfflineEubShippingOrderGenerator();
							generator.setWarehouseService(warehouseService);
							generator.setEubShippingService(eubShippingService);
							logger.warn("generate eub apv file");
							ByteArrayOutputStream bos = generator.generateShippingOrder(apvDTO, true);
							logger.warn("generate eub apv file successfully");
							if (bos != null) {
								eubShippingLabel = bos.toByteArray();
								if (eubShippingLabel == null || eubShippingLabel.length < 10 * 1024) {
									this.chainManagementService.cancelOfflineEubAllocationProductVoucher(apv.getId());
									deleteFile(apvFilePath);
									this.eubShippingService.sendAllocationProductVoucherOrder(apv.getId());
								}
								bos = generator.generateShippingOrder(apvDTO, true);
								if (bos != null) {
									eubShippingLabel = bos.toByteArray();
								}
								populatePackingUserInfo(apv);
							}
						}
					} else {
						apvFilePath = Env.APP_REAL_PATH + "/apvs/" + datePath + "/eub/" + apvlNo + "/" + apvNo + ".pdf";
						shippingOrderUrl = "/apvs/" + datePath + "/eub/" + apvlNo + "/" + apvNo + ".pdf";
						File apvFile = new File(apvFilePath);
						logger.warn("apvFilePath[" + apvFilePath + "]");
						if (apvFile.exists() == true) {
							eubShippingLabel = IOUtils.toByteArray(new FileInputStream(apvFile));
							logger.warn("apvFile exist [" + eubShippingLabel + "]");
							if (eubShippingLabel == null || eubShippingLabel.length < 10 * 1024) {
								deleteFile(apvFilePath);
								eubShippingLabel = null;
								logger.warn("remove corrupted eub file");
							}
						}
						if (eubShippingLabel == null) {
							EubShippingServiceClient eubShippingServiceClient = (EubShippingServiceClient) SpringUtils
									.getBean("eubShippingServiceClient");
							eubShippingLabel = eubShippingServiceClient.getEubShippingLabel(apv);
							logger.warn("generate eub apv file successfully");
							if (eubShippingLabel != null && eubShippingLabel.length >= 10 * 1024) {
								FileUtils.writeByteArrayToFile(apvFile, eubShippingLabel);
								logger.warn("retrieve eub file");
								populatePackingUserInfo(apv);
							}
						}
					}
					if (eubShippingLabel != null && eubShippingLabel.length >= 10 * 1024) {
						return new ModelAndView("chain/preload_shippingorderbyarticlenumber", "shippingOrderUrl",
								shippingOrderUrl);
					}
				}
			}
		}
		return null;
	}

	private void populatePackingUserInfo(AllocationProductVoucher apv) {
		if (StringUtils.isEmpty(apv.getPackingUser())) {
			User currentUser = AppContext.getContextData().getCurrentUser();
			if (currentUser != null) {
				List<Role> roleList = currentUser.getRoleList();
				if (CollectionUtils.isNotEmpty(roleList)) {
					for (Role role : roleList) {
						if (role.getName().equals("包装员")) {
							apv.setPackingUser(currentUser.getUsername());
							apv.setPackingTime(new Timestamp(System.currentTimeMillis()));
						}
					}
				}
			}
		}
	}

	public void removeApvFile(Long apvId) {

		AllocationProductVoucher apv = this.warehouseService.findAllocationProductVoucher(apvId);

		String apvNo = apv.getAllocationProductVoucherNo();

		String datePath = apvNo.replaceFirst(Env.APV_PREFIX.toUpperCase(), "").substring(0, 6);

		String apvDirPath = Env.APP_REAL_PATH + "apvs/offline_eub/" + datePath;

		logger.warn("apv dir path [" + apvDirPath + "]");

		if (apv.getAllocationProductVoucherList() != null) {
			AllocationProductVoucherList apvl = apv.getAllocationProductVoucherList();
			apvDirPath = apvDirPath + "/" + apvl.getAllocationProductVoucherListNo();
		}

		String apvFileName = apv.getAllocationProductVoucherNo() + ".pdf";

		String apvFilePath = apvDirPath + "/" + apvFileName;

		deleteFile(apvFilePath);

	}

	public void deleteFile(String filePath) {
		try {
			FileUtils.forceDelete(new File(filePath));
		} catch (Exception e) {
		}
	}
}


text:
import { module, test } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { fillIn, find, triggerKeyEvent, render } from '@ember/test-helpers';
import hbs from 'htmlbars-inline-precompile';

module('Integration | Component | one-way-input-mask', function(hooks) {
  setupRenderingTest(hooks);

  test('It masks a passed in value', async function(assert) {
    this.set('value', 123)
    await render(hbs`{{one-way-input-mask value mask='9-9+9'}}`);
    assert.dom('input').hasValue('1-2+3');
  });

  test('The mask updates if the passed value is mutated in the parent', async function(assert) {
    this.set('value', 123)
    await render(hbs`{{one-way-input-mask value mask='9-9+9'}}`);
    assert.dom('input').hasValue('1-2+3');
    this.set('value', 456)
    assert.dom('input').hasValue('4-5+6');
  });

  test('The parent can receive the updated value via the `update` action', async function(assert) {
    this.set('value', 123)
    await render(hbs`{{one-way-input-mask value mask='9-9+9' update=(action (mut value))}}`);
    await fillIn('input', '456');
    assert.equal(this.value, '456');
  });

  test('Update action works when `value` begins as undefined', async function(assert) {
    await render(hbs`{{one-way-input-mask value mask='9-9+9' update=(action (mut value))}}`);
    await fillIn('input', '456');
    assert.equal(this.value, '456');
  });

  test('The parent can receive the masked value via the `update` action', async function(assert) {
    this.set('update', (unmasked, masked) => {
      this.set('masked', masked)
    })
    await render(hbs`{{one-way-input-mask value mask='9-9+9' update=update}}`);
    await fillIn('input', '456');
    assert.equal(this.masked, '4-5+6');
  });

  test('It can accept options', async function(assert) {
    this.set('value', 1)
    this.set('options', { placeholder: '*' });
    await render(hbs`{{one-way-input-mask value mask='9-9+9' options=options}}`);
    assert.dom('input').hasValue('1-*+*');
  });

  test('mask and options are not bound attributes', async function(assert) {
    this.set('options', { placeholder: '*' });
    await render(hbs`{{one-way-input-mask value mask='9-9+9' options=options}}`);
    assert.notOk(find('input').getAttribute('mask'), 'mask is not bound');
    assert.notOk(find('input').getAttribute('options'), 'options is not bound');
  });

  test('mask can dynamically be changed', async function(assert) {
    this.set('mask', '9-9+9');
    this.set('value', 123);
    await render(hbs`{{one-way-input-mask value mask=mask}}`);
    assert.dom('input').hasValue('1-2+3');

    this.set('mask', '9_9_9');
    assert.dom('input').hasValue('1_2_3');
  });

  test('options can dynamically be changed', async function(assert) {
    this.set('value', 1)
    this.set('options', { placeholder: '*' });
    await render(hbs`{{one-way-input-mask value mask='9-9+9' options=options}}`);
    assert.dom('input').hasValue('1-*+*');

    this.set('options', { placeholder: '_' });
    assert.dom('input').hasValue('1-_+_');
  });

  test('It can have classes', async function(assert) {
    this.set('value', 123)
    await render(hbs`{{one-way-input-mask value mask='9-9+9' class='foo'}}`);
    assert.dom('.foo').hasValue('1-2+3');
  });

  test('It does not throw errors if key event methods are not passed in', async function(assert) {
    this.set('value', 123)
    await render(hbs`{{one-way-input-mask value mask='9-9+9'}}`);
    await triggerKeyEvent('input', 'keyup', 13);
    await triggerKeyEvent('input', 'keyup', 27);
    assert.dom('input').hasValue('1-2+3', 'no errors thrown');
  });

  test('Shows the correct value in input if modified in `update` action', async function(assert) {
    this.set('num', 15)
    this.set('update', unmaskedValue => {
      let number = parseInt(unmaskedValue, 10);
      if (number > 15) {
        this.set('num', '15');
      } else {
        this.set('num', number);
      }
    });
    await render(hbs`{{one-way-input-mask num mask='999999' update=update
      options=(hash
        showMaskOnFocus=false
        showMaskOnHover=false
        jitMasking=true)}}`);
    assert.dom('input').hasValue('15');

    await fillIn('input', '155');
    assert.dom('input').hasValue('15');
  });
});


text:
package io.buoyant.namerd.iface

import java.net.InetSocketAddress

import com.twitter.conversions.time._
import com.twitter.finagle.Name.Bound
import com.twitter.finagle.http._
import com.twitter.finagle.naming.NameInterpreter
import com.twitter.finagle.{Status => _, _}
import com.twitter.io.{Buf, Reader}
import com.twitter.util._
import io.buoyant.namer.{ConfiguredDtabNamer, RichActivity}
import io.buoyant.namerd._
import io.buoyant.namerd.storage.InMemoryDtabStore
import io.buoyant.test.Awaits
import org.scalatest.{Assertion, FunSuite}

class HttpControlServiceTest extends FunSuite with Awaits {

  val defaultDtabs = Map(
    "yeezus" -> Dtab.read("/yeezy => /yeezus"),
    "tlop" -> Dtab.read("/yeezy => /pablo")
  )

  val v1Stamp = DtabHandler.versionString(InMemoryDtabStore.InitialVersion)

  def newDtabStore(dtabs: Map[String, Dtab] = defaultDtabs): DtabStore =
    new InMemoryDtabStore(dtabs)

  def newService(store: DtabStore = newDtabStore()): Service[Request, Response] =
    new HttpControlService(store, { ns =>
      val dtab = store.observe(ns).map {
        case Some(versionedDtab) => versionedDtab.dtab
        case None => Dtab.empty
      }
      ConfiguredDtabNamer(dtab, Nil)
    }, Map.empty)

  def readAndAssert(reader: Reader, value: String): Assertion = {
    val buf = Buf.Utf8(value)
    readAndAssert(reader, buf)
  }

  def readAndAssert(reader: Reader, value: Buf): Assertion = {
    val buf = value.concat(HttpControlService.newline)
    val res = await(reader.read(buf.length)).flatMap(Buf.Utf8.unapply)
    assert(res == Some(buf).flatMap(Buf.Utf8.unapply))
  }

  test("dtab round-trips through json") {
    val dtab = Dtab.read("/tshirt => /suit")
    val json = Buf.Utf8("""[{"prefix":"/tshirt","dst":"/suit"}]""")
    assert(Json.read[Seq[Dentry]](json) == Return(dtab))
    assert(Json.write(dtab) == json)
  }

  test("GET /api/1/dtabs") {
    val req = Request()
    req.uri = "/api/1/dtabs"
    val service = newService()
    val rsp = Await.result(service(req), 1.second)
    assert(rsp.status == Status.Ok)
    assert(rsp.contentType == Some(MediaType.Json))
    val expected = Json.write(defaultDtabs.keys.toSeq.sorted).concat(HttpControlService.newline)
    assert(rsp.content == expected)
  }

  test("GET /api/1/dtabs watch") {
    val req = Request("/api/1/dtabs?watch=true")
    val store = newDtabStore()
    val service = newService(store)
    val rsp = Await.result(service(req), 1.second)
    assert(rsp.status == Status.Ok)
    assert(rsp.contentType == Some(MediaType.Json))

    readAndAssert(rsp.reader, """["yeezus","tlop"]""")

    await(store.create("graduation", Dtab.empty))
    readAndAssert(rsp.reader, """["yeezus","tlop","graduation"]""")

    rsp.reader.discard()
  }

  test("streaming response is de-duplicated") {
    val req = Request("/api/1/dtabs?watch=true")
    val (dtabs, witness) = Activity[Set[Ns]]()
    val store = new DtabStore {
      def update(ns: Ns, dtab: Dtab, version: DtabStore.Version): Future[Unit] = ???
      def put(ns: Ns, dtab: Dtab): Future[Unit] = ???
      def observe(ns: Ns): Activity[Option[VersionedDtab]] = ???
      def delete(ns: Ns): Future[Unit] = ???
      def list(): Activity[Set[Ns]] = dtabs
      def create(ns: Ns, dtab: Dtab): Future[Unit] = ???
    }
    val service = newService(store)
    witness.notify(Return(Set.empty))
    val rsp = Await.result(service(req), 1.second)
    assert(rsp.status == Status.Ok)
    assert(rsp.contentType == Some(MediaType.Json))

    readAndAssert(rsp.reader, """[]""")

    witness.notify(Return(Set("hello")))
    witness.notify(Return(Set("hello")))
    witness.notify(Return(Set("hello")))
    witness.notify(Return(Set("goodbye")))

    readAndAssert(rsp.reader, """["hello"]""")
    readAndAssert(rsp.reader, """["goodbye"]""")

    rsp.reader.discard()
  }

  test("GET /api/1/dtabs/") {
    val req = Request()
    req.uri = "/api/1/dtabs/"
    val service = newService()
    val rsp = Await.result(service(req), 1.second)
    assert(rsp.status == Status.Ok)
    assert(rsp.contentType == Some(MediaType.Json))
    val expected = Json.write(defaultDtabs.keys.toSeq.sorted).concat(HttpControlService.newline)
    assert(rsp.content == expected)
  }

  test("GET /api/1/dtabsexpialidocious") {
    val req = Request()
    req.uri = "/api/1/dtabsexpialidocious"
    val service = newService()
    val rsp = Await.result(service(req), 1.second)
    assert(rsp.status == Status.NotFound)
  }

  test("GET /api/1/dtabs/ns exists") {
    val req = Request()
    req.uri = "/api/1/dtabs/yeezus"
    val service = newService()
    val rsp = Await.result(service(req), 1.second)
    assert(rsp.status == Status.Ok)
    assert(rsp.contentType == Some(MediaType.Json))
    assert(rsp.headerMap("ETag") == v1Stamp)
    val expected = Json.write(defaultDtabs("yeezus")).concat(HttpControlService.newline)
    assert(rsp.content == expected)
  }

  test("GET /api/1/dtabs/ns watch") {
    val req = Request("/api/1/dtabs/yeezus?watch=true")
    val store = newDtabStore()
    val service = newService(store)
    val rsp = Await.result(service(req), 1.second)
    assert(rsp.status == Status.Ok)
    assert(rsp.contentType == Some(MediaType.Json))

    readAndAssert(rsp.reader, Json.write(defaultDtabs("yeezus")))

    val newDtab = Dtab.read("/yeezy=>/kanye")
    await(store.put("yeezus", newDtab))
    readAndAssert(rsp.reader, Json.write(newDtab))

    rsp.reader.discard()
  }

  val acceptsAndMediaTypes = List(
    ("application/dtab", "application/dtab"),
    ("application/dtab;q=0.9", "application/dtab"),
    (MediaType.Txt, MediaType.Txt),
    (MediaType.Txt + ";q=0.9", MediaType.Txt)
  )

  for ((a, mt) <- acceptsAndMediaTypes)
    test(s"GET /api/1/dtabs/ns exists; accept $a") {
      val req = Request()
      req.uri = "/api/1/dtabs/yeezus"
      req.accept = Seq(a, MediaType.Json)
      val service = newService()
      val rsp = Await.result(service(req), 1.second)
      assert(rsp.status == Status.Ok)
      assert(rsp.contentType == Some(mt))
      assert(rsp.headerMap("ETag") == v1Stamp)
      assert(rsp.contentString == defaultDtabs("yeezus").show + "\n")
    }

  test("GET /api/1/dtabs/ns not exists") {
    val req = Request()
    req.uri = "/api/1/dtabs/graduation"
    req.accept = Seq("application/dtab", MediaType.Json)
    val service = newService()
    val rsp = Await.result(service(req), 1.second)
    assert(rsp.status == Status.NotFound)
  }

  test("POST /api/1/dtabs/ns; no content-type") {
    val req = Request()
    req.method = Method.Post
    req.uri = "/api/1/dtabs/graduation"
    req.contentString = "/yeezy => /kanye"
    val service = newService()
    val rsp = Await.result(service(req), 1.second)
    assert(rsp.status == Status.BadRequest)
  }

  test("HEAD /api/1/dtabs/ns returns ETag") {
    val req = Request()
    req.method = Method.Head
    req.uri = "/api/1/dtabs/yeezus"
    val service = newService()
    val rsp = Await.result(service(req), 1.second)
    assert(rsp.status == Status.Ok)
    assert(rsp.headerMap("ETag") == v1Stamp)
    assert(rsp.contentLength == None)
  }

  val data = Map(
    MediaType.Json -> """[{"prefix":"/yeezy","dst":"/kanye"}]""",
    MediaType.Json + ";charset=UTF-8" -> """[{"prefix":"/yeezy","dst":"/kanye"}]""",
    MediaType.Txt -> "/yeezy => /kanye",
    "application/dtab" -> "/yeezy => /kanye"
  )
  for ((ct, body) <- data)
    test(s"POST /api/1/dtabs/ns; $ct") {
      val req = Request()
      req.method = Method.Post
      req.uri = "/api/1/dtabs/graduation"
      req.contentType = ct
      req.contentString = body
      val store = newDtabStore()
      val service = newService(store)
      val rsp = Await.result(service(req), 1.second)
      assert(rsp.status == Status.NoContent)
      val result = Await.result(store.observe("graduation").toFuture)
      assert(result.get.dtab == Dtab.read("/yeezy=>/kanye"))
    }

  for ((ct, body) <- data) {
    test(s"PUT without stamp; $ct") {
      val req = Request()
      req.method = Method.Put
      req.uri = s"/api/1/dtabs/yeezus"
      req.contentType = ct
      req.contentString = body
      val store = newDtabStore()
      val service = newService(store)
      val rsp = Await.result(service(req), 1.second)
      assert(rsp.status == Status.NoContent)
      val result = Await.result(store.observe("yeezus").toFuture)
      assert(result.get.dtab == Dtab.read("/yeezy=>/kanye"))
    }

    test(s"PUT with valid stamp; $ct") {
      val req = Request()
      req.method = Method.Put
      req.uri = s"/api/1/dtabs/yeezus"
      req.headerMap.add("If-Match", v1Stamp)
      req.contentType = ct
      req.contentString = body
      val store = newDtabStore()
      val service = newService(store)
      val rsp = Await.result(service(req), 1.second)
      assert(rsp.status == Status.NoContent)
      val result = Await.result(store.observe("yeezus").toFuture)
      assert(result.get.dtab == Dtab.read("/yeezy=>/kanye"))
    }

    test(s"PUT with invalid stamp; $ct") {
      val req = Request()
      req.method = Method.Put
      req.uri = "/api/1/dtabs/yeezus"
      req.headerMap.add("If-Match", "yolo")
      req.contentType = ct
      req.contentString = body
      val store = newDtabStore()
      val service = newService(store)
      val rsp = Await.result(service(req), 1.second)
      assert(rsp.status == Status.PreconditionFailed)
      val result = Await.result(store.observe("yeezus").toFuture)
      assert(result.get.dtab == Dtab.read("/yeezy=>/yeezus"))
    }
  }

  def interpreter = {
    val (act, witness) = Activity[NameTree[Bound]]()
    val ni = new NameInterpreter {
      override def bind(dtab: Dtab, path: Path): Activity[NameTree[Bound]] = act
    }
    (ni, witness)
  }

  test("bind") {
    val (ni, witness) = interpreter
    def delegate(ns: Ns): NameInterpreter = {
      assert(ns == "default")
      ni
    }
    val service = new HttpControlService(NullDtabStore, delegate, Map.empty)
    val bound = "/#/io.l5d.namer/foo"
    witness.notify(Return(NameTree.Leaf(Name.Bound(Var(Addr.Bound(Address(1))), Path.read(bound)))))

    val resp = await(service(Request("/api/1/bind/default?path=/foo")))
    assert(resp.status == Status.Ok)
    assert(resp.contentString.replaceAllLiterally("\n", "") ==
      """
        |{"type":"leaf",
        |"bound":{"addr":{"type":"bound","addrs":[{"ip":"127.0.0.1","port":1,"meta":{}}],"meta":{}},
        |"id":"/#/io.l5d.namer/foo","path":"/"}}
        |""".stripMargin.replaceAllLiterally("\n", ""))
  }

  test("bind with an extra dtab") {
    val ni = new NameInterpreter {
      override def bind(dtab: Dtab, path: Path): Activity[NameTree[Bound]] = {
        assert(dtab.show == "/foo=>/bar")
        val NameTree.Leaf(Name.Path(p)) = dtab.lookup(path)
        Activity.value(NameTree.Leaf(Name.Bound(Var(Addr.Bound(Address(1))), Path.read("/#/io.l5d.namer") ++ p)))
      }
    }

    def delegate(ns: Ns): NameInterpreter = {
      assert(ns == "default")
      ni
    }
    val service = new HttpControlService(NullDtabStore, delegate, Map.empty)

    val resp = await(service(Request("/api/1/bind/default?path=/foo&dtab=/foo=>/bar")))
    assert(resp.status == Status.Ok)
    assert(resp.contentString.replaceAllLiterally("\n", "") ==
      """
        |{"type":"leaf",
        |"bound":{"addr":{"type":"bound","addrs":[{"ip":"127.0.0.1","port":1,"meta":{}}],"meta":{}},
        |"id":"/#/io.l5d.namer/bar","path":"/"}}
        |""".stripMargin.replaceAllLiterally("\n", ""))
  }

  test("bind watch") {
    val (ni, witness) = interpreter
    def delegate(ns: Ns): NameInterpreter = {
      assert(ns == "default")
      ni
    }
    val service = new HttpControlService(NullDtabStore, delegate, Map.empty)
    val resp = await(service(Request("/api/1/bind/default?path=/foo&watch=true")))

    val bound = Path.read("/#/io.l5d.namer/foo")
    witness.notify(Return(NameTree.Leaf(Name.Bound(Var(Addr.Bound(Address(1))), bound))))
    readAndAssert(
      resp.reader,
      """
        |{"type":"leaf",
        |"bound":{"addr":{"type":"bound","addrs":[{"ip":"127.0.0.1","port":1,"meta":{}}],"meta":{}},
        |"id":"/#/io.l5d.namer/foo","path":"/"}}""".stripMargin.replaceAllLiterally("\n", "")
    )

    witness.notify(Return(NameTree.Neg))
    readAndAssert(
      resp.reader,
      """
        |{"type":"neg"}""".stripMargin.replaceAllLiterally("\n", "")
    )

    val bound2 = Path.read("/#/io.l5d.namer/bar")
    witness.notify(Return(NameTree.Leaf(Name.Bound(Var(Addr.Bound(Address(1))), bound2))))
    readAndAssert(
      resp.reader,
      """
        |{"type":"leaf",
        |"bound":{"addr":{"type":"bound","addrs":[{"ip":"127.0.0.1","port":1,"meta":{}}],"meta":{}},
        |"id":"/#/io.l5d.namer/bar","path":"/"}}""".stripMargin.replaceAllLiterally("\n", "")
    )

    resp.reader.discard()
  }

  test("bind an invalid path") {
    val service = newService(NullDtabStore)
    val resp = await(service(Request("/api/1/bind/default?path=invalid")))
    assert(resp.status == Status.BadRequest)
  }

  test("errors are printed") {
    val (ni, witness) = interpreter
    def delegate(ns: Ns): NameInterpreter = {
      assert(ns == "default")
      ni
    }
    val service = new HttpControlService(NullDtabStore, delegate, Map.empty)
    val resp = await(service(Request("/api/1/bind/default?path=/foo&watch=true")))

    val bound = "/io.l5d.namer/foo"
    witness.notify(Throw(new Exception("error")))
    readAndAssert(resp.reader, "error")

    assert(await(resp.reader.read(0)) == None)

    resp.reader.discard()
  }

  test("addr") {
    val (nameTree, witness) = Activity[NameTree[Name]]()
    val namer = new Namer {
      override def lookup(path: Path): Activity[NameTree[Name]] = nameTree
    }
    val prefix = Path.read("/#/io.l5d.namer")
    val service = new HttpControlService(NullDtabStore, _ => null, Map(prefix -> namer))
    val name = prefix ++ Path.read("/foo")

    val addr = Var[Addr](Addr.Pending)
    witness.notify(Return(NameTree.Leaf(Name.Bound(addr, name))))
    addr() = Addr.Bound(Address(1))

    val resp = await(service(Request(s"/api/1/addr/default?path=${name.show}")))

    assert(resp.status == Status.Ok)
    assert(resp.contentString.replaceAllLiterally("\n", "") ==
      """
        |{"type":"bound",
        |"addrs":[{"ip":"127.0.0.1","port":1,"meta":{}}],"meta":{}}
        |""".stripMargin.replaceAllLiterally("\n", ""))
  }

  test("addr watch") {
    val (nameTree, witness) = Activity[NameTree[Name]]()
    val namer = new Namer {
      override def lookup(path: Path): Activity[NameTree[Name]] = nameTree
    }
    val prefix = Path.read("/io.l5d.namer")
    val service = new HttpControlService(NullDtabStore, _ => null, Map(prefix -> namer))
    val id = "/foo"
    val resp = await(service(Request(s"/api/1/addr/default?path=${prefix.show}$id&watch=true")))
    val addr = Var[Addr](Addr.Bound(Address(1)))
    witness.notify(Return(NameTree.Leaf(Name.Bound(addr, id))))

    readAndAssert(
      resp.reader,
      """
        |{"type":"bound",
        |"addrs":[{"ip":"127.0.0.1","port":1,"meta":{}}],"meta":{}}
        |""".stripMargin.replaceAllLiterally("\n", "")
    )

    addr() = Addr.Bound(Address(1), Address(2))
    readAndAssert(
      resp.reader,
      """
        |{"type":"bound",
        |"addrs":[{"ip":"127.0.0.1","port":1,"meta":{}},{"ip":"127.0.0.1","port":2,"meta":{}}],"meta":{}}
        |""".stripMargin.replaceAllLiterally("\n", "")
    )

    witness.notify(Return(NameTree.Neg))
    readAndAssert(
      resp.reader,
      """
        |{"type":"neg"}
        |""".stripMargin.replaceAllLiterally("\n", "")
    )

    val addr2 = Var[Addr](Addr.Bound(Address(3)))
    witness.notify(Return(NameTree.Leaf(Name.Bound(addr2, id))))
    readAndAssert(
      resp.reader,
      """
        |{"type":"bound",
        |"addrs":[{"ip":"127.0.0.1","port":3,"meta":{}}],"meta":{}}
        |""".stripMargin.replaceAllLiterally("\n", "")
    )

    resp.reader.discard()
  }

  test("addr an invalid path") {
    val service = newService(NullDtabStore)
    val resp = await(service(Request("/api/1/addr/default?path=invalid")))
    assert(resp.status == Status.BadRequest)
  }

  test("delegate an invalid path") {
    val service = newService(NullDtabStore)
    val resp = await(service(Request("/api/1/delegate/default?path=invalid")))
    assert(resp.status == Status.BadRequest)
  }

  test("delegate a path given a namespace") {
    val service = newService()
    val resp = await(service(Request("/api/1/delegate/yeezus?path=/yeezy")))
    assert(resp.status == Status.Ok)
    assert(resp.contentString == """
                                   |{
                                   |  "type":"delegate",
                                   |  "path":"/yeezy",
                                   |  "delegate":{
                                   |    "type":"neg",
                                   |    "path":"/yeezus",
                                   |    "dentry":{
                                   |      "prefix":"/yeezy",
                                   |      "dst":"/yeezus"
                                   |    }
                                   |  }
                                   |}""".stripMargin.replaceAll("\\s", ""))
  }

  test("delegate a path given a dtab") {
    val service = newService()
    val resp = await(service(Request("/api/1/delegate?dtab=/foo=>/bar&path=/foo")))
    assert(resp.status == Status.Ok)
    assert(resp.contentString == """
                                   |{
                                   |  "type":"delegate",
                                   |  "path":"/foo",
                                   |  "delegate":{
                                   |    "type":"neg",
                                   |    "path":"/bar",
                                   |    "dentry":{
                                   |      "prefix":"/foo",
                                   |      "dst":"/bar"
                                   |    }
                                   |  }
                                   |}""".stripMargin.replaceAll("\\s", ""))
  }

  test("delegate a path given a namespace and a dtab") {
    val service = newService()
    val resp = await(service(Request("/api/1/delegate/yeezus?path=/yeezy&dtab=/yeezy=>/bar")))
    assert(resp.status == Status.Ok)
    assert(resp.contentString == """
                                   |{
                                   |  "type":"alt",
                                   |  "path":"/yeezy",
                                   |  "alt":[
                                   |    {
                                   |      "type": "neg",
                                   |      "path": "/bar",
                                   |      "dentry":{
                                   |        "prefix":"/yeezy",
                                   |        "dst":"/bar"
                                   |      }
                                   |    },
                                   |    {
                                   |      "type": "neg",
                                   |      "path": "/yeezus",
                                   |      "dentry": {
                                   |        "prefix": "/yeezy",
                                   |        "dst":"/yeezus"
                                   |      }
                                   |    }
                                   |  ]
                                   |}""".stripMargin.replaceAll("\\s", ""))
  }

  test("resolve w/ dtab") {
    val prefix = Path.read("/io.l5d.namer")

    val ni = new NameInterpreter {
      override def bind(dtab: Dtab, path: Path): Activity[NameTree[Bound]] = {
        val idStr = s"${prefix.show}${dtab.lookup(path).show}"
        Activity.value(NameTree.Leaf(Name.Bound(Var(null), Path.read(idStr))))
      }
    }

    def delegate(ns: Ns): NameInterpreter = ni

    val (nameTreeAct, witness) = Activity[NameTree[Name]]()
    val namer = new Namer {
      override def lookup(path: Path): Activity[NameTree[Name]] = nameTreeAct
    }

    val service = new HttpControlService(newDtabStore(), delegate, Map(prefix -> namer))

    val id = "/foo"

    val addr = Var[Addr](Addr.Pending)
    witness.notify(Return(NameTree.Leaf(Name.Bound(addr, id))))
    val isa = new InetSocketAddress("127.0.0.1", 1)
    val inet = Address.Inet(isa, Addr.Metadata(("isa-meta", "isa-data"))).asInstanceOf[Address]
    addr() = Addr.Bound(Set(inet), Addr.Metadata(("bound-meta", "bound-data")))

    val resp = await(service(Request(s"/api/1/resolve/default?path=/yeezy&dtab=/yeezy=>/foo")))

    assert(resp.status == Status.Ok)
    assert(resp.contentString ==
      """
        |{
        |  "type":"bound",
        |  "addrs":[
        |    {"ip":"127.0.0.1","port":1,"meta":{"isa-meta":"isa-data"}}
        |  ],
        |  "meta":{
        |    "bound-meta":"bound-data"
        |  }
        |}""".stripMargin.replaceAll("\\s", "") + "\n")

  }

  test("resolve watch") {
    val prefix = Path.read("/io.l5d.namer")

    val ni = new NameInterpreter {
      override def bind(dtab: Dtab, path: Path): Activity[NameTree[Bound]] = {
        val idsStr = s"${prefix.show}${dtab.lookup(path).show}"
        Activity.value(NameTree.Leaf(Name.Bound(Var(null), Path.read(idsStr))))
      }
    }

    def delegate(ns: Ns): NameInterpreter = ni

    val (nameTreeAct, witness) = Activity[NameTree[Name]]()
    val namer = new Namer {
      override def lookup(path: Path): Activity[NameTree[Name]] = nameTreeAct
    }

    val service = new HttpControlService(newDtabStore(), delegate, Map(prefix -> namer))

    val id = "/foo"

    val addr = Var[Addr](Addr.Pending)
    witness.notify(Return(NameTree.Leaf(Name.Bound(addr, id))))

    val resp = await(service(Request(s"/api/1/resolve/default?path=/yeezy&dtab=/yeezy=>/foo&watch=true")))

    val isa1 = new InetSocketAddress("127.0.0.1", 1)
    val inet1 = Address.Inet(isa1, Addr.Metadata(("isa-meta-1", "isa-data-1"))).asInstanceOf[Address]
    addr() = Addr.Bound(Set(inet1), Addr.Metadata(("bound-meta", "bound-data")))

    readAndAssert(
      resp.reader,
      """
        |{
        |  "type":"bound",
        |  "addrs":[
        |    {"ip":"127.0.0.1","port":1,"meta":{"isa-meta-1":"isa-data-1"}}
        |  ],
        |  "meta":{
        |    "bound-meta":"bound-data"
        |  }
        |}""".stripMargin.replaceAll("\\s", "")
    )

    val isa2 = new InetSocketAddress("127.0.0.1", 2)
    val inet2 = Address.Inet(isa2, Addr.Metadata(("isa-meta-2", "isa-data-2"))).asInstanceOf[Address]
    addr() = Addr.Bound(Set(inet1, inet2), Addr.Metadata(("bound-meta", "bound-data")))
    readAndAssert(
      resp.reader,
      """
        |{
        |  "type":"bound",
        |  "addrs":[
        |    {"ip":"127.0.0.1","port":1,"meta":{"isa-meta-1":"isa-data-1"}},
        |    {"ip":"127.0.0.1","port":2,"meta":{"isa-meta-2":"isa-data-2"}}
        |  ],
        |  "meta":{
        |    "bound-meta":"bound-data"
        |  }
        |}""".stripMargin.replaceAll("\\s", "")
    )

    witness.notify(Return(NameTree.Neg))
    readAndAssert(
      resp.reader,
      """
        |{
        |  "type":"neg"
        |}""".stripMargin.replaceAll("\\s", "")
    )

    resp.reader.discard()
  }

  test("resolve an invalid path") {
    val service = newService(NullDtabStore)
    val resp = await(service(Request("/api/1/resolve/default?path=invalid")))
    assert(resp.status == Status.BadRequest)
  }
}


text:
\documentclass[xcolor=svgnames]{beamer}
\usetheme{Torino}

\usepackage{epsfig} %for figures
\usepackage{xcolor} %for color
\usepackage[utf8]{inputenc}
\usepackage{multicol}
\usepackage{hyperref}

% latex definitions:
\def\d{{\rm d}}
\def\half{{\textstyle{1\over2}}}

\title[SymPy\hspace{4em}\insertframenumber/
\inserttotalframenumber]{~\\ SymPy Tutorial \\~}

\author[A. Meurer, Matthew Rocklin, Jason Moore]
{Aaron Meurer, Ondřej Čertík, Amit Kumar, Jason Moore, \\ Sartaj Singh, Harsh Gupta}

\pgfdeclareimage[height=1.5cm]{mylogo}{sympy-250px}
\institute{\pgfuseimage{mylogo}}

\date{July 11, 2016}

\begin{document}

\begin{frame}
  \maketitle
\begin{center}
\normalsize All materials for today's tutorial are at \url{http://www.sympy.org/scipy-2016-tutorial/}
\end{center}
\end{frame}

\begin{frame}{Outline}
  \begin{block}{SymPy Introduction}
    \begin{itemize}
    \item Goal
    \item Features
    \item History
    \item Present
    \item Future
    \end{itemize}
  \end{block}

  \begin{block}{Tutorial}
    \begin{itemize}
    \item Intro to SymPy and Basic features
    \item Solving real life problems
    \end{itemize}
  \end{block}
\end{frame}

\begin{frame}{SymPy Goal}
  \begin{block}{Goal}
    Provide a symbolic manipulation library in Python.
  \end{block}
  \pause
  \begin{block}

    ``SymPy is an open source Python library for symbolic mathematics. It aims to
    become a full-featured computer algebra system (CAS) while keeping the code as
    simple as possible in order to be comprehensible and easily extensible. SymPy
    is written entirely in Python and does not require any external libraries.''

  \end{block}
\end{frame}

\begin{frame}{Why SymPy?}
  \begin{block}{}
    \begin{itemize}
      \item Standalone
      \item Full featured
      \item BSD licensed
      \item Embraces Python
      \item Usable as a library
    \end{itemize}
  \end{block}
\end{frame}

\begin{frame}{Features}
  \begin{multicols}{2}
    \tiny
    \begin{itemize}
    \item \textbf{Core Capabilities}
      \begin{itemize}
        \tiny
      \item Basic arithmetic: Support for operators such as +, -, *, /, ** (power)
      \item Simplification
      \item Expansion
      \item Functions: trigonometric, hyperbolic, exponential, roots, logarithms,
        absolute value, spherical harmonics, factorials and gamma functions, zeta
        functions, polynomials, special functions, \ldots
      \item Substitution
      \item Numbers: arbitrary precision integers, rationals, and floats
      \item Noncommutative symbols
      \item Pattern matching
      \end{itemize}
    \item \textbf{Polynomials}
      \begin{itemize}
        \tiny
      \item Basic arithmetic: division, gcd, \ldots
      \item Factorization
      \item Square-free decomposition
      \item Gröbner bases
      \item Partial fraction decomposition
      \item Resultants
      \end{itemize}
    \item \textbf{Calculus}
      \begin{itemize}
        \tiny
      \item Limits: $\lim_{x\to 0}{x\log(x)} = 0$
      \item Differentiation
      \item Integration: It uses extended Risch-Norman heuristic
      \item Taylor (Laurent) series
      \end{itemize}
    \item \textbf{Solving equations}
      \begin{itemize}
        \tiny
      \item Polynomial equations
      \item Algebraic equations
      \item Differential equations
      \item Difference equations
      \item Systems of equations
      \end{itemize}
    \item \textbf{Combinatorics}
      \begin{itemize}
        \tiny
      \item Permutations
      \item Combinations
      \item Partitions
      \item Subsets
      \item Permutation Groups: Polyhedral, Rubik, Symmetric, \ldots
      \item Prufer and Gray Codes
      \end{itemize}

    \end{itemize}
  \end{multicols}
\end{frame}

\begin{frame}{Features}
  \begin{multicols}{2}
    \begin{itemize}
      \tiny
    \item \textbf{Discrete math}
      \begin{itemize}
        \tiny
      \item Binomial coefficients
      \item Summations
      \item Products
      \item Number theory: generating prime numbers, primality testing, integer
        factorization, \ldots
      \item Logic expressions
      \end{itemize}

    \item \textbf{Matrices}
      \begin{itemize}
        \tiny
      \item Basic arithmetic
      \item Eigenvalues/eigenvectors
      \item Determinants
      \item Inversion
      \item Solving
      \item Abstract expressions
      \end{itemize}

    \item \textbf{Geometric Algebra}

    \item \textbf{Geometry}
      \begin{itemize}
        \tiny
      \item points, lines, rays, segments, ellipses, circles, polygons, \ldots
      \item Intersection
      \item Tangency
      \item Similarity
      \end{itemize}

    \item \textbf{Plotting}
      \begin{itemize}
        \tiny
      \item Coordinate modes
      \item Plotting Geometric Entities
      \item 2D and 3D
      \item Interactive interface
      \item Colors
      \end{itemize}

    \item \textbf{Physics}
      \begin{itemize}
        \tiny
      \item Units
      \item Mechanics
      \item Quantum
      \item Gaussian Optics
      \item Pauli Algebra
      \end{itemize}

    \item \textbf{Statistics}
      \begin{itemize}
        \tiny
      \item Normal distributions
      \item Uniform distributions
      \item Probability
      \end{itemize}

    \item \textbf{Printing}
      \begin{itemize}
        \tiny
      \item Pretty printing: ASCII/Unicode pretty printing, LaTeX
      \item Code generation: C, Fortran, Python
      \end{itemize}
    \end{itemize}
  \end{multicols}
\end{frame}

\begin{frame}{History}
  \begin{block}{History}
    \begin{itemize}
    \item Ondřej Čertík started the project in 2006.
    \item Development took off in 2007 when SymPy first participated in Google
      Summer of Code. We have participated in every Google Summer of Code since.
    \item In 2011, Aaron Meurer (who also joined from Google Summer of Code) took
      over as lead developer.
    \end{itemize}
  \end{block}
\end{frame}

\begin{frame}{Present}
  \begin{block}{Current Status}
    \begin{itemize}
    \item Over 450 contributors.
    \item Current code base has over 400,000 lines of code and documentation.
    \item We have crossed the point of ``sympy a toy'' to ``sympy a tool''
    \end{itemize}
  \end{block}
\end{frame}

\begin{frame}{Future}
  \begin{block}{GSoC (1/2)}
    These are our current GSoC projects. Expect to see these features by the end
    of the summer.
    \begin{itemize}
    \item \normalsize Group Theory, \small Gaurav Dhingra
    \item \normalsize Extending solveset, \small Kshitij Saraogi
    \item \normalsize Completing Solveset, \small Shekhar Prasad Rajak
    \item \normalsize Implementation of Holonomic Functions, \small Shubham Tibra
    \item \normalsize Implementation of Singularity Functions to solve Beam Bending problems, \small Sampad Kumar Saha

    \end{itemize}
  \end{block}
\end{frame}

\begin{frame}{Future}
  \begin{block}{GSoC (2/2)}
    These are our current GSoC projects. Expect to see these features by the end
    of the summer.
    \begin{itemize}
    \item \normalsize Adding to SymEngine's Polynomial functionality and interfacing it with FLINT \& Piranha \small Srajan Garg
    \item \normalsize Implementing Finite Fields and Set module in SymEngine \small Nishant Nikhil
    \end{itemize}
  \end{block}
\end{frame}

\begin{frame}{Future}
\begin{block}{Other Plans}
\begin{itemize}
\item New assumptions
\item Make things faster
\item Implement more algorithms, so we can compute more things (and also make
  them faster)
\item Make it easier for people to define custom behavior of their own objects
  in Add and Mul
\item Encourage people to use SymPy for many applications
\item https://github.com/sympy/sympy/wiki/gsoc-2016-ideas for full list of
  things we want done
\end{itemize}
\end{block}
\end{frame}

%% I was too lazy to redo these for now

%% \begin{frame}{Git Commits Plots}
%%   \begin{block}{Last Year}
%%     \includegraphics[width=4in]{commits1.pdf}
%%   \end{block}
%% \end{frame}
%%
%% \begin{frame}{Git Commit Plots}
%%   \begin{block}{Last Year}
%%     \begin{itemize}
%%     \item The dotted line is 50 commits.
%%     \item Rough measurement of each project's ``bus factor''
%%     \end{itemize}
%%   \end{block}
%% \end{frame}
%%
%% \begin{frame}{Git Commits Plots}
%%   \begin{block}{All Time}
%%     \includegraphics[width=4in]{commits-all.pdf}
%%   \end{block}
%% \end{frame}
%%
%% \begin{frame}{Git Commit Plots}
%%   \begin{block}{All Time}
%%     \begin{itemize}
%%     \item SymPy has more total contributors\footnote{some of the other projects are actually exaggerated,
%%         because they don't use \texttt{.mailmap}}
%%     \item SymPy has a very welcome and friendly community, which is open, and
%%       actively encourages contributions.
%%     \item The SymPy code base is very approachable to new contributors.
%%     \item To be fair, Google Code-In accounts for a lot of this\ldots
%%     \end{itemize}
%%   \end{block}
%% \end{frame}

\input{authors.tex}

\begin{frame}{Here at SciPy}
  \begin{block}{Talks}
    \begin{itemize}
    \item \normalsize Jason Moore, \textit{Simulating Robot, Vehicle, Spacecraft, and Animal Motion with Python (Advanced)}
      (Tutorial). \\ \footnotesize Monday 1:30 PM - 5:30 PM - Room 103
    \item \normalsize Aaron Meurer, Anthony Scopatz \textit{SymPy Code Generation}. \\ \footnotesize Thursday 11:30
      PM - 12:00 PM - Room 204
    \item \normalsize Ondřej Čertík, Isuru Fernando, Thilina Rathnayake, Abhinav Agarwal \textit{SymEngine: A Fast Symbolic Manipulation Library}. \\ \footnotesize Thursday 3:30
      - 4:00 - Room 204
    \end{itemize}
  \end{block}
\end{frame}

%\begin{frame}{Here at SciPy}
%  \begin{block}{Bof}
%    \begin{itemize}
%      \item SymPy BoF - Wednesday 5:30 PM - 6:30 PM - Rm 203
%    \end{itemize}
%  \end{block}
%  \begin{block}{Sprints}
%    Come sprint with us!
%    \begin{itemize}
%    \item Releasing SymPy 1.1
%    \item Assumptions
%    \item Whatever interests you
%    \item Lot's of tasks that are easy for new contributors
%    \item Friday and Saturday
%    \end{itemize}
%  \end{block}
%\end{frame}

\begin{frame}
\Huge Let's begin!
\end{frame}
\end{document}


text:
package com.heliosmi.euler.worksheet;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import static org.junit.Assert.*;

import com.heliosmi.euler.math.MainService;

/*
 * If we list all the natural numbers below 10 that are multiples of 3 or 5,
 * we get 3, 5, 6 and 9. The sum of these multiples is 23.
 *
 * Find the sum of all the multiples of 3 or 5 below 1000.
 */
@ContextConfiguration(locations = { "classpath:/META-INF/spring/app-context.xml"} )
@RunWith(SpringJUnit4ClassRunner.class)
public class One {
	private Logger log = LoggerFactory.getLogger(getClass());

	@Autowired
	private MainService mainService;

	@Test
	public void checkInitialCondition(){
		List<Integer> multiplesOf3 = mainService.getMultiplesBelowThreshold(3, 10);
		List<Integer> multiplesOf5 = mainService.getMultiplesBelowThreshold(5, 10);

		List<Integer> listOfAllMultiples = multiplesOf3;
		listOfAllMultiples.addAll(multiplesOf5);

		//Get rid of duplicates.
		Set<Integer> setOfMultiples = new HashSet<>(listOfAllMultiples);

		long sum = 0;
		for (Integer i:setOfMultiples){
			sum = sum + i;
		}
		assertEquals(23, sum);
	}

	@Test
	public void assertInitialCondition(){
		//get multiples of 3 below 1000
		//get multiples of 5 below 1000
		//subtract one list from another to remove duplicates
		//add the elements
		List<Integer> multipleOf3 = mainService.getMultiplesBelowThreshold(3,1000);
		List<Integer> multipleOf5 = mainService.getMultiplesBelowThreshold(5, 1000);

		List<Integer> listOfAllMultiples = multipleOf3;
		listOfAllMultiples.addAll(multipleOf5);

		//Get rid of duplicates
		Set<Integer> setOfMultiples = new HashSet<>(listOfAllMultiples);

		long sum =0;
		for (Integer i:setOfMultiples){
			sum = sum + i;
		}

		log.info("Result for problem 1: " + sum);

		//Taken from google
		assertEquals(233168, sum);
	}

}


text:
/***************************************************************************/
/*                                                                         */
/*  ftparams.h                                                             */
/*                                                                         */
/*    FreeType API for possible FT_Parameter tags (specification only).    */
/*                                                                         */
/*  Copyright 2017-2018 by                                                 */
/*  David Turner, Robert Wilhelm, and Werner Lemberg.                      */
/*                                                                         */
/*  This file is part of the FreeType project, and may only be used,       */
/*  modified, and distributed under the terms of the FreeType project      */
/*  license, LICENSE.TXT.  By continuing to use, modify, or distribute     */
/*  this file you indicate that you have read the license and              */
/*  understand and accept it fully.                                        */
/*                                                                         */
/***************************************************************************/

#ifndef FTPARAMS_H_
#define FTPARAMS_H_

#include <ft2build.h>
#include FT_FREETYPE_H

#ifdef FREETYPE_H
#error "freetype.h of FreeType 1 has been loaded!"
#error "Please fix the directory search order for header files"
#error "so that freetype.h of FreeType 2 is found first."
#endif

FT_BEGIN_HEADER

  /**************************************************************************
   *
   * @section:
   *   parameter_tags
   *
   * @title:
   *   Parameter Tags
   *
   * @abstract:
   *   Macros for driver property and font loading parameter tags.
   *
   * @description:
   *   This section contains macros for the @FT_Parameter structure that are
   *   used with various functions to activate some special functionality or
   *   different behaviour of various components of FreeType.
   *
   */

  /***************************************************************************
   *
   * @constant:
   *   FT_PARAM_TAG_IGNORE_TYPOGRAPHIC_FAMILY
   *
   * @description:
   *   A tag for @FT_Parameter to make @FT_Open_Face ignore typographic
   *   family names in the `name' table (introduced in OpenType version
   *   1.4).  Use this for backward compatibility with legacy systems that
   *   have a four-faces-per-family restriction.
   *
   * @since:
   *   2.8
   *
   */
#define FT_PARAM_TAG_IGNORE_TYPOGRAPHIC_FAMILY \
          FT_MAKE_TAG( 'i', 'g', 'p', 'f' )

  /* this constant is deprecated */
#define FT_PARAM_TAG_IGNORE_PREFERRED_FAMILY \
          FT_PARAM_TAG_IGNORE_TYPOGRAPHIC_FAMILY

  /***************************************************************************
   *
   * @constant:
   *   FT_PARAM_TAG_IGNORE_TYPOGRAPHIC_SUBFAMILY
   *
   * @description:
   *   A tag for @FT_Parameter to make @FT_Open_Face ignore typographic
   *   subfamily names in the `name' table (introduced in OpenType version
   *   1.4).  Use this for backward compatibility with legacy systems that
   *   have a four-faces-per-family restriction.
   *
   * @since:
   *   2.8
   *
   */
#define FT_PARAM_TAG_IGNORE_TYPOGRAPHIC_SUBFAMILY \
          FT_MAKE_TAG( 'i', 'g', 'p', 's' )

  /* this constant is deprecated */
#define FT_PARAM_TAG_IGNORE_PREFERRED_SUBFAMILY \
          FT_PARAM_TAG_IGNORE_TYPOGRAPHIC_SUBFAMILY

  /***************************************************************************
   *
   * @constant:
   *   FT_PARAM_TAG_INCREMENTAL
   *
   * @description:
   *   An @FT_Parameter tag to be used with @FT_Open_Face to indicate
   *   incremental glyph loading.
   *
   */
#define FT_PARAM_TAG_INCREMENTAL \
          FT_MAKE_TAG( 'i', 'n', 'c', 'r' )

  /**************************************************************************
   *
   * @constant:
   *   FT_PARAM_TAG_LCD_FILTER_WEIGHTS
   *
   * @description:
   *   An @FT_Parameter tag to be used with @FT_Face_Properties.  The
   *   corresponding argument specifies the five LCD filter weights for a
   *   given face (if using @FT_LOAD_TARGET_LCD, for example), overriding
   *   the global default values or the values set up with
   *   @FT_Library_SetLcdFilterWeights.
   *
   * @since:
   *   2.8
   *
   */
#define FT_PARAM_TAG_LCD_FILTER_WEIGHTS \
          FT_MAKE_TAG( 'l', 'c', 'd', 'f' )

  /**************************************************************************
   *
   * @constant:
   *   FT_PARAM_TAG_RANDOM_SEED
   *
   * @description:
   *   An @FT_Parameter tag to be used with @FT_Face_Properties.  The
   *   corresponding 32bit signed integer argument overrides the font
   *   driver's random seed value with a face-specific one; see
   *   @random-seed.
   *
   * @since:
   *   2.8
   *
   */
#define FT_PARAM_TAG_RANDOM_SEED \
          FT_MAKE_TAG( 's', 'e', 'e', 'd' )

  /**************************************************************************
   *
   * @constant:
   *   FT_PARAM_TAG_STEM_DARKENING
   *
   * @description:
   *   An @FT_Parameter tag to be used with @FT_Face_Properties.  The
   *   corresponding Boolean argument specifies whether to apply stem
   *   darkening, overriding the global default values or the values set up
   *   with @FT_Property_Set (see @no-stem-darkening).
   *
   *   This is a passive setting that only takes effect if the font driver
   *   or autohinter honors it, which the CFF, Type~1, and CID drivers
   *   always do, but the autohinter only in `light' hinting mode (as of
   *   version 2.9).
   *
   * @since:
   *   2.8
   *
   */
#define FT_PARAM_TAG_STEM_DARKENING \
          FT_MAKE_TAG( 'd', 'a', 'r', 'k' )

 /***************************************************************************
  *
  * @constant:
  *   FT_PARAM_TAG_UNPATENTED_HINTING
  *
  * @description:
  *   Deprecated, no effect.
  *
  *   Previously: A constant used as the tag of an @FT_Parameter structure to
  *   indicate that unpatented methods only should be used by the TrueType
  *   bytecode interpreter for a typeface opened by @FT_Open_Face.
  *
  */
#define FT_PARAM_TAG_UNPATENTED_HINTING \
          FT_MAKE_TAG( 'u', 'n', 'p', 'a' )

  /* */

FT_END_HEADER

#endif /* FTPARAMS_H_ */

/* END */


text:
<?php echo __('FORGOT_PASSWORD'); ?>

    <form method="POST" action="/login/forgot">
        <input type="hidden" name="<?php echo \Config::get('security.csrf_token_key');?>" value="<?php echo \Security::fetch_token();?>" />

            <?php echo __('EMAIL'); ?>
            <input type="email" class="form-control" placeholder="<?php echo __('EMAIL'); ?>" name="email"/>

        <button type="submit" class="btn btn-default"><?php echo __('GET_PASSWORD'); ?></button>
    </form>


text:
<?php

class Ess_M2ePro_Model_Walmart_Listing_Product_Variation_Matcher_Attribute_Resolver
{
    protected $_sourceAttributes = array();

    protected $_sourceAttributesNames = array();

    protected $_destinationAttributes = array();

    protected $_destinationAttributesNames = array();

    protected $_resolvedAttributes = array();

    //########################################

    /**
     * @param $attribute
     * @param array $names
     * @return $this
     */
    public function addSourceAttribute($attribute, array $names)
    {
        if (in_array($attribute, $this->_sourceAttributes)) {
            return $this;
        }

        $this->_sourceAttributes[]                = $attribute;
        $this->_sourceAttributesNames[$attribute] = $names;

        return $this;
    }

    /**
     * @param $attribute
     * @param array $names
     * @return $this
     */
    public function addDestinationAttribute($attribute, array $names)
    {
        if (in_array($attribute, $this->_destinationAttributes)) {
            return $this;
        }

        $this->_destinationAttributes[]                = $attribute;
        $this->_destinationAttributesNames[$attribute] = $names;

        return $this;
    }

    //########################################

    /**
     * @return $this
     */
    public function resolve()
    {
        if (array_diff($this->_sourceAttributes, array_keys($this->_resolvedAttributes))) {
            $this->_resolvedAttributes = array();
        }

        foreach ($this->_sourceAttributes as $sourceAttribute) {
            if (!empty($this->_resolvedAttributes[$sourceAttribute]) &&
                in_array($this->_resolvedAttributes[$sourceAttribute], $this->_destinationAttributes)
            ) {
                continue;
            }

            $this->_resolvedAttributes[$sourceAttribute] = null;

            $sourceNames = $this->_sourceAttributesNames[$sourceAttribute];

            foreach ($this->_destinationAttributes as $destinationAttribute) {
                $destinationNames = $this->_destinationAttributesNames[$destinationAttribute];

                if (!empty(array_intersect($sourceNames, $destinationNames)) &&
                    !in_array($destinationAttribute, $this->_resolvedAttributes)
                ) {
                    $this->_resolvedAttributes[$sourceAttribute] = $destinationAttribute;
                    break;
                }
            }
        }

        return $this;
    }

    /**
     * @return array
     */
    public function getResolvedAttributes()
    {
        return $this->_resolvedAttributes;
    }

    //########################################

    /**
     * @return $this
     */
    public function clearSourceAttributes()
    {
        $this->_sourceAttributes      = array();
        $this->_sourceAttributesNames = array();

        return $this;
    }

    /**
     * @return $this
     */
    public function clearDestinationAttributes()
    {
        $this->_destinationAttributes      = array();
        $this->_destinationAttributesNames = array();

        return $this;
    }

    //########################################
}


text:
<?php

return [
    'login'                             => 'Welcome back, :display_name',

    'create_success'                    => 'Success! New :entity has been created.',
    'update_success'                    => 'Success! :entity has been updated.',
    'delete_success'                    => 'Success! :entity has been deleted.',
    'upload_success'                    => 'Success! New :entity has been uploaded.',
    'reset_index_success'               => 'Success! The index has been reset.',
    'cache_clear_success'               => 'Success! The application cache has been cleared.',
    'enable_maintenance_mode_success'   => 'Success! The application is now in maintenance mode.',
    'disable_maintenance_mode_success'  => 'Success! The application is now in active mode.',
    'save_settings_success'             => 'Success! The blog settings have been saved.',

    'create_error'                      => 'Sorry! An error occurred creating :entity.',
    'delete_error'                      => 'Sorry! An error occurred deleting :entity.',
    'upload_error'                      => 'Sorry! An error occurred uploading file.',
    'reset_index_error'                 => 'Sorry! An error occurred while resetting the index.',
    'cache_clear_error'                 => 'Sorry! An error occurred while clearing the cache.',
    'enable_maintenance_mode_error'     => 'Sorry! An error occurred while enabling maintenance mode.',
    'disable_maintenance_mode_error'    => 'Sorry! An error occurred while disabling maintenance mode.',
];


text:
from datetime import timedelta
import time
from .db import db
import jwt
import logging
import requests
from requests.auth import HTTPBasicAuth
from werkzeug.exceptions import abort

_log = logging.getLogger(__name__)

ACCESS_TOKEN_CACHE = "hipchat-tokens:{oauth_id}"

class Tenant:

    def __init__(self, id, secret=None, homepage=None, capabilities_url=None, room_id=None, token_url=None,
                 group_id=None, group_name=None, capdoc=None):
        self.id = id
        self.room_id = room_id
        self.secret = secret
        self.group_id = group_id
        self.group_name = None if not group_name else group_name
        self.homepage = homepage or None if not capdoc else capdoc['links']['homepage']
        self.token_url = token_url or None if not capdoc else capdoc['capabilities']['oauth2Provider']['tokenUrl']
        self.capabilities_url = capabilities_url or None if not capdoc else capdoc['links']['self']

    def to_map(self):
        return {
            "id": self.id,
            "secret": self.secret,
            "room_id": self.room_id,
            "group_id": self.group_id,
            "group_name": self.group_name,
            "homepage": self.homepage,
            "token_url": self.token_url,
            "capabilities_url": self.capabilities_url
        }

    @staticmethod
    def from_map(data):
        filtered = {key: val for key, val in data.items() if not key.startswith('_')}
        return Tenant(**filtered)

    @staticmethod
    def load(client_id):
        client_data = db.get(client_id)
        if client_data:
            return Tenant.from_map(client_data)
        else:
            _log.warn("Cannot find client: %s" % client_id)
            abort(400)

    @property
    def id_query(self):
        return {"id": self.id}

    def get_token(self, token_only=True, scopes=None):
        if scopes is None:
            scopes = ["send_notification"]

        cache_key = ACCESS_TOKEN_CACHE.format(oauth_id=self.id)
        cache_key += ":" + ",".join(scopes)

        def gen_token():
            resp = requests.post(self.token_url, data={"grant_type": "client_credentials", "scope": " ".join(scopes)},
                                 auth=HTTPBasicAuth(self.id, self.secret), timeout=10)
            if resp.status_code == 200:
                _log.debug("Token request response: " + resp.text)
                return resp.json()
            elif resp.status_code == 401:
                _log.error("Client %s is invalid but we weren't notified.  Uninstalling" % self.id)
                raise OauthClientInvalidError(self)
            else:
                raise Exception("Invalid token: %s" % resp.text)

        if token_only:
            token = db.get(cache_key)
            if not token:
                data = gen_token()
                token = data['access_token']
                db[cache_key] = token
            return token
        else:
            return gen_token()

    def sign_jwt(self, user_id, data=None):
        if data is None:
            data = {}

        now = int(time.time())
        exp = now + timedelta(hours=1).total_seconds()

        jwt_data = {"iss": self.id,
                    "iat": now,
                    "exp": exp}

        if user_id:
            jwt_data['prn'] = user_id

        data.update(jwt_data)
        return jwt.encode(data, self.secret)

class OauthClientInvalidError(Exception):
    def __init__(self, client, *args, **kwargs):
        super(OauthClientInvalidError, self).__init__(*args, **kwargs)
        self.client = client


text:
class VirtualCanvas extends Canvas {

	constructor(width, height) {

		// Create the element
		var element = document.createElement("canvas");

		// Set the size
		element.width  = width;
		element.height = height;

		super(element);
	}

}


text:
#ifndef PROGRAMS_PROG_UTIL_H
#define PROGRAMS_PROG_UTIL_H

#ifdef HAVE_CONFIG_H
#  include "config.h"
#endif

#include "libxpack.h"

#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "common_defs.h"

#ifdef __GNUC__
# define _printf(str_idx, args_idx)	\
		__attribute__((format(printf, str_idx, args_idx)))
#else
# define _printf(str_idx, args_idx)
#endif

#ifdef _WIN32

/*
 * Definitions for Windows builds.  Mainly, 'tchar' is defined to be the 2-byte
 * 'wchar_t' type instead of 'char'.  This is the only "easy" way I know of to
 * get full Unicode support on Windows...
 */

#include <wchar.h>
extern int wmain(int argc, wchar_t **argv);
#  define	tmain		wmain
#  define	tchar		wchar_t
#  define	_T(text)	L##text
#  define	T(text)		_T(text)
#  define	TS		"ls"
#  define	TC		"lc"
#  define	tmemcpy		wmemcpy
#  define	topen		_wopen
#  define	tstrchr		wcschr
#  define	tstrcmp		wcscmp
#  define	tstrcpy		wcscpy
#  define	tstrlen		wcslen
#  define	tstrrchr	wcsrchr
#  define	tstrtoul	wcstoul
#  define	tstrxcmp	wcsicmp
#  define	tunlink		_wunlink
#  define	tutimbuf	_utimbuf
#  define	tutime		_wutime
#  ifdef _MSC_VER
     /* Standard file descriptors?  What are those? */
#    define	STDIN_FILENO	0
#    define	STDOUT_FILENO	1
#    define	STDERR_FILENO	2

     /* Fix the broken stat-related definitions. */
#    define	fstat		_fstat
#    define	stat		_stat
#    define	S_ISREG(m)      (((m) & S_IFMT) == S_IFREG)
#    define	S_ISDIR(m)      (((m) & S_IFMT) == S_IFDIR)
#  endif
#  define	O_NOFOLLOW	0

#else /* _WIN32 */

/* Standard definitions for everyone else */

#  define	tmain		main
#  define	tchar		char
#  define	T(text)		text
#  define	TS		"s"
#  define	TC		"c"
#  define	tmemcpy		memcpy
#  define	topen		open
#  define	tstrchr		strchr
#  define	tstrcmp		strcmp
#  define	tstrcpy		strcpy
#  define	tstrlen		strlen
#  define	tstrrchr	strrchr
#  define	tstrtoul	strtoul
#  define	tstrxcmp	strcmp
#  define	tunlink		unlink
#  define	tutimbuf	utimbuf
#  define	tutime		utime
#  define	O_BINARY	0

#endif /* !_WIN32 */

extern const tchar *program_invocation_name;

extern void _printf(1, 2) msg(const char *fmt, ...);
extern void _printf(1, 2) msg_errno(const char *fmt, ...);

extern void *xmalloc(size_t size);

extern u64 current_time(void);

extern const tchar *get_filename(const tchar *path);

struct file_stream {
	int fd;
	tchar *name;
	bool is_standard_stream;
};

extern int xopen_for_read(const tchar *path, struct file_stream *strm);
extern int xopen_for_write(const tchar *path, bool force,
			   struct file_stream *strm);

extern ssize_t xread(struct file_stream *strm, void *buf, size_t count);
extern int skip_bytes(struct file_stream *strm, size_t count);
extern int full_write(struct file_stream *strm, const void *buf, size_t count);

extern int xclose(struct file_stream *strm);

extern u32 parse_chunk_size(const tchar *arg);
extern int parse_compression_level(const tchar *arg);

extern struct xpack_compressor *alloc_compressor(u32 chunk_size, int level);
extern struct xpack_decompressor *alloc_decompressor(void);

/* tgetopt.c */

extern tchar *toptarg;
extern int toptind, topterr, toptopt;

extern int tgetopt(int argc, tchar *argv[], const tchar *optstring);

#endif /* PROGRAMS_PROG_UTIL_H */