/*
 * Wireless Host Controller (WHC) driver.
 *
 * Copyright (C) 2007 Cambridge Silicon Radio Ltd.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version
 * 2 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/uwb/umc.h>

#include "../../wusbcore/wusbhc.h"

#include "whcd.h"

/*
 * One time initialization.
 *
 * Nothing to do here.
 */
static int whc_reset(struct usb_hcd *usb_hcd)
{
	return 0;
}

/*
 * Start the wireless host controller.
 *
 * Start device notification.
 *
 * Put hc into run state, set DNTS parameters.
 */
static int whc_start(struct usb_hcd *usb_hcd)
{
	struct wusbhc *wusbhc = usb_hcd_to_wusbhc(usb_hcd);
	struct whc *whc = wusbhc_to_whc(wusbhc);
	u8 bcid;
	int ret;

	mutex_lock(&wusbhc->mutex);

	le_writel(WUSBINTR_GEN_CMD_DONE
		  | WUSBINTR_HOST_ERR
		  | WUSBINTR_ASYNC_SCHED_SYNCED
		  | WUSBINTR_DNTS_INT
		  | WUSBINTR_ERR_INT
		  | WUSBINTR_INT,
		  whc->base + WUSBINTR);

	/* set cluster ID */
	bcid = wusb_cluster_id_get();
	ret = whc_set_cluster_id(whc, bcid);
	if (ret < 0)
		goto out;
	wusbhc->cluster_id = bcid;

	/* start HC */
	whc_write_wusbcmd(whc, WUSBCMD_RUN, WUSBCMD_RUN);

	usb_hcd->uses_new_polling = 1;
	set_bit(HCD_FLAG_POLL_RH, &usb_hcd->flags);
	usb_hcd->state = HC_STATE_RUNNING;

out:
	mutex_unlock(&wusbhc->mutex);
	return ret;
}

/*
 * Stop the wireless host controller.
 *
 * Stop device notification.
 *
 * Wait for pending transfer to stop? Put hc into stop state?
 */
static void whc_stop(struct usb_hcd *usb_hcd)
{
	struct wusbhc *wusbhc = usb_hcd_to_wusbhc(usb_hcd);
	struct whc *whc = wusbhc_to_whc(wusbhc);

	mutex_lock(&wusbhc->mutex);

	/* stop HC */
	le_writel(0, whc->base + WUSBINTR);
	whc_write_wusbcmd(whc, WUSBCMD_RUN, 0);
	whci_wait_for(&whc->umc->dev, whc->base + WUSBSTS,
		      WUSBSTS_HCHALTED, WUSBSTS_HCHALTED,
		      100, "HC to halt");

	wusb_cluster_id_put(wusbhc->cluster_id);

	mutex_unlock(&wusbhc->mutex);
}

static int whc_get_frame_number(struct usb_hcd *usb_hcd)
{
	/* Frame numbers are not applicable to WUSB. */
	return -ENOSYS;
}

/*
 * Queue an URB to the ASL or PZL
 */
static int whc_urb_enqueue(struct usb_hcd *usb_hcd, struct urb *urb,
			   gfp_t mem_flags)
{
	struct wusbhc *wusbhc = usb_hcd_to_wusbhc(usb_hcd);
	struct whc *whc = wusbhc_to_whc(wusbhc);
	int ret;

	switch (usb_pipetype(urb->pipe)) {
	case PIPE_INTERRUPT:
		ret = pzl_urb_enqueue(whc, urb, mem_flags);
		break;
	case PIPE_ISOCHRONOUS:
		dev_err(&whc->umc->dev, "isochronous transfers unsupported\n");
		ret = -ENOTSUPP;
		break;
	case PIPE_CONTROL:
	case PIPE_BULK:
	default:
		ret = asl_urb_enqueue(whc, urb, mem_flags);
		break;
	};

	return ret;
}

/*
 * Remove a queued URB from the ASL or PZL.
 */
static int whc_urb_dequeue(struct usb_hcd *usb_hcd, struct urb *urb, int status)
{
	struct wusbhc *wusbhc = usb_hcd_to_wusbhc(usb_hcd);
	struct whc *whc = wusbhc_to_whc(wusbhc);
	int ret;

	switch (usb_pipetype(urb->pipe)) {
	case PIPE_INTERRUPT:
		ret = pzl_urb_dequeue(whc, urb, status);
		break;
	case PIPE_ISOCHRONOUS:
		ret = -ENOTSUPP;
		break;
	case PIPE_CONTROL:
	case PIPE_BULK:
	default:
		ret = asl_urb_dequeue(whc, urb, status);
		break;
	};

	return ret;
}

/*
 * Wait for all URBs to the endpoint to be completed, then delete the
 * qset.
 */
static void whc_endpoint_disable(struct usb_hcd *usb_hcd,
				 struct usb_host_endpoint *ep)
{
	struct wusbhc *wusbhc = usb_hcd_to_wusbhc(usb_hcd);
	struct whc *whc = wusbhc_to_whc(wusbhc);
	struct whc_qset *qset;

	qset = ep->hcpriv;
	if (qset) {
		ep->hcpriv = NULL;
		if (usb_endpoint_xfer_bulk(&ep->desc)
		    || usb_endpoint_xfer_control(&ep->desc))
			asl_qset_delete(whc, qset);
		else
			pzl_qset_delete(whc, qset);
	}
}

static void whc_endpoint_reset(struct usb_hcd *usb_hcd,
			       struct usb_host_endpoint *ep)
{
	struct wusbhc *wusbhc = usb_hcd_to_wusbhc(usb_hcd);
	struct whc *whc = wusbhc_to_whc(wusbhc);
	struct whc_qset *qset;
	unsigned long flags;

	spin_lock_irqsave(&whc->lock, flags);

	qset = ep->hcpriv;
	if (qset) {
		qset->remove = 1;
		qset->reset = 1;

		if (usb_endpoint_xfer_bulk(&ep->desc)
		    || usb_endpoint_xfer_control(&ep->desc))
			queue_work(whc->workqueue, &whc->async_work);
		else
			queue_work(whc->workqueue, &whc->periodic_work);
	}

	spin_unlock_irqrestore(&whc->lock, flags);
}

static struct hc_driver whc_hc_driver = {
	.description = "whci-hcd",
	.product_desc = "Wireless host controller",
	.hcd_priv_size = sizeof(struct whc) - sizeof(struct usb_hcd),
	.irq = whc_int_handler,
	.flags = HCD_USB2,

	.reset = whc_reset,
	.start = whc_start,
	.stop = whc_stop,
	.get_frame_number = whc_get_frame_number,
	.urb_enqueue = whc_urb_enqueue,
	.urb_dequeue = whc_urb_dequeue,
	.endpoint_disable = whc_endpoint_disable,
	.endpoint_reset = whc_endpoint_reset,

	.hub_status_data = wusbhc_rh_status_data,
	.hub_control = wusbhc_rh_control,
	.bus_suspend = wusbhc_rh_suspend,
	.bus_resume = wusbhc_rh_resume,
	.start_port_reset = wusbhc_rh_start_port_reset,
};

static int whc_probe(struct umc_dev *umc)
{
	int ret = -ENOMEM;
	struct usb_hcd *usb_hcd;
	struct wusbhc *wusbhc = NULL;
	struct whc *whc = NULL;
	struct device *dev = &umc->dev;

	usb_hcd = usb_create_hcd(&whc_hc_driver, dev, "whci");
	if (usb_hcd == NULL) {
		dev_err(dev, "unable to create hcd\n");
		goto error;
	}

	usb_hcd->wireless = 1;
	usb_hcd->self.sg_tablesize = 2048; /* somewhat arbitrary */

	wusbhc = usb_hcd_to_wusbhc(usb_hcd);
	whc = wusbhc_to_whc(wusbhc);
	whc->umc = umc;

	ret = whc_init(whc);
	if (ret)
		goto error;

	wusbhc->dev = dev;
	wusbhc->uwb_rc = uwb_rc_get_by_grandpa(umc->dev.parent);
	if (!wusbhc->uwb_rc) {
		ret = -ENODEV;
		dev_err(dev, "cannot get radio controller\n");
		goto error;
	}

	if (whc->n_devices > USB_MAXCHILDREN) {
		dev_warn(dev, "USB_MAXCHILDREN too low for WUSB adapter (%u ports)\n",
			 whc->n_devices);
		wusbhc->ports_max = USB_MAXCHILDREN;
	} else
		wusbhc->ports_max = whc->n_devices;
	wusbhc->mmcies_max      = whc->n_mmc_ies;
	wusbhc->start           = whc_wusbhc_start;
	wusbhc->stop            = whc_wusbhc_stop;
	wusbhc->mmcie_add       = whc_mmcie_add;
	wusbhc->mmcie_rm        = whc_mmcie_rm;
	wusbhc->dev_info_set    = whc_dev_info_set;
	wusbhc->bwa_set         = whc_bwa_set;
	wusbhc->set_num_dnts    = whc_set_num_dnts;
	wusbhc->set_ptk         = whc_set_ptk;
	wusbhc->set_gtk         = whc_set_gtk;

	ret = wusbhc_create(wusbhc);
	if (ret)
		goto error_wusbhc_create;

	ret = usb_add_hcd(usb_hcd, whc->umc->irq, IRQF_SHARED);
	if (ret) {
		dev_err(dev, "cannot add HCD: %d\n", ret);
		goto error_usb_add_hcd;
	}

	ret = wusbhc_b_create(wusbhc);
	if (ret) {
		dev_err(dev, "WUSBHC phase B setup failed: %d\n", ret);
		goto error_wusbhc_b_create;
	}

	whc_dbg_init(whc);

	return 0;

error_wusbhc_b_create:
	usb_remove_hcd(usb_hcd);
error_usb_add_hcd:
	wusbhc_destroy(wusbhc);
error_wusbhc_create:
	uwb_rc_put(wusbhc->uwb_rc);
error:
	whc_clean_up(whc);
	if (usb_hcd)
		usb_put_hcd(usb_hcd);
	return ret;
}

static void whc_remove(struct umc_dev *umc)
{
	struct usb_hcd *usb_hcd = dev_get_drvdata(&umc->dev);
	struct wusbhc *wusbhc = usb_hcd_to_wusbhc(usb_hcd);
	struct whc *whc = wusbhc_to_whc(wusbhc);

	if (usb_hcd) {
		whc_dbg_clean_up(whc);
		wusbhc_b_destroy(wusbhc);
		usb_remove_hcd(usb_hcd);
		wusbhc_destroy(wusbhc);
		uwb_rc_put(wusbhc->uwb_rc);
		whc_clean_up(whc);
		usb_put_hcd(usb_hcd);
	}
}

static struct umc_driver whci_hc_driver = {
	.name =		"whci-hcd",
	.cap_id =       UMC_CAP_ID_WHCI_WUSB_HC,
	.probe =	whc_probe,
	.remove =	whc_remove,
};

static int __init whci_hc_driver_init(void)
{
	return umc_driver_register(&whci_hc_driver);
}
module_init(whci_hc_driver_init);

static void __exit whci_hc_driver_exit(void)
{
	umc_driver_unregister(&whci_hc_driver);
}
module_exit(whci_hc_driver_exit);

/* PCI device ID's that we handle (so it gets loaded) */
static struct pci_device_id __used whci_hcd_id_table[] = {
	{ PCI_DEVICE_CLASS(PCI_CLASS_WIRELESS_WHCI, ~0) },
	{ /* empty last entry */ }
};
MODULE_DEVICE_TABLE(pci, whci_hcd_id_table);

MODULE_DESCRIPTION("WHCI Wireless USB host controller driver");
MODULE_AUTHOR("Cambridge Silicon Radio Ltd.");
MODULE_LICENSE("GPL");


package android.support.v4.d;

import android.os.Handler;
import android.os.Handler.Callback;
import android.os.HandlerThread;
import android.os.Message;
import com.tencent.tmassistantsdk.downloadservice.Downloads;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public final class c {
    private Callback Ku = new Callback() {
        public final boolean handleMessage(Message message) {
            switch (message.what) {
                case 0:
                    c cVar = c.this;
                    synchronized (cVar.mLock) {
                        if (cVar.mHandler.hasMessages(1)) {
                            break;
                        }
                        cVar.mThread.quit();
                        cVar.mThread = null;
                        cVar.mHandler = null;
                    }
                case 1:
                    c cVar2 = c.this;
                    ((Runnable) message.obj).run();
                    synchronized (cVar2.mLock) {
                        cVar2.mHandler.removeMessages(0);
                        cVar2.mHandler.sendMessageDelayed(cVar2.mHandler.obtainMessage(0), (long) cVar2.Kv);
                    }
                    break;
            }
            return true;
        }
    };
    final int Kv;
    private int mGeneration;
    Handler mHandler;
    final Object mLock = new Object();
    private final int mPriority;
    HandlerThread mThread;
    private final String mThreadName;

    /* renamed from: android.support.v4.d.c$2 */
    class AnonymousClass2 implements Runnable {
        final /* synthetic */ Handler Kx;
        final /* synthetic */ a Ky;
        final /* synthetic */ Callable val$callable;

        AnonymousClass2(Callable callable, Handler handler, a aVar) {
            this.val$callable = callable;
            this.Kx = handler;
            this.Ky = aVar;
        }

        public final void run() {
            Object call;
            try {
                call = this.val$callable.call();
            } catch (Exception e) {
                call = null;
            }
            this.Kx.post(new Runnable() {
                public final void run() {
                    AnonymousClass2.this.Ky.D(call);
                }
            });
        }
    }

    public interface a<T> {
        void D(T t);
    }

    public c(String str) {
        this.mThreadName = str;
        this.mPriority = 10;
        this.Kv = Downloads.MIN_WAIT_FOR_NETWORK;
        this.mGeneration = 0;
    }

    /* Access modifiers changed, original: final */
    public final void f(Runnable runnable) {
        synchronized (this.mLock) {
            if (this.mThread == null) {
                this.mThread = new HandlerThread(this.mThreadName, this.mPriority);
                this.mThread.start();
                this.mHandler = new Handler(this.mThread.getLooper(), this.Ku);
                this.mGeneration++;
            }
            this.mHandler.removeMessages(0);
            this.mHandler.sendMessage(this.mHandler.obtainMessage(1, runnable));
        }
    }

    public final <T> T a(Callable<T> callable, int i) {
        final ReentrantLock reentrantLock = new ReentrantLock();
        final Condition newCondition = reentrantLock.newCondition();
        final AtomicReference atomicReference = new AtomicReference();
        final AtomicBoolean atomicBoolean = new AtomicBoolean(true);
        final Callable<T> callable2 = callable;
        f(new Runnable() {
            public final void run() {
                try {
                    atomicReference.set(callable2.call());
                } catch (Exception e) {
                }
                reentrantLock.lock();
                try {
                    atomicBoolean.set(false);
                    newCondition.signal();
                } finally {
                    reentrantLock.unlock();
                }
            }
        });
        reentrantLock.lock();
        try {
            T t;
            if (atomicBoolean.get()) {
                long toNanos = TimeUnit.MILLISECONDS.toNanos((long) i);
                while (true) {
                    try {
                        toNanos = newCondition.awaitNanos(toNanos);
                    } catch (InterruptedException e) {
                    }
                    if (!atomicBoolean.get()) {
                        t = atomicReference.get();
                        reentrantLock.unlock();
                        break;
                    } else if (toNanos <= 0) {
                        throw new InterruptedException("timeout");
                    }
                }
            }
            t = atomicReference.get();
            return t;
        } finally {
            reentrantLock.unlock();
        }
    }
}


/**
 * Copyright (C) 2007 Rob Buis <buis@kde.org>
 * Copyright (C) 2007 Nikolas Zimmermann <zimmermann@kde.org>
 * Copyright (C) 2007 Eric Seidel <eric@webkit.org>
 * Copyright (C) 2009 Google, Inc.  All rights reserved.
 * Copyright (C) Research In Motion Limited 2010. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#pragma once

#include "PaintInfo.h"
#include "RenderObject.h"

namespace WebCore {

class FloatPoint;
class FloatRect;
class ImageBuffer;
class LayoutRect;
class RenderBoxModelObject;
class RenderElement;
class RenderGeometryMap;
class RenderLayerModelObject;
class RenderStyle;
class RenderSVGRoot;
class TransformState;

// SVGRendererSupport is a helper class sharing code between all SVG renderers.
class SVGRenderSupport {
public:
    static void layoutDifferentRootIfNeeded(const RenderElement&);

    // Shares child layouting code between RenderSVGRoot/RenderSVG(Hidden)Container
    static void layoutChildren(RenderElement&, bool selfNeedsLayout);

    // Helper function determining wheter overflow is hidden
    static bool isOverflowHidden(const RenderElement&);

    // Calculates the repaintRect in combination with filter, clipper and masker in local coordinates.
    static void intersectRepaintRectWithResources(const RenderElement&, FloatRect&);

    // Determines whether a container needs to be laid out because it's filtered and a child is being laid out.
    static bool filtersForceContainerLayout(const RenderElement&);

    // Determines whether the passed point lies in a clipping area
    static bool pointInClippingArea(const RenderElement&, const FloatPoint&);

    static void computeContainerBoundingBoxes(const RenderElement& container, FloatRect& objectBoundingBox, bool& objectBoundingBoxValid, FloatRect& strokeBoundingBox, FloatRect& repaintBoundingBox);
    static bool paintInfoIntersectsRepaintRect(const FloatRect& localRepaintRect, const AffineTransform& localTransform, const PaintInfo&);

    // Important functions used by nearly all SVG renderers centralizing coordinate transformations / repaint rect calculations
    static LayoutRect clippedOverflowRectForRepaint(const RenderElement&, const RenderLayerModelObject* repaintContainer);
    static Optional<FloatRect> computeFloatVisibleRectInContainer(const RenderElement&, const FloatRect&, const RenderLayerModelObject* container, RenderObject::VisibleRectContext);
    static const RenderElement& localToParentTransform(const RenderElement&, AffineTransform &);
    static void mapLocalToContainer(const RenderElement&, const RenderLayerModelObject* repaintContainer, TransformState&, bool* wasFixed);
    static const RenderElement* pushMappingToContainer(const RenderElement&, const RenderLayerModelObject* ancestorToStopAt, RenderGeometryMap&);
    static bool checkForSVGRepaintDuringLayout(const RenderElement&);

    // Shared between SVG renderers and resources.
    static void applyStrokeStyleToContext(GraphicsContext*, const RenderStyle&, const RenderElement&);

    // Determines if any ancestor's transform has changed.
    static bool transformToRootChanged(RenderElement*);

    static void clipContextToCSSClippingArea(GraphicsContext&, const RenderElement& renderer);

    static void styleChanged(RenderElement&, const RenderStyle*);

#if ENABLE(CSS_COMPOSITING)
    static bool isolatesBlending(const RenderStyle&);
    static void updateMaskedAncestorShouldIsolateBlending(const RenderElement&);
#endif

    static RenderSVGRoot* findTreeRootObject(RenderElement&);
    static const RenderSVGRoot* findTreeRootObject(const RenderElement&);

private:
    // This class is not constructable.
    SVGRenderSupport();
    ~SVGRenderSupport();
};

} // namespace WebCore


// LzmaRam.h

#ifndef __LzmaRam_h
#define __LzmaRam_h

#include <stdlib.h>
#include "../../../Common/Types.h"

/*
LzmaRamEncode: BCJ + LZMA RAM->RAM compressing.
It uses .lzma format, but it writes one additional byte to .lzma file:
  0: - no filter
  1: - x86(BCJ) filter.

To provide best compression ratio dictionarySize mustbe >= inSize

LzmaRamEncode allocates Data with MyAlloc/BigAlloc functions.
RAM Requirements:
  RamSize = dictionarySize * 9.5 + 6MB + FilterBlockSize
    FilterBlockSize = 0, if useFilter == false
    FilterBlockSize = inSize, if useFilter == true

  Return code:
    0 - OK
    1 - Unspecified Error
    2 - Memory allocating error
    3 - Output buffer OVERFLOW

If you use SZ_FILTER_AUTO mode, then encoder will use 2 or 3 passes:
  2 passes when FILTER_NO provides better compression.
  3 passes when FILTER_YES provides better compression.
*/

enum ESzFilterMode
{
  SZ_FILTER_NO,
  SZ_FILTER_YES,
  SZ_FILTER_AUTO
};

int LzmaRamEncode(
    const Byte *inBuffer, size_t inSize,
    Byte *outBuffer, size_t outSize, size_t *outSizeProcessed,
    UInt32 dictionarySize, ESzFilterMode filterMode);

#endif


package breeze.integrate

import breeze.linalg._
import org.apache.commons.math3.ode.nonstiff.{HighamHall54Integrator => ApacheHighamHall54Integrator}

class HighamHall54Integrator(
    minStep: Double,
    maxStep: Double,
    relTol: DenseVector[Double] = null,
    absTol: DenseVector[Double] = null)
    extends ApacheAdaptiveStepIntegrator(relTol, absTol) {

  type T = ApacheHighamHall54Integrator

  protected final def create: ApacheHighamHall54Integrator =
    new ApacheHighamHall54Integrator(
      minStep,
      maxStep,
      ApacheAdaptiveStepIntegrator.defaultAbsTol,
      ApacheAdaptiveStepIntegrator.defaultRelTol)
}


-- Jan 16, 2008 8:58:57 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Column (Name,IsMandatory,IsTranslated,IsIdentifier,SeqNo,Version,IsActive,AD_Table_ID,AD_Column_ID,ColumnName,AD_Client_ID,AD_Org_ID,FieldLength,IsParent,Created,IsSyncDatabase,AD_Reference_ID,CreatedBy,Updated,AD_Element_ID,IsUpdateable,IsKey,IsSelectionColumn,UpdatedBy,IsAlwaysUpdateable,IsEncrypted,EntityType) VALUES ('Group1','N','N','N',0,0,'Y',477,54237,'Group1',0,0,255,'N',TO_TIMESTAMP('2008-01-16 20:58:54','YYYY-MM-DD HH24:MI:SS'),'N',10,0,TO_TIMESTAMP('2008-01-16 20:58:54','YYYY-MM-DD HH24:MI:SS'),52018,'Y','N','N',0,'N','N','D')
;

-- Jan 16, 2008 8:58:57 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Column_ID=54237 AND EXISTS (SELECT * FROM AD_Column_Trl tt WHERE tt.AD_Language!=l.AD_Language OR tt.AD_Column_ID!=t.AD_Column_ID)
;

-- Jan 16, 2008 8:59:29 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Column (Name,IsMandatory,IsTranslated,IsIdentifier,SeqNo,Version,IsActive,AD_Table_ID,AD_Column_ID,ColumnName,AD_Client_ID,AD_Org_ID,FieldLength,IsParent,Created,IsSyncDatabase,AD_Reference_ID,CreatedBy,Updated,AD_Element_ID,IsUpdateable,IsKey,IsSelectionColumn,UpdatedBy,IsAlwaysUpdateable,IsEncrypted,EntityType) VALUES ('Group2','N','N','N',0,0,'Y',477,54238,'Group2',0,0,255,'N',TO_TIMESTAMP('2008-01-16 20:59:26','YYYY-MM-DD HH24:MI:SS'),'N',10,0,TO_TIMESTAMP('2008-01-16 20:59:26','YYYY-MM-DD HH24:MI:SS'),52019,'Y','N','N',0,'N','N','D')
;

-- Jan 16, 2008 8:59:29 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Column_ID=54238 AND EXISTS (SELECT * FROM AD_Column_Trl tt WHERE tt.AD_Language!=l.AD_Language OR tt.AD_Column_ID!=t.AD_Column_ID)
;

-- Jan 16, 2008 9:00:22 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Column (Name,IsMandatory,IsTranslated,Description,IsIdentifier,SeqNo,Help,Version,IsActive,AD_Table_ID,AD_Column_ID,ColumnName,AD_Client_ID,AD_Org_ID,FieldLength,IsParent,Created,IsSyncDatabase,AD_Reference_ID,CreatedBy,Updated,AD_Element_ID,IsUpdateable,IsKey,IsSelectionColumn,UpdatedBy,IsAlwaysUpdateable,IsEncrypted,EntityType) VALUES ('Classification','N','N','Classification for grouping','N',0,'The Classification can be used to optionally group products.',0,'Y',477,54239,'Classification',0,0,12,'N',TO_TIMESTAMP('2008-01-16 21:00:19','YYYY-MM-DD HH24:MI:SS'),'N',10,0,TO_TIMESTAMP('2008-01-16 21:00:19','YYYY-MM-DD HH24:MI:SS'),852,'Y','N','N',0,'N','N','D')
;

-- Jan 16, 2008 9:00:22 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Column_ID=54239 AND EXISTS (SELECT * FROM AD_Column_Trl tt WHERE tt.AD_Language!=l.AD_Language OR tt.AD_Column_ID!=t.AD_Column_ID)
;

-- Jan 16, 2008 9:00:28 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
ALTER TABLE M_DiscountSchemaLine ADD COLUMN Classification VARCHAR(12)
;

-- Jan 16, 2008 9:00:34 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
ALTER TABLE M_DiscountSchemaLine ADD COLUMN Group2 VARCHAR(255)
;

-- Jan 16, 2008 9:00:39 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
ALTER TABLE M_DiscountSchemaLine ADD COLUMN Group1 VARCHAR(255)
;

-- Jan 16, 2008 9:02:42 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Field (IsEncrypted,AD_Org_ID,UpdatedBy,IsDisplayed,IsCentrallyMaintained,IsActive,Created,AD_Client_ID,AD_Field_ID,Description,DisplayLength,AD_Column_ID,IsFieldOnly,CreatedBy,Help,Updated,Name,AD_Tab_ID,IsSameLine,IsHeading,IsReadOnly,EntityType) VALUES ('N',0,0,'Y','Y','Y',TO_TIMESTAMP('2008-01-16 21:02:39','YYYY-MM-DD HH24:MI:SS'),0,54331,'Classification for grouping',12,54239,'N',0,'The Classification can be used to optionally group products.',TO_TIMESTAMP('2008-01-16 21:02:39','YYYY-MM-DD HH24:MI:SS'),'Classification',405,'N','N','N','D')
;

-- Jan 16, 2008 9:02:42 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Field_Trl (AD_Language,AD_Field_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Field_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Field t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Field_ID=54331 AND EXISTS (SELECT * FROM AD_Field_Trl tt WHERE tt.AD_Language!=l.AD_Language OR tt.AD_Field_ID!=t.AD_Field_ID)
;

-- Jan 16, 2008 9:02:45 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Field (IsEncrypted,AD_Org_ID,UpdatedBy,IsDisplayed,IsCentrallyMaintained,IsActive,Created,AD_Client_ID,AD_Field_ID,DisplayLength,AD_Column_ID,IsFieldOnly,CreatedBy,Updated,Name,AD_Tab_ID,IsSameLine,IsHeading,IsReadOnly,EntityType) VALUES ('N',0,0,'Y','Y','Y',TO_TIMESTAMP('2008-01-16 21:02:42','YYYY-MM-DD HH24:MI:SS'),0,54332,255,54237,'N',0,TO_TIMESTAMP('2008-01-16 21:02:42','YYYY-MM-DD HH24:MI:SS'),'Group1',405,'N','N','N','D')
;

-- Jan 16, 2008 9:02:45 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Field_Trl (AD_Language,AD_Field_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Field_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Field t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Field_ID=54332 AND EXISTS (SELECT * FROM AD_Field_Trl tt WHERE tt.AD_Language!=l.AD_Language OR tt.AD_Field_ID!=t.AD_Field_ID)
;

-- Jan 16, 2008 9:02:48 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Field (IsEncrypted,AD_Org_ID,UpdatedBy,IsDisplayed,IsCentrallyMaintained,IsActive,Created,AD_Client_ID,AD_Field_ID,DisplayLength,AD_Column_ID,IsFieldOnly,CreatedBy,Updated,Name,AD_Tab_ID,IsSameLine,IsHeading,IsReadOnly,EntityType) VALUES ('N',0,0,'Y','Y','Y',TO_TIMESTAMP('2008-01-16 21:02:45','YYYY-MM-DD HH24:MI:SS'),0,54333,255,54238,'N',0,TO_TIMESTAMP('2008-01-16 21:02:45','YYYY-MM-DD HH24:MI:SS'),'Group2',405,'N','N','N','D')
;

-- Jan 16, 2008 9:02:48 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
INSERT INTO AD_Field_Trl (AD_Language,AD_Field_ID, Description,Help,Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language,t.AD_Field_ID, t.Description,t.Help,t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Field t WHERE l.IsActive='Y' AND l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N' AND t.AD_Field_ID=54333 AND EXISTS (SELECT * FROM AD_Field_Trl tt WHERE tt.AD_Language!=l.AD_Language OR tt.AD_Field_ID!=t.AD_Field_ID)
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=0,IsDisplayed='N' WHERE AD_Field_ID=5243
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=10,IsDisplayed='Y' WHERE AD_Field_ID=5244
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=20,IsDisplayed='Y' WHERE AD_Field_ID=5245
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=30,IsDisplayed='Y' WHERE AD_Field_ID=5247
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=40,IsDisplayed='Y' WHERE AD_Field_ID=5246
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=50,IsDisplayed='Y' WHERE AD_Field_ID=5248
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=60,IsDisplayed='Y' WHERE AD_Field_ID=8642
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=70,IsDisplayed='Y' WHERE AD_Field_ID=5253
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=80,IsDisplayed='Y' WHERE AD_Field_ID=5250
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=90,IsDisplayed='Y' WHERE AD_Field_ID=5251
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=110,IsDisplayed='Y' WHERE AD_Field_ID=54331
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=120,IsDisplayed='Y' WHERE AD_Field_ID=54332
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=130,IsDisplayed='Y' WHERE AD_Field_ID=54333
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=140,IsDisplayed='Y' WHERE AD_Field_ID=5254
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=150,IsDisplayed='Y' WHERE AD_Field_ID=5258
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=160,IsDisplayed='Y' WHERE AD_Field_ID=5255
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=170,IsDisplayed='Y' WHERE AD_Field_ID=5259
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=180,IsDisplayed='Y' WHERE AD_Field_ID=5256
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=190,IsDisplayed='Y' WHERE AD_Field_ID=5257
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=200,IsDisplayed='Y' WHERE AD_Field_ID=5349
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=210,IsDisplayed='Y' WHERE AD_Field_ID=5260
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=220,IsDisplayed='Y' WHERE AD_Field_ID=5264
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=230,IsDisplayed='Y' WHERE AD_Field_ID=5261
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=240,IsDisplayed='Y' WHERE AD_Field_ID=5265
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=250,IsDisplayed='Y' WHERE AD_Field_ID=5262
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=260,IsDisplayed='Y' WHERE AD_Field_ID=5263
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=270,IsDisplayed='Y' WHERE AD_Field_ID=5350
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=280,IsDisplayed='Y' WHERE AD_Field_ID=5266
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=290,IsDisplayed='Y' WHERE AD_Field_ID=5270
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=300,IsDisplayed='Y' WHERE AD_Field_ID=5267
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=310,IsDisplayed='Y' WHERE AD_Field_ID=5271
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=320,IsDisplayed='Y' WHERE AD_Field_ID=5268
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=330,IsDisplayed='Y' WHERE AD_Field_ID=5269
;

-- Jan 16, 2008 9:04:13 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET SeqNo=340,IsDisplayed='Y' WHERE AD_Field_ID=5348
;

-- Jan 16, 2008 9:04:22 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET IsSameLine='N',Updated=TO_TIMESTAMP('2008-01-16 21:04:22','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=0 WHERE AD_Field_ID=5251
;

-- Jan 16, 2008 9:04:25 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET IsSameLine='Y',Updated=TO_TIMESTAMP('2008-01-16 21:04:25','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=0 WHERE AD_Field_ID=5249
;

-- Jan 16, 2008 9:04:36 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET IsSameLine='N',Updated=TO_TIMESTAMP('2008-01-16 21:04:36','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=0 WHERE AD_Field_ID=5249
;

-- Jan 16, 2008 9:04:42 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET IsSameLine='Y',Updated=TO_TIMESTAMP('2008-01-16 21:04:42','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=0 WHERE AD_Field_ID=54331
;

-- Jan 16, 2008 9:04:45 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET IsSameLine='Y',Updated=TO_TIMESTAMP('2008-01-16 21:04:45','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=0 WHERE AD_Field_ID=54333
;

-- Jan 16, 2008 9:09:32 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET DisplayLength=20,Updated=TO_TIMESTAMP('2008-01-16 21:09:32','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=0 WHERE AD_Field_ID=54332
;

-- Jan 16, 2008 9:09:36 PM CST
-- [ 1871403 ] Adding new field of product into Price List Schema
UPDATE AD_Field SET DisplayLength=20,Updated=TO_TIMESTAMP('2008-01-16 21:09:36','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=0 WHERE AD_Field_ID=54333
;


/*
   Copyright (C) 2003 Commonwealth Scientific and Industrial Research
   Organisation (CSIRO) Australia

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

   - Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.

   - Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

   - Neither the name of CSIRO Australia nor the names of its
   contributors may be used to endorse or promote products derived from
   this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
   PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE ORGANISATION OR
   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
   PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#ifndef CONFIG_H
#define CONFIG_H

#ifdef __WINS__

/* Disable some warnings */

#pragma warning(disable: 4100) /* unreferenced formal parameter */
#pragma warning(disable: 4127) /* conditional expression is constant */
#pragma warning(disable: 4189) /* local variable is initialized but not referenced */
#pragma warning(disable: 4244) /* conversion from '...' to '...', possible loss of data */
#pragma warning(disable: 4305) /* truncation from '...' to '...' */
#pragma warning(disable: 4505) /* unreferenced local function has been removed */
#pragma warning(disable: 4514) /* unreferenced inline function has been removed */
#pragma warning(disable: 4702) /* unreachable code */
#pragma warning(disable: 4701) /* local variable may be be used without having been initialized */
#pragma warning(disable: 4706) /* assignment within conditional expression */
#pragma warning(disable: 4761) /* integral size mismatch in argument: conversion supplied */

#endif

#endif /* ! CONFIG_H */


   1       0 ram0 0 0 0 0 0 0 0 0 0 0 0
   1       1 ram1 0 0 0 0 0 0 0 0 0 0 0
   1       2 ram2 0 0 0 0 0 0 0 0 0 0 0
   1       3 ram3 0 0 0 0 0 0 0 0 0 0 0
   1       4 ram4 0 0 0 0 0 0 0 0 0 0 0
   1       5 ram5 0 0 0 0 0 0 0 0 0 0 0
   1       6 ram6 0 0 0 0 0 0 0 0 0 0 0
   1       7 ram7 0 0 0 0 0 0 0 0 0 0 0
   1       8 ram8 0 0 0 0 0 0 0 0 0 0 0
   1       9 ram9 0 0 0 0 0 0 0 0 0 0 0
   1      10 ram10 0 0 0 0 0 0 0 0 0 0 0
   1      11 ram11 0 0 0 0 0 0 0 0 0 0 0
   1      12 ram12 0 0 0 0 0 0 0 0 0 0 0
   1      13 ram13 0 0 0 0 0 0 0 0 0 0 0
   1      14 ram14 0 0 0 0 0 0 0 0 0 0 0
   1      15 ram15 0 0 0 0 0 0 0 0 0 0 0
   7       0 loop0 0 0 0 0 0 0 0 0 0 0 0
   7       1 loop1 0 0 0 0 0 0 0 0 0 0 0
   7       2 loop2 0 0 0 0 0 0 0 0 0 0 0
   7       3 loop3 0 0 0 0 0 0 0 0 0 0 0
   7       4 loop4 0 0 0 0 0 0 0 0 0 0 0
   7       5 loop5 0 0 0 0 0 0 0 0 0 0 0
   7       6 loop6 0 0 0 0 0 0 0 0 0 0 0
   7       7 loop7 0 0 0 0 0 0 0 0 0 0 0
   2       0 fd0 0 0 0 0 0 0 0 0 0 0 0
  11       0 sr0 0 0 0 0 0 0 0 0 0 0 0
   8       0 sda 19082 3880 738216 7548 24972 23399 2094164 11708 0 5980 19048
   8       1 sda1 614 3840 33050 168 7 1 28 0 0 132 168
   8       2 sda2 2 0 4 0 0 0 0 0 0 0 0
   8       5 sda5 18281 40 703682 7348 24965 23398 2094136 11708 0 5948 18848
 252       0 dm-0 18067 0 701250 7396 48368 0 2094136 21208 0 5940 28604
 252       1 dm-1 224 0 1792 36 0 0 0 0 0 36 36


<?xml version="1.0" encoding="utf-8"?>
<ModMetaData>
  <name>Rimworld Search Agency</name>
  <author>DoctorVanGogh, Killface, meonester</author>
   <supportedVersions>

1.0

1.1

   </supportedVersions>
  <packageId>Storage.Search.RSA</packageId>
  <description>
    This Mod allows you to search by name in various filters:

    + Storage tab
    + Bill tab
    + Outfit tab

    Original A12 version by meonester. Initial update for A17 by Killface.
    Mod menu, rewrites for Harmony and massive improvements by
    DoctorVanGogh

    Includes Hauling Hysteresis by Vendan https://ludeon.com/forums/index.php?topic=26958.0

  </description>
  <modDependenciesByVersion>
      <v1.1>

              <packageId>brrainz.harmony</packageId>
              <displayName>Harmony</displayName>
              <steamWorkshopUrl>steam://url/CommunityFilePage/2009463077</steamWorkshopUrl>
              <downloadUrl>https://github.com/pardeike/HarmonyRimWorld/releases/latest</downloadUrl>

      </v1.1>
  </modDependenciesByVersion>
  <loadAfter>

brrainz.harmony

  </loadAfter>
</ModMetaData>


// HashCalc.cpp

#include "StdAfx.h"

#include "../../../../C/Alloc.h"

#include "../../../Common/StringToInt.h"

#include "../../Common/FileStreams.h"
#include "../../Common/StreamUtils.h"

#include "EnumDirItems.h"
#include "HashCalc.h"

using namespace NWindows;

class CHashMidBuf
{
  void *_data;
public:
  CHashMidBuf(): _data(0) {}
  operator void *() { return _data; }
  bool Alloc(size_t size)
  {
    if (_data != 0)
      return false;
    _data = ::MidAlloc(size);
    return _data != 0;
  }
  ~CHashMidBuf() { ::MidFree(_data); }
};

struct CEnumDirItemCallback_Hash: public IEnumDirItemCallback
{
  IHashCallbackUI *Callback;

  HRESULT ScanProgress(UInt64 numFolders, UInt64 numFiles, UInt64 totalSize, const wchar_t *path, bool isDir)
  {
    return Callback->ScanProgress(numFolders, numFiles, totalSize, path, isDir);
  }
};

static const wchar_t *k_DefaultHashMethod = L"CRC32";

HRESULT CHashBundle::SetMethods(DECL_EXTERNAL_CODECS_LOC_VARS const UStringVector &hashMethods)
{
  UStringVector names = hashMethods;
  if (names.IsEmpty())
    names.Add(k_DefaultHashMethod);

  CRecordVector<CMethodId> ids;
  CObjectVector<COneMethodInfo> methods;

  unsigned i;
  for (i = 0; i < names.Size(); i++)
  {
    COneMethodInfo m;
    RINOK(m.ParseMethodFromString(names[i]));

    if (m.MethodName.IsEmpty())
      m.MethodName = k_DefaultHashMethod;

    if (m.MethodName == L"*")
    {
      CRecordVector<CMethodId> tempMethods;
      GetHashMethods(EXTERNAL_CODECS_LOC_VARS tempMethods);
      methods.Clear();
      ids.Clear();
      FOR_VECTOR (t, tempMethods)
      {
        int index = ids.AddToUniqueSorted(tempMethods[t]);
        if (ids.Size() != methods.Size())
          methods.Insert(index, m);
      }
      break;
    }
    else
    {
      // m.MethodName.RemoveChar(L'-');
      CMethodId id;
      if (!FindHashMethod(EXTERNAL_CODECS_LOC_VARS m.MethodName, id))
        return E_NOTIMPL;
      int index = ids.AddToUniqueSorted(id);
      if (ids.Size() != methods.Size())
        methods.Insert(index, m);
    }
  }

  for (i = 0; i < ids.Size(); i++)
  {
    CMyComPtr<IHasher> hasher;
    UString name;
    RINOK(CreateHasher(EXTERNAL_CODECS_LOC_VARS ids[i], name, hasher));
    if (!hasher)
      throw "Can't create hasher";
    const COneMethodInfo &m = methods[i];
    {
      CMyComPtr<ICompressSetCoderProperties> scp;
      hasher.QueryInterface(IID_ICompressSetCoderProperties, &scp);
      if (scp)
      {
        RINOK(m.SetCoderProps(scp, NULL));
      }
    }
    UInt32 digestSize = hasher->GetDigestSize();
    if (digestSize > k_HashCalc_DigestSize_Max)
      return E_NOTIMPL;
    CHasherState &h = Hashers.AddNew();
    h.Hasher = hasher;
    h.Name = name;
    h.DigestSize = digestSize;
    for (int i = 0; i < k_HashCalc_NumGroups; i++)
      memset(h.Digests[i], 0, digestSize);
  }
  return S_OK;
}

void CHashBundle::InitForNewFile()
{
  CurSize = 0;
  FOR_VECTOR (i, Hashers)
  {
    CHasherState &h = Hashers[i];
    h.Hasher->Init();
    memset(h.Digests[k_HashCalc_Index_Current], 0, h.DigestSize);
  }
}

void CHashBundle::Update(const void *data, UInt32 size)
{
  CurSize += size;
  FOR_VECTOR (i, Hashers)
    Hashers[i].Hasher->Update(data, size);
}

void CHashBundle::SetSize(UInt64 size)
{
  CurSize = size;
}

static void AddDigests(Byte *dest, const Byte *src, UInt32 size)
{
  unsigned next = 0;
  for (UInt32 i = 0; i < size; i++)
  {
    next += (unsigned)dest[i] + (unsigned)src[i];
    dest[i] = (Byte)next;
    next >>= 8;
  }
}

void CHashBundle::Final(bool isDir, bool isAltStream, const UString &path)
{
  if (isDir)
    NumDirs++;
  else if (isAltStream)
  {
    NumAltStreams++;
    AltStreamsSize += CurSize;
  }
  else
  {
    NumFiles++;
    FilesSize += CurSize;
  }

  Byte pre[16];
  memset(pre, 0, sizeof(pre));
  if (isDir)
    pre[0] = 1;

  FOR_VECTOR (i, Hashers)
  {
    CHasherState &h = Hashers[i];
    if (!isDir)
    {
      h.Hasher->Final(h.Digests[0]);
      if (!isAltStream)
        AddDigests(h.Digests[k_HashCalc_Index_DataSum], h.Digests[0], h.DigestSize);
    }

    h.Hasher->Init();
    h.Hasher->Update(pre, sizeof(pre));
    h.Hasher->Update(h.Digests[0], h.DigestSize);

    for (unsigned k = 0; k < path.Len(); k++)
    {
      wchar_t c = path[k];
      Byte temp[2] = { (Byte)(c & 0xFF), (Byte)((c >> 8) & 0xFF) };
      h.Hasher->Update(temp, 2);
    }

    Byte tempDigest[k_HashCalc_DigestSize_Max];
    h.Hasher->Final(tempDigest);
    if (!isAltStream)
      AddDigests(h.Digests[k_HashCalc_Index_NamesSum], tempDigest, h.DigestSize);
    AddDigests(h.Digests[k_HashCalc_Index_StreamsSum], tempDigest, h.DigestSize);
  }
}

HRESULT HashCalc(
    DECL_EXTERNAL_CODECS_LOC_VARS
    const NWildcard::CCensor &censor,
    const CHashOptions &options,
    UString &errorInfo,
    IHashCallbackUI *callback)
{
  CDirItems dirItems;

  UInt64 numErrors = 0;
  UInt64 totalBytes = 0;
  if (options.StdInMode)
  {
    CDirItem di;
    di.Size = (UInt64)(Int64)-1;
    di.Attrib = 0;
    di.MTime.dwLowDateTime = 0;
    di.MTime.dwHighDateTime = 0;
    di.CTime = di.ATime = di.MTime;
    dirItems.Items.Add(di);
  }
  else
  {
    CEnumDirItemCallback_Hash enumCallback;
    enumCallback.Callback = callback;
    RINOK(callback->StartScanning());
    dirItems.ScanAltStreams = options.AltStreamsMode;
    HRESULT res = EnumerateItems(censor,
        options.PathMode,
        UString(),
        dirItems, &enumCallback);
    totalBytes = dirItems.TotalSize;
    FOR_VECTOR (i, dirItems.ErrorPaths)
    {
      RINOK(callback->CanNotFindError(fs2us(dirItems.ErrorPaths[i]), dirItems.ErrorCodes[i]));
    }
    numErrors = dirItems.ErrorPaths.Size();
    if (res != S_OK)
    {
      if (res != E_ABORT)
        errorInfo = L"Scanning error";
      return res;
    }
    RINOK(callback->FinishScanning());
  }

  unsigned i;
  CHashBundle hb;
  RINOK(hb.SetMethods(EXTERNAL_CODECS_LOC_VARS options.Methods));
  hb.Init();
  hb.NumErrors = numErrors;

  if (options.StdInMode)
  {
    RINOK(callback->SetNumFiles(1));
  }
  else
  {
    RINOK(callback->SetTotal(totalBytes));
  }

  const UInt32 kBufSize = 1 << 15;
  CHashMidBuf buf;
  if (!buf.Alloc(kBufSize))
    return E_OUTOFMEMORY;

  UInt64 completeValue = 0;

  RINOK(callback->BeforeFirstFile(hb));

  for (i = 0; i < dirItems.Items.Size(); i++)
  {
    CMyComPtr<ISequentialInStream> inStream;
    UString path;
    bool isDir = false;
    bool isAltStream = false;
    if (options.StdInMode)
    {
      inStream = new CStdInFileStream;
    }
    else
    {
      CInFileStream *inStreamSpec = new CInFileStream;
      inStream = inStreamSpec;
      const CDirItem &dirItem = dirItems.Items[i];
      isDir = dirItem.IsDir();
      isAltStream = dirItem.IsAltStream;
      path = dirItems.GetLogPath(i);
      if (!isDir)
      {
        UString phyPath = dirItems.GetPhyPath(i);
        if (!inStreamSpec->OpenShared(us2fs(phyPath), options.OpenShareForWrite))
        {
          HRESULT res = callback->OpenFileError(phyPath, ::GetLastError());
          hb.NumErrors++;
          if (res != S_FALSE)
            return res;
          continue;
        }
      }
    }
    RINOK(callback->GetStream(path, isDir));
    UInt64 fileSize = 0;

    hb.InitForNewFile();
    if (!isDir)
    {
      for (UInt32 step = 0;; step++)
      {
        if ((step & 0xFF) == 0)
          RINOK(callback->SetCompleted(&completeValue));
        UInt32 size;
        RINOK(inStream->Read(buf, kBufSize, &size));
        if (size == 0)
          break;
        hb.Update(buf, size);
        fileSize += size;
        completeValue += size;
      }
    }
    hb.Final(isDir, isAltStream, path);
    RINOK(callback->SetOperationResult(fileSize, hb, !isDir));
    RINOK(callback->SetCompleted(&completeValue));
  }
  return callback->AfterLastFile(hb);
}

static inline char GetHex(Byte value)
{
  return (char)((value < 10) ? ('0' + value) : ('A' + (value - 10)));
}

void AddHashHexToString(char *dest, const Byte *data, UInt32 size)
{
  dest[size * 2] = 0;
  if (!data)
  {
    for (UInt32 i = 0; i < size; i++)
    {
      dest[0] = ' ';
      dest[1] = ' ';
      dest += 2;
    }
    return;
  }
  int step = 2;
  if (size <= 8)
  {
    step = -2;
    dest += size * 2 - 2;
  }
  for (UInt32 i = 0; i < size; i++)
  {
    Byte b = data[i];
    dest[0] = GetHex((Byte)((b >> 4) & 0xF));
    dest[1] = GetHex((Byte)(b & 0xF));
    dest += step;
  }
}


/*!
 * Bootstrap-select v1.12.2 (http://silviomoreto.github.io/bootstrap-select)
 *
 * Copyright 2013-2017 bootstrap-select
 * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE)
 */

(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module unless amdModuleId is set
    define(["jquery"], function (a0) {
      return (factory(a0));
    });
  } else if (typeof module === 'object' && module.exports) {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory(require("jquery"));
  } else {
    factory(root["jQuery"]);
  }
}(this, function (jQuery) {

(function ($) {
  $.fn.selectpicker.defaults = {
    noneSelectedText: 'Vyberte zo zoznamu',
    noneResultsText: 'Pre výraz {0} neboli nájdené žiadne výsledky',
    countSelectedText: 'Vybrané {0} z {1}',
    maxOptionsText: ['Limit prekročený ({n} {var} max)', 'Limit skupiny prekročený ({n} {var} max)', ['položiek', 'položka']],
    selectAllText: 'Vybrať všetky',
    deselectAllText: 'Zrušiť výber',
    multipleSeparator: ', '
  };
})(jQuery);

}));


# makefile for libpng on Solaris 2.x with cc
# Contributed by William L. Sebok, based on makefile.linux
# Copyright (C) 2020 Cosmin Truta
# Copyright (C) 2002, 2006, 2010-2014 Glenn Randers-Pehrson
# Copyright (C) 1998 Greg Roelofs
# Copyright (C) 1996, 1997 Andreas Dilger

# This code is released under the libpng license.
# For conditions of distribution and use, see the disclaimer
# and license in png.h

# Library name:
LIBNAME=libpng16
PNGMAJ = 16

# Shared library names:
LIBSO=$(LIBNAME).so
LIBSOMAJ=$(LIBNAME).so.$(PNGMAJ)
LIBSOREL=$(LIBSOMAJ).$(RELEASE)
OLDSO=libpng.so

# Utilities:
CC=cc
AR_RC=ar rc
MKDIR_P=mkdir -p
LN_SF=ln -f -s
RANLIB=echo
RM_F=/bin/rm -f

SUN_CC_FLAGS=-fast -xtarget=ultra
SUN_LD_FLAGS=-fast -xtarget=ultra

# where make install puts libpng.a, libpng16.so and libpng16/png.h
prefix=/a
exec_prefix=$(prefix)

# Where the zlib library and include files are located
# Changing these to ../zlib poses a security risk.  If you want
# to have zlib in an adjacent directory, specify the full path instead of "..".
#ZLIBLIB=../zlib
#ZLIBINC=../zlib

ZLIBLIB=/usr/lib
ZLIBINC=/usr/include

WARNMORE=-Wwrite-strings -Wpointer-arith -Wshadow \
	-Wmissing-declarations -Wtraditional -Wcast-align \
	-Wstrict-prototypes -Wmissing-prototypes #-Wconversion
CPPFLAGS=-I$(ZLIBINC) # -DPNG_DEBUG=5
CFLAGS=$(SUN_CC_FLAGS) # $(WARNMORE) -g
LDFLAGS=$(SUN_LD_FLAGS) -L$(ZLIBLIB) -R$(ZLIBLIB) libpng.a -lz -lm

INCPATH=$(prefix)/include
LIBPATH=$(exec_prefix)/lib
MANPATH=$(prefix)/man
BINPATH=$(exec_prefix)/bin

# override DESTDIR= on the make install command line to easily support
# installing into a temporary location.  Example:
#
#    make install DESTDIR=/tmp/build/libpng
#
# If you're going to install into a temporary location
# via DESTDIR, $(DESTDIR)$(prefix) must already exist before
# you execute make install.
DESTDIR=

DB=$(DESTDIR)$(BINPATH)
DI=$(DESTDIR)$(INCPATH)
DL=$(DESTDIR)$(LIBPATH)
DM=$(DESTDIR)$(MANPATH)

OBJS = png.o pngerror.o pngget.o pngmem.o pngpread.o \
       pngread.o pngrio.o pngrtran.o pngrutil.o pngset.o \
       pngtrans.o pngwio.o pngwrite.o pngwtran.o pngwutil.o

OBJSDLL = $(OBJS:.o=.pic.o)

.SUFFIXES:      .c .o .pic.o

.c.o:
	$(CC) -c $(CPPFLAGS) $(CFLAGS) -o $@ $<

.c.pic.o:
	$(CC) -c $(CPPFLAGS) $(CFLAGS) -KPIC -o $@ $*.c

all: libpng.a $(LIBSO) pngtest libpng.pc libpng-config

include scripts/pnglibconf.mak
DELETE = $(RM_F)
DFNFLAGS = $(DEFS) $(CPPFLAGS)

libpng.a: $(OBJS)
	$(AR_RC) $@ $(OBJS)
	$(RANLIB) $@

libpng.pc:
	cat scripts/libpng.pc.in | sed -e s!@prefix@!$(prefix)! \
	-e s!@exec_prefix@!$(exec_prefix)! \
	-e s!@libdir@!$(LIBPATH)! \
	-e s!@includedir@!$(INCPATH)! \
	-e s!-lpng16!-lpng16\ -lz\ -lm! > libpng.pc

libpng-config:
	( cat scripts/libpng-config-head.in; \
	echo prefix=\"$(prefix)\"; \
	echo libdir=\"$(LIBPATH)\"; \
	echo I_opts=\"-I$(INCPATH)/$(LIBNAME)\"; \
	echo L_opts=\"-L$(LIBPATH)\"; \
	echo R_opts=\"-R$(LIBPATH)\"; \
	echo ccopts=\"-fast -xtarget=ultra\"; \
	echo ldopts=\"-fast -xtarget=ultra\"; \
	echo libs=\"-lpng16 -lz -lm\"; \
	cat scripts/libpng-config-body.in ) > libpng-config
	chmod +x libpng-config

$(LIBSO): $(LIBSOMAJ)
	$(LN_SF) $(LIBSOMAJ) $(LIBSO)

$(LIBSOMAJ): $(OBJSDLL)
	@case "`type ld`" in *ucb*) \
	echo; \
	echo '## WARNING:'; \
	echo '## The commands "CC" and "LD" must NOT refer to /usr/ucb/cc'; \
	echo '## and /usr/ucb/ld.  If they do, you need to adjust your PATH'; \
	echo '## environment variable to put /usr/ccs/bin ahead of /usr/ucb.'; \
	echo '## The environment variable LD_LIBRARY_PATH should not be set'; \
	echo '## at all.  If it is, things are likely to break because of'; \
	echo '## the libucb dependency that is created.'; \
	echo; \
	;; \
	esac
	$(LD) -G -L$(ZLIBLIB) -R$(ZLIBLIB) -h $(LIBSOMAJ) \
	 -o $(LIBSOMAJ) $(OBJSDLL)

pngtest: pngtest.o $(LIBSO)
	$(CC) -o pngtest $(CFLAGS) pngtest.o $(LDFLAGS)

test: pngtest
	./pngtest

install-headers: png.h pngconf.h pnglibconf.h
	-@if [ ! -d $(DI) ]; then $(MKDIR_P) $(DI); fi
	-@if [ ! -d $(DI)/$(LIBNAME) ]; then $(MKDIR_P) $(DI)/$(LIBNAME); fi
	cp png.h pngconf.h pnglibconf.h $(DI)/$(LIBNAME)
	chmod 644 $(DI)/$(LIBNAME)/png.h $(DI)/$(LIBNAME)/pngconf.h $(DI)/$(LIBNAME)/pnglibconf.h
	-@$(RM_F) $(DI)/png.h $(DI)/pngconf.h $(DI)/pnglibconf.h
	-@$(RM_F) $(DI)/libpng
	(cd $(DI); $(LN_SF) $(LIBNAME) libpng; $(LN_SF) $(LIBNAME)/* .)

install-static: install-headers libpng.a
	-@if [ ! -d $(DL) ]; then $(MKDIR_P) $(DL); fi
	cp libpng.a $(DL)/$(LIBNAME).a
	chmod 644 $(DL)/$(LIBNAME).a
	-@$(RM_F) $(DL)/libpng.a
	(cd $(DL); $(LN_SF) $(LIBNAME).a libpng.a)

install-shared: install-headers $(LIBSOMAJ) libpng.pc
	-@if [ ! -d $(DL) ]; then $(MKDIR_P) $(DL); fi
	-@$(RM_F) $(DL)/$(LIBSO)
	-@$(RM_F) $(DL)/$(LIBSOREL)
	-@$(RM_F) $(DL)/$(OLDSO)
	cp $(LIBSOMAJ) $(DL)/$(LIBSOREL)
	chmod 755 $(DL)/$(LIBSOREL)
	(cd $(DL); \
	$(LN_SF) $(LIBSOREL) $(LIBSO); \
	$(LN_SF) $(LIBSO) $(OLDSO))
	-@if [ ! -d $(DL)/pkgconfig ]; then $(MKDIR_P) $(DL)/pkgconfig; fi
	-@$(RM_F) $(DL)/pkgconfig/$(LIBNAME).pc
	-@$(RM_F) $(DL)/pkgconfig/libpng.pc
	cp libpng.pc $(DL)/pkgconfig/$(LIBNAME).pc
	chmod 644 $(DL)/pkgconfig/$(LIBNAME).pc
	(cd $(DL)/pkgconfig; $(LN_SF) $(LIBNAME).pc libpng.pc)

install-man: libpng.3 libpngpf.3 png.5
	-@if [ ! -d $(DM) ]; then $(MKDIR_P) $(DM); fi
	-@if [ ! -d $(DM)/man3 ]; then $(MKDIR_P) $(DM)/man3; fi
	-@$(RM_F) $(DM)/man3/libpng.3
	-@$(RM_F) $(DM)/man3/libpngpf.3
	cp libpng.3 $(DM)/man3
	cp libpngpf.3 $(DM)/man3
	-@if [ ! -d $(DM)/man5 ]; then $(MKDIR_P) $(DM)/man5; fi
	-@$(RM_F) $(DM)/man5/png.5
	cp png.5 $(DM)/man5

install-config: libpng-config
	-@if [ ! -d $(DB) ]; then $(MKDIR_P) $(DB); fi
	-@$(RM_F) $(DB)/libpng-config
	-@$(RM_F) $(DB)/$(LIBNAME)-config
	cp libpng-config $(DB)/$(LIBNAME)-config
	chmod 755 $(DB)/$(LIBNAME)-config
	(cd $(DB); $(LN_SF) $(LIBNAME)-config libpng-config)

install: install-static install-shared install-man install-config

# If you installed in $(DESTDIR), test-installed won't work until you
# move the library to its final location.  Use test-dd to test it
# before then.

test-dd:
	echo
	echo Testing installed dynamic shared library in $(DL).
	$(CC) $(SUN_CC_FLAGS) -I$(DI) $(CPPFLAGS) \
	   `$(BINPATH)/$(LIBNAME)-config --cflags` pngtest.c \
	   -o pngtestd -L$(DL) -R$(DL) `$(BINPATH)/$(LIBNAME)-config --ldflags` \
	   $(SUN_LD_FLAGS) -L$(ZLIBLIB) -R$(ZLIBLIB)
	./pngtestd pngtest.png

test-installed:
	echo
	echo Testing installed dynamic shared library.
	$(CC) $(SUN_CC_FLAGS) $(CPPFLAGS) \
	   `$(BINPATH)/$(LIBNAME)-config --cflags` pngtest.c \
	   -o pngtesti `$(BINPATH)/$(LIBNAME)-config --ldflags` \
	   $(SUN_LD_FLAGS) -L$(ZLIBLIB) -R$(ZLIBLIB)
	./pngtesti pngtest.png

clean:
	$(RM_F) *.o libpng.a pngtest pngtesti pngout.png \
	libpng-config $(LIBSO) $(LIBSOMAJ)* \
	libpng.pc

# DO NOT DELETE THIS LINE -- make depend depends on it.

png.o      png.pic.o:      png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngerror.o pngerror.pic.o: png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngget.o   pngget.pic.o:   png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngmem.o   pngmem.pic.o:   png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngpread.o pngpread.pic.o: png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngread.o  pngread.pic.o:  png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngrio.o   pngrio.pic.o:   png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngrtran.o pngrtran.pic.o: png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngrutil.o pngrutil.pic.o: png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngset.o   pngset.pic.o:   png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngtrans.o pngtrans.pic.o: png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngwio.o   pngwio.pic.o:   png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngwrite.o pngwrite.pic.o: png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngwtran.o pngwtran.pic.o: png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h
pngwutil.o pngwutil.pic.o: png.h pngconf.h pnglibconf.h pngpriv.h pngstruct.h pnginfo.h pngdebug.h

pngtest.o: png.h pngconf.h pnglibconf.h


#!/usr/bin/env python
# Copyright (c) 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""
This utility takes a JSON input that describes a CRLSet and produces a
CRLSet from it.

The input is taken on stdin and is a dict with the following keys:
  - BlockedBySPKI: An array of strings, where each string is a filename
      containing a PEM certificate, from which an SPKI will be extracted.
  - BlockedByHash: A dict of string to an array of ints, where the string is
      a filename containing a PEM format certificate, and the ints are the
      serial numbers. The listed serial numbers will be blocked when issued by
      the given certificate.

For example:

{
  "BlockedBySPKI": ["/tmp/blocked-certificate"],
  "BlockedByHash": {
    "/tmp/intermediate-certificate": [1, 2, 3]
  }
}
"""

import hashlib
import json
import optparse
import struct
import sys

def _pem_cert_to_binary(pem_filename):
  """Decodes the first PEM-encoded certificate in a given file into binary

  Args:
    pem_filename: A filename that contains a PEM-encoded certificate. It may
        contain additional data (keys, textual representation) which will be
        ignored

  Returns:
    A byte array containing the decoded certificate data
  """
  base64 = ""
  started = False

  with open(pem_filename, 'r') as pem_file:
    for line in pem_file:
      if not started:
        if line.startswith('-----BEGIN CERTIFICATE'):
          started = True
      else:
        if line.startswith('-----END CERTIFICATE'):
          break
        base64 += line[:-1].strip()

  return base64.decode('base64')

def _parse_asn1_element(der_bytes):
  """Parses a DER-encoded tag/Length/Value into its component parts

  Args:
    der_bytes: A DER-encoded ASN.1 data type

  Returns:
    A tuple of the ASN.1 tag value, the length of the ASN.1 header that was
    read, the sequence of bytes for the value, and then any data from der_bytes
    that was not part of the tag/Length/Value.
  """
  tag = ord(der_bytes[0])
  length = ord(der_bytes[1])
  header_length = 2

  if length & 0x80:
    num_length_bytes = length & 0x7f
    length = 0
    for i in xrange(2, 2 + num_length_bytes):
      length <<= 8
      length += ord(der_bytes[i])
    header_length = 2 + num_length_bytes

  contents = der_bytes[:header_length + length]
  rest = der_bytes[header_length + length:]

  return (tag, header_length, contents, rest)

class ASN1Iterator(object):
  """Iterator that parses and iterates through a ASN.1 DER structure"""

  def __init__(self, contents):
    self._tag = 0
    self._header_length = 0
    self._rest = None
    self._contents = contents
    self.step_into()

  def step_into(self):
    """Begins processing the inner contents of the next ASN.1 element"""
    (self._tag, self._header_length, self._contents, self._rest) = (
        _parse_asn1_element(self._contents[self._header_length:]))

  def step_over(self):
    """Skips/ignores the next ASN.1 element"""
    (self._tag, self._header_length, self._contents, self._rest) = (
        _parse_asn1_element(self._rest))

  def tag(self):
    """Returns the ASN.1 tag of the current element"""
    return self._tag

  def contents(self):
    """Returns the raw data of the current element"""
    return self._contents

def _der_cert_to_spki(der_bytes):
  """Returns the subjectPublicKeyInfo of a DER-encoded certificate

  Args:
    der_bytes: A DER-encoded certificate (RFC 5280)

  Returns:
    A byte array containing the subjectPublicKeyInfo
  """
  iterator = ASN1Iterator(der_bytes)
  iterator.step_into()  # enter certificate structure
  iterator.step_into()  # enter TBSCertificate
  iterator.step_over()  # over version
  iterator.step_over()  # over serial
  iterator.step_over()  # over signature algorithm
  iterator.step_over()  # over issuer name
  iterator.step_over()  # over validity
  iterator.step_over()  # over subject name
  return iterator.contents()

def pem_cert_file_to_spki_hash(pem_filename):
  """Gets the SHA-256 hash of the subjectPublicKeyInfo of a cert in a file

  Args:
    pem_filename: A file containing a PEM-encoded certificate.

  Returns:
    The SHA-256 hash of the first certificate in the file, as a byte sequence
  """
  return hashlib.sha256(
    _der_cert_to_spki(_pem_cert_to_binary(pem_filename))).digest()

def main():
  parser = optparse.OptionParser(description=sys.modules[__name__].__doc__)
  parser.add_option('-o', '--output',
                    help='Specifies the output file. The default is stdout.')
  options, _ = parser.parse_args()
  outfile = sys.stdout
  if options.output and options.output != '-':
    outfile = open(options.output, 'wb')

  config = json.load(sys.stdin)
  blocked_spkis = [
      pem_cert_file_to_spki_hash(pem_file).encode('base64').strip()
      for pem_file in config.get('BlockedBySPKI', [])]
  parents = {
    pem_cert_file_to_spki_hash(pem_file): serials
    for pem_file, serials in config.get('BlockedByHash', {}).iteritems()
  }
  header_json = {
      'Version': 0,
      'ContentType': 'CRLSet',
      'Sequence': 0,
      'DeltaFrom': 0,
      'NumParents': len(parents),
      'BlockedSPKIs': blocked_spkis,
  }
  header = json.dumps(header_json)
  outfile.write(struct.pack('<H', len(header)))
  outfile.write(header)
  for spki, serials in sorted(parents.iteritems()):
    outfile.write(spki)
    outfile.write(struct.pack('<I', len(serials)))
    for serial in serials:
      raw_serial = []
      if not serial:
        raw_serial = ['\x00']
      else:
        while serial:
          raw_serial.insert(0, chr(serial & 0xff))
          serial >>= 8

    outfile.write(struct.pack('<B', len(raw_serial)))
    outfile.write(''.join(raw_serial))
  return 0

if __name__ == '__main__':
  sys.exit(main())


package course.examples.ui.webview

import android.app.Activity
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.webkit.WebView
import android.webkit.WebViewClient

class WebViewActivity : Activity() {

    companion object {
        private const val TAG = "HelloWebViewClient"
    }

    private lateinit var mWebView: WebView

    public override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.main)

        mWebView = findViewById(R.id.webview)

        // Set a kind of listener on the WebView so the WebView can intercept
        // URL loading requests if it wants to
        mWebView.webViewClient = HelloWebViewClient()

        // Add Zoom controls to WebView
        mWebView.settings.builtInZoomControls = true

        mWebView.loadUrl("https://www.cs.umd.edu/~aporter/Tmp/bee.html")
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack()
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private inner class HelloWebViewClient : WebViewClient() {

        // Give application a chance to catch additional URL loading requests
        override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
            Log.i(TAG, "About to load:$url")
            view.loadUrl(url)
            return true
        }
    }

}


<?php

/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

declare(strict_types=1);

namespace spec\Sylius\Bundle\ApiBundle\CommandHandler\Checkout;

use Doctrine\Common\Collections\ArrayCollection;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use SM\Factory\FactoryInterface;
use SM\StateMachine\StateMachineInterface;
use Sylius\Bundle\ApiBundle\Command\Checkout\ChooseShippingMethod;
use Sylius\Component\Core\Model\OrderInterface;
use Sylius\Component\Core\Model\ShipmentInterface;
use Sylius\Component\Core\Model\ShippingMethodInterface;
use Sylius\Component\Core\OrderCheckoutTransitions;
use Sylius\Component\Core\Repository\OrderRepositoryInterface;
use Sylius\Component\Core\Repository\ShipmentRepositoryInterface;
use Sylius\Component\Core\Repository\ShippingMethodRepositoryInterface;
use Sylius\Component\Shipping\Checker\ShippingMethodEligibilityCheckerInterface;

final class ChooseShippingMethodHandlerSpec extends ObjectBehavior
{
    function let(
        OrderRepositoryInterface $orderRepository,
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        ShipmentRepositoryInterface $shipmentRepository,
        ShippingMethodEligibilityCheckerInterface $eligibilityChecker,
        FactoryInterface $stateMachineFactory
    ): void {
        $this->beConstructedWith(
            $orderRepository,
            $shippingMethodRepository,
            $shipmentRepository,
            $eligibilityChecker,
            $stateMachineFactory
        );
    }

    function it_assigns_choosen_shipping_method_to_specified_shipment(
        OrderRepositoryInterface $orderRepository,
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        ShipmentRepositoryInterface $shipmentRepository,
        ShippingMethodEligibilityCheckerInterface $eligibilityChecker,
        FactoryInterface $stateMachineFactory,
        OrderInterface $cart,
        ShippingMethodInterface $shippingMethod,
        ShipmentInterface $shipment,
        StateMachineInterface $stateMachine
    ): void {
        $chooseShippingMethod = new ChooseShippingMethod('DHL_SHIPPING_METHOD');
        $chooseShippingMethod->setOrderTokenValue('ORDERTOKEN');
        $chooseShippingMethod->setSubresourceId('123');

        $orderRepository->findOneBy(['tokenValue' => 'ORDERTOKEN'])->willReturn($cart);

        $stateMachineFactory->get($cart, OrderCheckoutTransitions::GRAPH)->willReturn($stateMachine);
        $stateMachine->can('select_shipping')->willReturn(true);

        $shippingMethodRepository->findOneBy(['code' => 'DHL_SHIPPING_METHOD'])->willReturn($shippingMethod);

        $cart->getShipments()->willReturn(new ArrayCollection([$shipment->getWrappedObject()]));

        $cart->getId()->willReturn('111');

        $shipmentRepository->findOneByOrderId('123', '111')->willReturn($shipment);

        $eligibilityChecker->isEligible($shipment, $shippingMethod)->willReturn(true);

        $shipment->setMethod($shippingMethod)->shouldBeCalled();
        $stateMachine->apply('select_shipping')->shouldBeCalled();

        $this($chooseShippingMethod)->shouldReturn($cart);
    }

    function it_throws_an_exception_if_shipping_method_is_not_eligible(
        OrderRepositoryInterface $orderRepository,
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        ShipmentRepositoryInterface $shipmentRepository,
        ShippingMethodEligibilityCheckerInterface $eligibilityChecker,
        FactoryInterface $stateMachineFactory,
        OrderInterface $cart,
        ShippingMethodInterface $shippingMethod,
        ShipmentInterface $shipment,
        StateMachineInterface $stateMachine
    ): void {
        $chooseShippingMethod = new ChooseShippingMethod('DHL_SHIPPING_METHOD');
        $chooseShippingMethod->setOrderTokenValue('ORDERTOKEN');
        $chooseShippingMethod->setSubresourceId('123');

        $orderRepository->findOneBy(['tokenValue' => 'ORDERTOKEN'])->willReturn($cart);

        $stateMachineFactory->get($cart, OrderCheckoutTransitions::GRAPH)->willReturn($stateMachine);
        $stateMachine->can('select_shipping')->willReturn(true);

        $shippingMethodRepository->findOneBy(['code' => 'DHL_SHIPPING_METHOD'])->willReturn($shippingMethod);

        $cart->getShipments()->willReturn(new ArrayCollection([$shipment->getWrappedObject()]));

        $cart->getId()->willReturn('111');

        $shipmentRepository->findOneByOrderId('123', '111')->willReturn($shipment);

        $eligibilityChecker->isEligible($shipment, $shippingMethod)->willReturn(false);

        $shipment->setMethod(Argument::type(ShippingMethodInterface::class))->shouldNotBeCalled();
        $stateMachine->apply('select_shipping')->shouldNotBeCalled();

        $this
            ->shouldThrow(\InvalidArgumentException::class)
            ->during('__invoke', [$chooseShippingMethod])
        ;
    }

    function it_throws_an_exception_if_order_with_given_token_has_not_been_found(
        OrderRepositoryInterface $orderRepository,
        ShipmentInterface $shipment
    ): void {
        $chooseShippingMethod = new ChooseShippingMethod('DHL_SHIPPING_METHOD');
        $chooseShippingMethod->setOrderTokenValue('ORDERTOKEN');

        $orderRepository->findOneBy(['tokenValue' => 'ORDERTOKEN'])->willReturn(null);

        $shipment->setMethod(Argument::type(ShippingMethodInterface::class))->shouldNotBeCalled();

        $this
            ->shouldThrow(\InvalidArgumentException::class)
            ->during('__invoke', [$chooseShippingMethod])
        ;
    }

    function it_throws_an_exception_if_order_cannot_have_shipping_selected(
        OrderRepositoryInterface $orderRepository,
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        FactoryInterface $stateMachineFactory,
        OrderInterface $cart,
        StateMachineInterface $stateMachine,
        ShipmentInterface $shipment
    ): void {
        $chooseShippingMethod = new ChooseShippingMethod('DHL_SHIPPING_METHOD');
        $chooseShippingMethod->setOrderTokenValue('ORDERTOKEN');

        $orderRepository->findOneBy(['tokenValue' => 'ORDERTOKEN'])->willReturn($cart);
        $shippingMethodRepository->findOneBy(['code' => 'DHL_SHIPPING_METHOD'])->willReturn(null);
        $stateMachineFactory->get($cart, OrderCheckoutTransitions::GRAPH)->willReturn($stateMachine);
        $stateMachine->can('select_shipping')->willReturn(false);

        $shipment->setMethod(Argument::type(ShippingMethodInterface::class))->shouldNotBeCalled();
        $stateMachine->apply('select_shipping')->shouldNotBeCalled();

        $this
            ->shouldThrow(\InvalidArgumentException::class)
            ->during('__invoke', [$chooseShippingMethod])
        ;
    }

    function it_throws_an_exception_if_shipping_method_with_given_code_has_not_been_found(
        OrderRepositoryInterface $orderRepository,
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        FactoryInterface $stateMachineFactory,
        OrderInterface $cart,
        StateMachineInterface $stateMachine,
        ShipmentInterface $shipment
    ): void {
        $chooseShippingMethod = new ChooseShippingMethod('DHL_SHIPPING_METHOD');
        $chooseShippingMethod->setOrderTokenValue('ORDERTOKEN');
        $chooseShippingMethod->setSubresourceId('123');

        $orderRepository->findOneBy(['tokenValue' => 'ORDERTOKEN'])->willReturn($cart);

        $stateMachineFactory->get($cart, OrderCheckoutTransitions::GRAPH)->willReturn($stateMachine);
        $stateMachine->can('select_shipping')->willReturn(true);

        $shippingMethodRepository->findOneBy(['code' => 'DHL_SHIPPING_METHOD'])->willReturn(null);

        $shipment->setMethod(Argument::type(ShippingMethodInterface::class))->shouldNotBeCalled();
        $stateMachine->apply('select_shipping')->shouldNotBeCalled();

        $this
            ->shouldThrow(\InvalidArgumentException::class)
            ->during('__invoke', [$chooseShippingMethod])
        ;
    }

    function it_throws_an_exception_if_ordered_shipment_has_not_been_found(
        OrderRepositoryInterface $orderRepository,
        ShippingMethodRepositoryInterface $shippingMethodRepository,
        ShipmentRepositoryInterface $shipmentRepository,
        FactoryInterface $stateMachineFactory,
        OrderInterface $cart,
        ShippingMethodInterface $shippingMethod,
        StateMachineInterface $stateMachine
    ): void {
        $chooseShippingMethod = new ChooseShippingMethod('DHL_SHIPPING_METHOD');
        $chooseShippingMethod->setOrderTokenValue('ORDERTOKEN');
        $chooseShippingMethod->setSubresourceId('123');

        $orderRepository->findOneBy(['tokenValue' => 'ORDERTOKEN'])->willReturn($cart);

        $stateMachineFactory->get($cart, OrderCheckoutTransitions::GRAPH)->willReturn($stateMachine);
        $stateMachine->can('select_shipping')->willReturn(true);

        $shippingMethodRepository->findOneBy(['code' => 'DHL_SHIPPING_METHOD'])->willReturn($shippingMethod);

        $cart->getId()->willReturn('111');

        $shipmentRepository->findOneByOrderId('123', '111')->willReturn(null);

        $stateMachine->apply('select_shipping')->shouldNotBeCalled();

        $this
            ->shouldThrow(\InvalidArgumentException::class)
            ->during('__invoke', [$chooseShippingMethod])
        ;
    }
}


@lrnwebcomponents/paper-fab-transitions

Automated conversion of paper-fab-transitions/

wct --configFile ../../wct.conf.json node_modules/@lrnwebcomponents/paper-fab-transitions/test/

gulp --gulpfile=gulpfile.cjs && rollup -c && prettier --ignore-path ../../.prettierignore --write "**/*.{js,json}" && wca analyze "**/*.js" --format vscode --outFile vscode-html-custom-data.json

concurrently --kill-others "yarn run watch" "yarn run serve"


// !$*UTF8*$!
{
	archiveVersion = 1;
	classes = {
	};
	objectVersion = 45;
	objects = {

/* Begin PBXBuildFile section */
		351C459816A6A9290030794D /* Note_Prefix.pch in Headers */ = {isa = PBXBuildFile; fileRef = 351C459716A6A9290030794D /* Note_Prefix.pch */; };
		AACBBE4A0F95108600F1A2B1 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = AACBBE490F95108600F1A2B1 /* Foundation.framework */; };
		C2942B5F16A6551A00359A14 /* Note.h in Headers */ = {isa = PBXBuildFile; fileRef = C2942B5D16A6551A00359A14 /* Note.h */; };
		C2942B6016A6551A00359A14 /* Note.m in Sources */ = {isa = PBXBuildFile; fileRef = C2942B5E16A6551A00359A14 /* Note.m */; };
		C2942B7516A655DB00359A14 /* NoteProtocolConverter.h in Headers */ = {isa = PBXBuildFile; fileRef = C2942B7316A655DB00359A14 /* NoteProtocolConverter.h */; };
		C2942B7616A655DB00359A14 /* NoteProtocolConverter.m in Sources */ = {isa = PBXBuildFile; fileRef = C2942B7416A655DB00359A14 /* NoteProtocolConverter.m */; };
/* End PBXBuildFile section */

/* Begin PBXFileReference section */
		351C459716A6A9290030794D /* Note_Prefix.pch */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Note_Prefix.pch; sourceTree = "<group>"; };
		AACBBE490F95108600F1A2B1 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
		C2942B5D16A6551A00359A14 /* Note.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Note.h; sourceTree = "<group>"; };
		C2942B5E16A6551A00359A14 /* Note.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Note.m; sourceTree = "<group>"; };
		C2942B7316A655DB00359A14 /* NoteProtocolConverter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NoteProtocolConverter.h; sourceTree = "<group>"; };
		C2942B7416A655DB00359A14 /* NoteProtocolConverter.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = NoteProtocolConverter.m; sourceTree = "<group>"; };
		D2AAC07E0554694100DB518D /* libNote.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libNote.a; sourceTree = BUILT_PRODUCTS_DIR; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
		D2AAC07C0554694100DB518D /* Frameworks */ = {
			isa = PBXFrameworksBuildPhase;
			buildActionMask = 2147483647;
			files = (
				AACBBE4A0F95108600F1A2B1 /* Foundation.framework in Frameworks */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXFrameworksBuildPhase section */

/* Begin PBXGroup section */
		034768DFFF38A50411DB9C8B /* Products */ = {
			isa = PBXGroup;
			children = (
				D2AAC07E0554694100DB518D /* libNote.a */,
			);
			name = Products;
			sourceTree = "<group>";
		};
		0867D691FE84028FC02AAC07 /* SendNote */ = {
			isa = PBXGroup;
			children = (
				08FB77AEFE84172EC02AAC07 /* Classes */,
				32C88DFF0371C24200C91783 /* Other Sources */,
				0867D69AFE84028FC02AAC07 /* Frameworks */,
				034768DFFF38A50411DB9C8B /* Products */,
			);
			name = SendNote;
			sourceTree = "<group>";
		};
		0867D69AFE84028FC02AAC07 /* Frameworks */ = {
			isa = PBXGroup;
			children = (
				AACBBE490F95108600F1A2B1 /* Foundation.framework */,
			);
			name = Frameworks;
			sourceTree = "<group>";
		};
		08FB77AEFE84172EC02AAC07 /* Classes */ = {
			isa = PBXGroup;
			children = (
				C2942B5D16A6551A00359A14 /* Note.h */,
				C2942B5E16A6551A00359A14 /* Note.m */,
				C2942B7316A655DB00359A14 /* NoteProtocolConverter.h */,
				C2942B7416A655DB00359A14 /* NoteProtocolConverter.m */,
			);
			name = Classes;
			sourceTree = "<group>";
		};
		32C88DFF0371C24200C91783 /* Other Sources */ = {
			isa = PBXGroup;
			children = (
				351C459716A6A9290030794D /* Note_Prefix.pch */,
			);
			name = "Other Sources";
			sourceTree = "<group>";
		};
/* End PBXGroup section */

/* Begin PBXHeadersBuildPhase section */
		D2AAC07A0554694100DB518D /* Headers */ = {
			isa = PBXHeadersBuildPhase;
			buildActionMask = 2147483647;
			files = (
				C2942B5F16A6551A00359A14 /* Note.h in Headers */,
				C2942B7516A655DB00359A14 /* NoteProtocolConverter.h in Headers */,
				351C459816A6A9290030794D /* Note_Prefix.pch in Headers */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXHeadersBuildPhase section */

/* Begin PBXNativeTarget section */
		D2AAC07D0554694100DB518D /* Note */ = {
			isa = PBXNativeTarget;
			buildConfigurationList = 1DEB921E08733DC00010E9CD /* Build configuration list for PBXNativeTarget "Note" */;
			buildPhases = (
				D2AAC07A0554694100DB518D /* Headers */,
				D2AAC07B0554694100DB518D /* Sources */,
				D2AAC07C0554694100DB518D /* Frameworks */,
			);
			buildRules = (
			);
			dependencies = (
			);
			name = Note;
			productName = SendNote;
			productReference = D2AAC07E0554694100DB518D /* libNote.a */;
			productType = "com.apple.product-type.library.static";
		};
/* End PBXNativeTarget section */

/* Begin PBXProject section */
		0867D690FE84028FC02AAC07 /* Project object */ = {
			isa = PBXProject;
			buildConfigurationList = 1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "Note" */;
			compatibilityVersion = "Xcode 3.1";
			hasScannedForEncodings = 1;
			mainGroup = 0867D691FE84028FC02AAC07 /* SendNote */;
			productRefGroup = 034768DFFF38A50411DB9C8B /* Products */;
			projectDirPath = "";
			projectRoot = "";
			targets = (
				D2AAC07D0554694100DB518D /* Note */,
			);
		};
/* End PBXProject section */

/* Begin PBXSourcesBuildPhase section */
		D2AAC07B0554694100DB518D /* Sources */ = {
			isa = PBXSourcesBuildPhase;
			buildActionMask = 2147483647;
			files = (
				C2942B6016A6551A00359A14 /* Note.m in Sources */,
				C2942B7616A655DB00359A14 /* NoteProtocolConverter.m in Sources */,
			);
			runOnlyForDeploymentPostprocessing = 0;
		};
/* End PBXSourcesBuildPhase section */

/* Begin XCBuildConfiguration section */
		1DEB921F08733DC00010E9CD /* Debug */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				ALWAYS_SEARCH_USER_PATHS = YES;
				ARCHS = "$(ARCHS_STANDARD_32_BIT)";
				COPY_PHASE_STRIP = NO;
				DSTROOT = /tmp/Note.dst;
				GCC_DYNAMIC_NO_PIC = NO;
				GCC_ENABLE_FIX_AND_CONTINUE = YES;
				GCC_MODEL_TUNING = G5;
				GCC_OPTIMIZATION_LEVEL = 0;
				GCC_PRECOMPILE_PREFIX_HEADER = YES;
				GCC_PREFIX_HEADER = Note_Prefix.pch;
				INSTALL_PATH = /usr/local/lib;
				PRODUCT_NAME = Note;
				USER_HEADER_SEARCH_PATHS = ../../../../../../../Std/FxStd;
			};
			name = Debug;
		};
		1DEB922008733DC00010E9CD /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				ALWAYS_SEARCH_USER_PATHS = YES;
				ARCHS = "$(ARCHS_STANDARD_32_BIT)";
				DSTROOT = /tmp/Note.dst;
				GCC_MODEL_TUNING = G5;
				GCC_PRECOMPILE_PREFIX_HEADER = YES;
				GCC_PREFIX_HEADER = Note_Prefix.pch;
				INSTALL_PATH = /usr/local/lib;
				PRODUCT_NAME = Note;
				USER_HEADER_SEARCH_PATHS = ../../../../../../../Std/FxStd;
			};
			name = Release;
		};
		1DEB922308733DC00010E9CD /* Debug */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				ARCHS = "$(ARCHS_STANDARD_32_BIT)";
				GCC_C_LANGUAGE_STANDARD = c99;
				GCC_OPTIMIZATION_LEVEL = 0;
				GCC_WARN_ABOUT_RETURN_TYPE = YES;
				GCC_WARN_UNUSED_VARIABLE = YES;
				OTHER_LDFLAGS = "-ObjC";
				PREBINDING = NO;
				SDKROOT = iphoneos4.0;
			};
			name = Debug;
		};
		1DEB922408733DC00010E9CD /* Release */ = {
			isa = XCBuildConfiguration;
			buildSettings = {
				ARCHS = "$(ARCHS_STANDARD_32_BIT)";
				GCC_C_LANGUAGE_STANDARD = c99;
				GCC_WARN_ABOUT_RETURN_TYPE = YES;
				GCC_WARN_UNUSED_VARIABLE = YES;
				OTHER_LDFLAGS = "-ObjC";
				PREBINDING = NO;
				SDKROOT = iphoneos4.0;
			};
			name = Release;
		};
/* End XCBuildConfiguration section */

/* Begin XCConfigurationList section */
		1DEB921E08733DC00010E9CD /* Build configuration list for PBXNativeTarget "Note" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				1DEB921F08733DC00010E9CD /* Debug */,
				1DEB922008733DC00010E9CD /* Release */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
		1DEB922208733DC00010E9CD /* Build configuration list for PBXProject "Note" */ = {
			isa = XCConfigurationList;
			buildConfigurations = (
				1DEB922308733DC00010E9CD /* Debug */,
				1DEB922408733DC00010E9CD /* Release */,
			);
			defaultConfigurationIsVisible = 0;
			defaultConfigurationName = Release;
		};
/* End XCConfigurationList section */
	};
	rootObject = 0867D690FE84028FC02AAC07 /* Project object */;
}


/* setsockopt with error checking.
   Copyright (C) 2016-2018 Free Software Foundation, Inc.
   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <http://www.gnu.org/licenses/>.  */

#include <support/xsocket.h>

#include <stdio.h>
#include <stdlib.h>
#include <support/check.h>

void
xsetsockopt (int fd, int level, int name, const void *val, socklen_t vallen)
{
  if (setsockopt (fd, level, name, val, vallen) != 0)
    FAIL_EXIT1 ("setsockopt (%d, %d, %d), %zu bytes: %m",
                fd, level, name, (size_t) vallen);
}


// Copyright 2014 go-dockerclient authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package docker

import (
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"math"
	"net"
	"net/http"
	"net/http/httputil"
	"sync"
	"sync/atomic"
	"time"
)

// APIEvents represents events coming from the Docker API
// The fields in the Docker API changed in API version 1.22, and
// events for more than images and containers are now fired off.
// To maintain forward and backward compatibility, go-dockerclient
// replicates the event in both the new and old format as faithfully as possible.
//
// For events that only exist in 1.22 in later, `Status` is filled in as
// `"Type:Action"` instead of just `Action` to allow for older clients to
// differentiate and not break if they rely on the pre-1.22 Status types.
//
// The transformEvent method can be consulted for more information about how
// events are translated from new/old API formats
type APIEvents struct {
	// New API Fields in 1.22
	Action string   `json:"action,omitempty"`
	Type   string   `json:"type,omitempty"`
	Actor  APIActor `json:"actor,omitempty"`

	// Old API fields for < 1.22
	Status string `json:"status,omitempty"`
	ID     string `json:"id,omitempty"`
	From   string `json:"from,omitempty"`

	// Fields in both
	Time     int64 `json:"time,omitempty"`
	TimeNano int64 `json:"timeNano,omitempty"`
}

// APIActor represents an actor that accomplishes something for an event
type APIActor struct {
	ID         string            `json:"id,omitempty"`
	Attributes map[string]string `json:"attributes,omitempty"`
}

type eventMonitoringState struct {
	// `sync/atomic` expects the first word in an allocated struct to be 64-bit
	// aligned on both ARM and x86-32. See https://goo.gl/zW7dgq for more details.
	lastSeen int64
	sync.RWMutex
	sync.WaitGroup
	enabled   bool
	C         chan *APIEvents
	errC      chan error
	listeners []chan<- *APIEvents
}

const (
	maxMonitorConnRetries = 5
	retryInitialWaitTime  = 10.
)

var (
	// ErrNoListeners is the error returned when no listeners are available
	// to receive an event.
	ErrNoListeners = errors.New("no listeners present to receive event")

	// ErrListenerAlreadyExists is the error returned when the listerner already
	// exists.
	ErrListenerAlreadyExists = errors.New("listener already exists for docker events")

	// ErrTLSNotSupported is the error returned when the client does not support
	// TLS (this applies to the Windows named pipe client).
	ErrTLSNotSupported = errors.New("tls not supported by this client")

	// EOFEvent is sent when the event listener receives an EOF error.
	EOFEvent = &APIEvents{
		Type:   "EOF",
		Status: "EOF",
	}
)

// AddEventListener adds a new listener to container events in the Docker API.
//
// The parameter is a channel through which events will be sent.
func (c *Client) AddEventListener(listener chan<- *APIEvents) error {
	var err error
	if !c.eventMonitor.isEnabled() {
		err = c.eventMonitor.enableEventMonitoring(c)
		if err != nil {
			return err
		}
	}
	return c.eventMonitor.addListener(listener)
}

// RemoveEventListener removes a listener from the monitor.
func (c *Client) RemoveEventListener(listener chan *APIEvents) error {
	err := c.eventMonitor.removeListener(listener)
	if err != nil {
		return err
	}
	if c.eventMonitor.listernersCount() == 0 {
		c.eventMonitor.disableEventMonitoring()
	}
	return nil
}

func (eventState *eventMonitoringState) addListener(listener chan<- *APIEvents) error {
	eventState.Lock()
	defer eventState.Unlock()
	if listenerExists(listener, &eventState.listeners) {
		return ErrListenerAlreadyExists
	}
	eventState.Add(1)
	eventState.listeners = append(eventState.listeners, listener)
	return nil
}

func (eventState *eventMonitoringState) removeListener(listener chan<- *APIEvents) error {
	eventState.Lock()
	defer eventState.Unlock()
	if listenerExists(listener, &eventState.listeners) {
		var newListeners []chan<- *APIEvents
		for _, l := range eventState.listeners {
			if l != listener {
				newListeners = append(newListeners, l)
			}
		}
		eventState.listeners = newListeners
		eventState.Add(-1)
	}
	return nil
}

func (eventState *eventMonitoringState) closeListeners() {
	for _, l := range eventState.listeners {
		close(l)
		eventState.Add(-1)
	}
	eventState.listeners = nil
}

func (eventState *eventMonitoringState) listernersCount() int {
	eventState.RLock()
	defer eventState.RUnlock()
	return len(eventState.listeners)
}

func listenerExists(a chan<- *APIEvents, list *[]chan<- *APIEvents) bool {
	for _, b := range *list {
		if b == a {
			return true
		}
	}
	return false
}

func (eventState *eventMonitoringState) enableEventMonitoring(c *Client) error {
	eventState.Lock()
	defer eventState.Unlock()
	if !eventState.enabled {
		eventState.enabled = true
		atomic.StoreInt64(&eventState.lastSeen, 0)
		eventState.C = make(chan *APIEvents, 100)
		eventState.errC = make(chan error, 1)
		go eventState.monitorEvents(c)
	}
	return nil
}

func (eventState *eventMonitoringState) disableEventMonitoring() error {
	eventState.Lock()
	defer eventState.Unlock()

	eventState.closeListeners()

	eventState.Wait()

	if eventState.enabled {
		eventState.enabled = false
		close(eventState.C)
		close(eventState.errC)
	}
	return nil
}

func (eventState *eventMonitoringState) monitorEvents(c *Client) {
	const (
		noListenersTimeout  = 5 * time.Second
		noListenersInterval = 10 * time.Millisecond
		noListenersMaxTries = noListenersTimeout / noListenersInterval
	)

	var err error
	for i := time.Duration(0); i < noListenersMaxTries && eventState.noListeners(); i++ {
		time.Sleep(10 * time.Millisecond)
	}

	if eventState.noListeners() {
		// terminate if no listener is available after 5 seconds.
		// Prevents goroutine leak when RemoveEventListener is called
		// right after AddEventListener.
		eventState.disableEventMonitoring()
		return
	}

	if err = eventState.connectWithRetry(c); err != nil {
		// terminate if connect failed
		eventState.disableEventMonitoring()
		return
	}
	for eventState.isEnabled() {
		timeout := time.After(100 * time.Millisecond)
		select {
		case ev, ok := <-eventState.C:
			if !ok {
				return
			}
			if ev == EOFEvent {
				eventState.disableEventMonitoring()
				return
			}
			eventState.updateLastSeen(ev)
			eventState.sendEvent(ev)
		case err = <-eventState.errC:
			if err == ErrNoListeners {
				eventState.disableEventMonitoring()
				return
			} else if err != nil {
				defer func() { go eventState.monitorEvents(c) }()
				return
			}
		case <-timeout:
			continue
		}
	}
}

func (eventState *eventMonitoringState) connectWithRetry(c *Client) error {
	var retries int
	eventState.RLock()
	eventChan := eventState.C
	errChan := eventState.errC
	eventState.RUnlock()
	err := c.eventHijack(atomic.LoadInt64(&eventState.lastSeen), eventChan, errChan)
	for ; err != nil && retries < maxMonitorConnRetries; retries++ {
		waitTime := int64(retryInitialWaitTime * math.Pow(2, float64(retries)))
		time.Sleep(time.Duration(waitTime) * time.Millisecond)
		eventState.RLock()
		eventChan = eventState.C
		errChan = eventState.errC
		eventState.RUnlock()
		err = c.eventHijack(atomic.LoadInt64(&eventState.lastSeen), eventChan, errChan)
	}
	return err
}

func (eventState *eventMonitoringState) noListeners() bool {
	eventState.RLock()
	defer eventState.RUnlock()
	return len(eventState.listeners) == 0
}

func (eventState *eventMonitoringState) isEnabled() bool {
	eventState.RLock()
	defer eventState.RUnlock()
	return eventState.enabled
}

func (eventState *eventMonitoringState) sendEvent(event *APIEvents) {
	eventState.RLock()
	defer eventState.RUnlock()
	eventState.Add(1)
	defer eventState.Done()
	if eventState.enabled {
		if len(eventState.listeners) == 0 {
			eventState.errC <- ErrNoListeners
			return
		}

		for _, listener := range eventState.listeners {
			select {
			case listener <- event:
			default:
			}
		}
	}
}

func (eventState *eventMonitoringState) updateLastSeen(e *APIEvents) {
	eventState.Lock()
	defer eventState.Unlock()
	if atomic.LoadInt64(&eventState.lastSeen) < e.Time {
		atomic.StoreInt64(&eventState.lastSeen, e.Time)
	}
}

func (c *Client) eventHijack(startTime int64, eventChan chan *APIEvents, errChan chan error) error {
	uri := "/events"
	if startTime != 0 {
		uri += fmt.Sprintf("?since=%d", startTime)
	}
	protocol := c.endpointURL.Scheme
	address := c.endpointURL.Path
	if protocol != "unix" && protocol != "npipe" {
		protocol = "tcp"
		address = c.endpointURL.Host
	}
	var dial net.Conn
	var err error
	if c.TLSConfig == nil {
		dial, err = c.Dialer.Dial(protocol, address)
	} else {
		netDialer, ok := c.Dialer.(*net.Dialer)
		if !ok {
			return ErrTLSNotSupported
		}
		dial, err = tlsDialWithDialer(netDialer, protocol, address, c.TLSConfig)
	}
	if err != nil {
		return err
	}
	//lint:ignore SA1019 this is needed here
	conn := httputil.NewClientConn(dial, nil)
	req, err := http.NewRequest("GET", uri, nil)
	if err != nil {
		return err
	}
	res, err := conn.Do(req)
	if err != nil {
		return err
	}
	//lint:ignore SA1019 ClientConn is needed here
	go func(res *http.Response, conn *httputil.ClientConn) {
		defer conn.Close()
		defer res.Body.Close()
		decoder := json.NewDecoder(res.Body)
		for {
			var event APIEvents
			if err = decoder.Decode(&event); err != nil {
				if err == io.EOF || err == io.ErrUnexpectedEOF {
					c.eventMonitor.RLock()
					if c.eventMonitor.enabled && c.eventMonitor.C == eventChan {
						// Signal that we're exiting.
						c.eventMonitor.RUnlock()
						eventChan <- EOFEvent
					} else {
						c.eventMonitor.RUnlock()
					}
					break
				}
				errChan <- err
			}
			if event.Time == 0 {
				continue
			}
			transformEvent(&event)
			c.eventMonitor.RLock()
			if c.eventMonitor.enabled && c.eventMonitor.C == eventChan {
				eventChan <- &event
			}
			c.eventMonitor.RUnlock()
		}
	}(res, conn)
	return nil
}

// transformEvent takes an event and determines what version it is from
// then populates both versions of the event
func transformEvent(event *APIEvents) {
	// if event version is <= 1.21 there will be no Action and no Type
	if event.Action == "" && event.Type == "" {
		event.Action = event.Status
		event.Actor.ID = event.ID
		event.Actor.Attributes = map[string]string{}
		switch event.Status {
		case "delete", "import", "pull", "push", "tag", "untag":
			event.Type = "image"
		default:
			event.Type = "container"
			if event.From != "" {
				event.Actor.Attributes["image"] = event.From
			}
		}
	} else {
		if event.Status == "" {
			if event.Type == "image" || event.Type == "container" {
				event.Status = event.Action
			} else {
				// Because just the Status has been overloaded with different Types
				// if an event is not for an image or a container, we prepend the type
				// to avoid problems for people relying on actions being only for
				// images and containers
				event.Status = event.Type + ":" + event.Action
			}
		}
		if event.ID == "" {
			event.ID = event.Actor.ID
		}
		if event.From == "" {
			event.From = event.Actor.Attributes["image"]
		}
	}
}