text:
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="import_form" class="WooRefill\Admin\Form\ImportForm">
            <argument type="service" id="refill_api"/>
            <argument type="service" id="request"/>
            <tag name="form.type"/>
        </service>

        <service id="product_table" class="WooRefill\Admin\Form\Type\ProductTableFormType">
            <tag name="form.type"/>
        </service>

        <service id="wp_checkbox" class="WooRefill\Admin\Form\Type\WPCheckboxType">
            <tag name="form.type"/>
        </service>

        <service id="carrier_choice" class="WooRefill\Admin\Form\Type\CarrierFormType">
            <argument type="service" id="product_category_manager"/>
            <tag name="form.type"/>
        </service>

        <service id="category_choice" class="WooRefill\Admin\Form\Type\CategoryFormType">
            <argument type="service" id="product_category_manager"/>
            <tag name="form.type"/>
        </service>

        <service id="product_status_choice" class="WooRefill\Admin\Form\Type\ProductStatusFormType">
            <tag name="form.type"/>
        </service>
    </services>
</container>


text:
package com.expedia.echox3.basics.monitoring.jvm;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.InstanceNotFoundException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

import com.expedia.echox3.basics.file.BaseFileHandler;
import com.expedia.echox3.basics.monitoring.event.BasicEvent;
import com.expedia.echox3.basics.monitoring.event.BasicException;
import com.expedia.echox3.basics.tools.time.WallClock;

public class BasicMBeanProxy
{
	private static final String		MESSAGE_FORMAT_INCOMPATIBLE		= "Incompatible types: Expected %s, but got %s.";
	private static final String		MESSAGE_FORMAT_SERVER_OBJECT	= "%s/%s";

	private String						m_serverName;
	private String						m_port;
	private ConnectionInformation		m_connectionInformation;
	private ObjectName					m_objectName;
	private AttributeList				m_attributeValueList;

	public BasicMBeanProxy(String serverName, String port)
	{
		m_serverName = serverName;
		m_port = port;
	}

	public String getServerName()
	{
		return m_serverName;
	}

	public String getPort()
	{
		return m_port;
	}

	public boolean isConnected()
	{
		return null != getConnectionInformation();
	}

	public MBeanServerConnection getConnection()
	{
		return getConnectionInformation().getServerConnection();
	}

	private ConnectionInformation getConnectionInformation()
	{
		return m_connectionInformation;
	}

	public void selectObject(String mbeanName) throws BasicException
	{
		try
		{
			m_objectName = new ObjectName(mbeanName);
		}
		catch (MalformedObjectNameException e)
		{
			String message = String.format("Failed to select object: %s", mbeanName);
			throw new BasicException(BasicEvent.EVENT_MBEAN_SELECT_ERROR, e, message);
		}
	}

	/**
	 * Generic method to read a single attribute from a remote MBean.
	 * This method does a network call.
	 * This method is also used by all the getAttributeAs<Type> methods.
	 *
	 * @param attributeName		name of the attribute within the currently selected MBean
	 * @return					The JMX matching object
	 * @throws BasicException	Something can always go wrong on a network call.
	 */
	public Object getAttribute(String attributeName) throws BasicException
	{
		try
		{
			Object attributeValue		= getConnection().getAttribute(m_objectName, attributeName);

			return attributeValue;
		}
		catch (InstanceNotFoundException e)
		{
			String message		= "Attribute not found: "
					+ String.format(MESSAGE_FORMAT_SERVER_OBJECT, m_serverName, m_objectName.toString());
			throw new BasicException(BasicEvent.EVENT_MBEAN_COUNTER_NOT_FOUND, e, message);
		}
		catch (Exception exception)
		{
			releaseConnection();
			String message		= "Failed to obtain the attribute for counter "
					+ String.format(MESSAGE_FORMAT_SERVER_OBJECT, m_serverName, m_objectName.toString());
			throw new BasicException(BasicEvent.EVENT_MBEAN_GET_OBJECT_ERROR, exception, message);
		}
	}

	/**
	 * Generic method to read multiple attributes from a remote MBean using a single network call.
	 * This method does a network call.
	 * This method is also used in combination with the getAttributeFromListAs<Type> methods
	 * when several attributes are required and a single network call is desired (better performance, less overhead).
	 *
	 * @param attributeNameList		name of the attributes within the currently selected MBean
	 * @throws BasicException		Something can always go wrong on a network call.
	 */
	public void getAttributeList(String[] attributeNameList) throws BasicException
	{
		try
		{
			m_attributeValueList	= getConnection().getAttributes(m_objectName, attributeNameList);
		}
		catch (Exception exception)
		{
			releaseConnection();
			String message		= "Failed to obtain attribute values for counter "
					+ String.format(MESSAGE_FORMAT_SERVER_OBJECT, m_serverName, m_objectName.toString());
			throw new BasicException(BasicEvent.EVENT_MBEAN_GET_OBJECT_ERROR, exception, message);
		}
	}

	public Object doOperation(String operationName, Object[] params, String[] signature) throws BasicException
	{
		try
		{
			return getConnection().invoke(m_objectName, operationName, params, signature);
		}
		catch (Exception exception)
		{
			String message		= "Exception using object: "
					+ String.format(MESSAGE_FORMAT_SERVER_OBJECT, m_serverName, m_objectName.toString());
			throw new BasicException(BasicEvent.EVENT_MBEAN_OPERATION_ERROR, exception, message);
		}
	}

	/**
	 *
	 * This call is very expensive, the value is cached and re-queried only every so many seconds.
	 * The caller is responsible for having an understanding of the maximum acceptable age.
	 * For example, the name of the garbage related counters do not change, so ageMaxMS can be high.
	 *
	 * @param ageMaxMS	Maximum age of the JMX object names that is acceptable to the caller
	 * 					e.g. GC object names do not change, so a large value is acceptable.
	 * @return			The complete set of object names.
	 * @throws BasicException        If the set cannot be obtained (e.g. the remote server is offline)
	 */
	public Set<ObjectName> getObjectNameSet(long ageMaxMS, String name) throws BasicException
	{
		ConnectionInformation	connectionInformation	= getConnectionInformation();
		try
		{
			long		ageMS		= WallClock.getCurrentTimeMS() - connectionInformation.getObjectNameSetTime();
			if (null == connectionInformation.getObjectNameSet() || ageMaxMS < ageMS)
			{
				ObjectName objectName		= new ObjectName(name);
				Set<ObjectName> objectNameSet	= getConnection().queryNames(objectName, null);
				connectionInformation.setObjectNameSet(objectNameSet);
			}
		}
		catch (Exception exception)
		{
			releaseConnection();
			String message		= "Failed to obtain a Set<ObjectName>";
			throw new BasicException(BasicEvent.EVENT_MBEAN_GET_OBJECT_ERROR, exception, message);
		}

		return connectionInformation.getObjectNameSet();
	}

	public String getAttributeAsString(String attributeName) throws BasicException
	{
		Object attributeObject		= getAttribute(attributeName);

		return attributeObject.toString();
	}

	public Integer getAttributeAsInteger(String attributeName) throws BasicException
	{
		Object attributeObject		= getAttribute(attributeName);

		if (attributeObject instanceof Integer)
		{
			return (Integer) attributeObject;
		}
		else
		{
			String message		= String.format(MESSAGE_FORMAT_INCOMPATIBLE,
					Integer.class.getName(), attributeObject.getClass().getName());
			throw new BasicException(BasicEvent.EVENT_MBEAN_GET_OBJECT_ERROR, message);
		}
	}

	public Long getAttributeAsLong(String attributeName) throws BasicException
	{
		Object attributeObject		= getAttribute(attributeName);

		if (attributeObject instanceof Long)
		{
			return (Long) attributeObject;
		}
		else
		{
			String message		= String.format(MESSAGE_FORMAT_INCOMPATIBLE,
					Long.class.getName(), attributeObject.getClass().getName());
			throw new BasicException(BasicEvent.EVENT_MBEAN_GET_OBJECT_ERROR, message);
		}
	}

	public double getAttributeAsDouble(String attributeName) throws BasicException
	{
		Object attributeObject		= getAttribute(attributeName);

		if (attributeObject instanceof Number)
		{
			return ((Number) attributeObject).doubleValue();
		}
		else
		{
			String message		= String.format(MESSAGE_FORMAT_INCOMPATIBLE,
					Double.class.getName(), attributeObject.getClass().getName());
			throw new BasicException(BasicEvent.EVENT_MBEAN_GET_OBJECT_ERROR, message);
		}
	}

	public Map<String, Number> getAttributeMapOfNumber()
	{
		Map<String, Number>		map		= new HashMap<>();
		for (Object o : m_attributeValueList)
		{
			Attribute attribute	= (Attribute) o;
			if (attribute.getValue() instanceof Number)
			{
				map.put(attribute.getName(), (Number) attribute.getValue());
			}
		}
		return map;
	}

	public Object getAttributeFromList(String attributeName)
	{
		for (Object o : m_attributeValueList)
		{
			Attribute attribute	= (Attribute) o;
			if (attribute.getName().equals(attributeName))
			{
				return attribute.getValue();
			}
		}
		return null;
	}

	public String getAttributeFromListAsString(String attributeName)
	{
		Object object		= getAttributeFromList(attributeName);
		return null == object ? null : object.toString();
	}

	public long getAttributeFromListAsInteger(String attributeName) throws BasicException
	{
		Object attributeObject		= getAttributeFromList(attributeName);

		if (attributeObject instanceof Number)
		{
			return ((Number) attributeObject).intValue();
		}
		else
		{
			String message		= String.format(MESSAGE_FORMAT_INCOMPATIBLE,
					Integer.class.getName(), attributeObject.getClass().getName());
			throw new BasicException(BasicEvent.EVENT_MBEAN_GET_OBJECT_ERROR, message);
		}
	}
	public long getAttributeFromListAsLong(String attributeName) throws BasicException
	{
		Object attributeObject		= getAttributeFromList(attributeName);

		if (attributeObject instanceof Number)
		{
			return ((Number) attributeObject).longValue();
		}
		else
		{
			String message		= String.format(MESSAGE_FORMAT_INCOMPATIBLE,
					Long.class.getName(), attributeObject.getClass().getName());
			throw new BasicException(BasicEvent.EVENT_MBEAN_GET_OBJECT_ERROR, message);
		}
	}
	public double getAttributeFromListAsDouble(String attributeName) throws BasicException
	{
		Object attributeObject		= getAttributeFromList(attributeName);

		if (attributeObject instanceof Number)
		{
			return ((Number) attributeObject).doubleValue();
		}
		else
		{
			String message		= String.format(MESSAGE_FORMAT_INCOMPATIBLE,
					Double.class.getName(), attributeObject.getClass().getName());
			throw new BasicException(BasicEvent.EVENT_MBEAN_GET_OBJECT_ERROR, message);
		}
	}

	public void connect() throws BasicException
	{
		if (null == m_connectionInformation)
		{
			try
			{
				String connectionString	= String.format(
						"service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi",
						m_serverName, m_port);
				JMXServiceURL url					= new JMXServiceURL(connectionString);
				JMXConnector connector			= JMXConnectorFactory.connect(url);
				MBeanServerConnection serverConnection	= connector.getMBeanServerConnection();
				m_connectionInformation	= new ConnectionInformation(connector, serverConnection);
			}
			catch (Exception exception)
			{
				String message		= "Failed to obtain the MBean for " + m_serverName;
				throw new BasicException(BasicEvent.EVENT_MBEAN_CONNECT_ERROR, exception, message);
			}
		}
	}

	public void releaseConnection()
	{
		BasicMBeanManager.getLogger().info(BasicEvent.EVENT_MBEAN_DISCONNECT,
				"Disconnecting (JMX) from %s:%s", m_serverName, m_port);
		BaseFileHandler.closeSafe(m_connectionInformation.getConnector());
		m_connectionInformation = null;
	}

	@Override
	public String toString()
	{
		return String.format("%s:%s (isConnected = %s)", getServerName(), getPort(), isConnected());
	}

	private static class ConnectionInformation
	{
		private JMXConnector m_connector;
		private MBeanServerConnection m_serverConnection;
		private Set<ObjectName> m_objectNameSet			= null;
		private long						m_objectNameSetTime		= 0;

		public ConnectionInformation(JMXConnector connector, MBeanServerConnection serverConnection)
		{
			m_connector = connector;
			m_serverConnection = serverConnection;
		}

		public JMXConnector getConnector()
		{
			return m_connector;
		}

		public MBeanServerConnection getServerConnection()
		{
			return m_serverConnection;
		}

		public Set<ObjectName> getObjectNameSet()
		{
			return m_objectNameSet;
		}

		public void setObjectNameSet(Set<ObjectName> objectNameSet)
		{
			m_objectNameSet = objectNameSet;
			m_objectNameSetTime = WallClock.getCurrentTimeMS();
		}

		public long getObjectNameSetTime()
		{
			return m_objectNameSetTime;
		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * This class is generated by jOOQ
 */
package org.carbon.sample.ext.jooq.tables.daos;

import java.util.List;
import javax.annotation.Generated;

import org.carbon.sample.ext.jooq.tables.Lecturer;
import org.carbon.sample.ext.jooq.tables.records.LecturerRecord;
import org.jooq.Configuration;
import org.jooq.impl.DAOImpl;

/**
 * This class is generated by jOOQ.
 */
@Generated(
        value = {
                "http://www.jooq.org",
                "jOOQ version:3.8.6"
        },
        comments = "This class is generated by jOOQ"
)
@SuppressWarnings({"all", "unchecked", "rawtypes"})
public class LecturerDao extends DAOImpl<LecturerRecord, org.carbon.sample.ext.jooq.tables.pojos.Lecturer, Long> {

    /**
     * Create a new LecturerDao without any configuration
     */
    public LecturerDao() {
        super(Lecturer.LECTURER, org.carbon.sample.ext.jooq.tables.pojos.Lecturer.class);
    }

    /**
     * Create a new LecturerDao with an attached configuration
     */
    public LecturerDao(Configuration configuration) {
        super(Lecturer.LECTURER, org.carbon.sample.ext.jooq.tables.pojos.Lecturer.class, configuration);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected Long getId(org.carbon.sample.ext.jooq.tables.pojos.Lecturer object) {
        return object.getId();
    }

    /**
     * Fetch records that have id IN (values)
     */
    public List<org.carbon.sample.ext.jooq.tables.pojos.Lecturer> fetchById(Long... values) {
        return fetch(Lecturer.LECTURER.ID, values);
    }

    /**
     * Fetch a unique record that has id = value
     */
    public org.carbon.sample.ext.jooq.tables.pojos.Lecturer fetchOneById(Long value) {
        return fetchOne(Lecturer.LECTURER.ID, value);
    }

    /**
     * Fetch records that have identityClass IN (values)
     */
    public List<org.carbon.sample.ext.jooq.tables.pojos.Lecturer> fetchByUsername(String... values) {
        return fetch(Lecturer.LECTURER.USERNAME, values);
    }

    /**
     * Fetch records that have email IN (values)
     */
    public List<org.carbon.sample.ext.jooq.tables.pojos.Lecturer> fetchByEmail(String... values) {
        return fetch(Lecturer.LECTURER.EMAIL, values);
    }

    /**
     * Fetch a unique record that has email = value
     */
    public org.carbon.sample.ext.jooq.tables.pojos.Lecturer fetchOneByEmail(String value) {
        return fetchOne(Lecturer.LECTURER.EMAIL, value);
    }

    /**
     * Fetch records that have thumbnail_id IN (values)
     */
    public List<org.carbon.sample.ext.jooq.tables.pojos.Lecturer> fetchByThumbnailId(Long... values) {
        return fetch(Lecturer.LECTURER.THUMBNAIL_ID, values);
    }

    /**
     * Fetch records that have pr_text IN (values)
     */
    public List<org.carbon.sample.ext.jooq.tables.pojos.Lecturer> fetchByPrText(String... values) {
        return fetch(Lecturer.LECTURER.PR_TEXT, values);
    }

    /**
     * Fetch records that have password IN (values)
     */
    public List<org.carbon.sample.ext.jooq.tables.pojos.Lecturer> fetchByPassword(String... values) {
        return fetch(Lecturer.LECTURER.PASSWORD, values);
    }

    /**
     * Fetch records that have pr_text_short IN (values)
     */
    public List<org.carbon.sample.ext.jooq.tables.pojos.Lecturer> fetchByPrTextShort(String... values) {
        return fetch(Lecturer.LECTURER.PR_TEXT_SHORT, values);
    }
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=../../openssl_sys/constant.NID_org.html">

Redirecting to ../../openssl_sys/constant.NID_org.html...


text:
namespace content {
// NOTE: changes to this class need to be reviewed by the security team.
class CONTENT_EXPORT PpapiPluginSandboxedProcessLauncherDelegate
    : public content::SandboxedProcessLauncherDelegate {
 public:
  explicit PpapiPluginSandboxedProcessLauncherDelegate(
      const ppapi::PpapiPermissions& permissions);

  PpapiPluginSandboxedProcessLauncherDelegate(
      const PpapiPluginSandboxedProcessLauncherDelegate&) = delete;
  PpapiPluginSandboxedProcessLauncherDelegate& operator=(
      const PpapiPluginSandboxedProcessLauncherDelegate&) = delete;

  ~PpapiPluginSandboxedProcessLauncherDelegate() override = default;

#if BUILDFLAG(IS_WIN)
  bool PreSpawnTarget(sandbox::TargetPolicy* policy) override;
#endif  // BUILDFLAG(IS_WIN)

#if BUILDFLAG(USE_ZYGOTE_HANDLE)
  ZygoteHandle GetZygote() override;
#endif  // BUILDFLAG(USE_ZYGOTE_HANDLE)

  sandbox::mojom::Sandbox GetSandboxType() override;

#if BUILDFLAG(IS_MAC)
  bool DisclaimResponsibility() override;
  bool EnableCpuSecurityMitigations() override;
#endif

 private:
#if BUILDFLAG(IS_WIN)
  const ppapi::PpapiPermissions permissions_;
#endif
};
}  // namespace content

#endif


text:
.class abstract Landroid/widget/RemoteViews$Action;
.super Ljava/lang/Object;
.source "RemoteViews.java"

# interfaces
.implements Landroid/os/Parcelable;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/widget/RemoteViews;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x40a
    name = "Action"
.end annotation

# static fields
.field public static final MERGE_APPEND:I = 0x1

.field public static final MERGE_IGNORE:I = 0x2

.field public static final MERGE_REPLACE:I

# instance fields
.field validToRemove:Z

.field validToReplace:Z

.field viewId:I

# direct methods
.method private constructor <init>()V
    .locals 1

    .prologue
    const/4 v0, 0x0

    .line 317
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 352
    iput-boolean v0, p0, Landroid/widget/RemoteViews$Action;->validToReplace:Z

    .line 353
    iput-boolean v0, p0, Landroid/widget/RemoteViews$Action;->validToRemove:Z

    return-void
.end method

.method synthetic constructor <init>(Landroid/widget/RemoteViews$1;)V
    .locals 0
    .param p1, "x0"    # Landroid/widget/RemoteViews$1;

    .prologue
    .line 317
    invoke-direct {p0}, Landroid/widget/RemoteViews$Action;-><init>()V

    return-void
.end method

# virtual methods
.method public abstract apply(Landroid/view/View;Landroid/view/ViewGroup;Landroid/widget/RemoteViews$OnClickHandler;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/widget/RemoteViews$ActionException;
        }
    .end annotation
.end method

.method public describeContents()I
    .locals 1

    .prologue
    .line 326
    const/4 v0, 0x0

    return v0
.end method

.method public abstract getActionName()Ljava/lang/String;
.end method

.method public getUniqueKey()Ljava/lang/String;
    .locals 2

    .prologue
    .line 348
    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    invoke-virtual {p0}, Landroid/widget/RemoteViews$Action;->getActionName()Ljava/lang/String;

    move-result-object v1

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget v1, p0, Landroid/widget/RemoteViews$Action;->viewId:I

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public mergeBehavior()I
    .locals 1

    .prologue
    .line 342
    const/4 v0, 0x0

    return v0
.end method

.method public setBitmapCache(Landroid/widget/RemoteViews$BitmapCache;)V
    .locals 0
    .param p1, "bitmapCache"    # Landroid/widget/RemoteViews$BitmapCache;

    .prologue
    .line 339
    return-void
.end method

.method public updateMemoryUsageEstimate(Landroid/widget/RemoteViews$MemoryUsageCounter;)V
    .locals 0
    .param p1, "counter"    # Landroid/widget/RemoteViews$MemoryUsageCounter;

    .prologue
    .line 335
    return-void
.end method


text:
<?php

namespace Flarum\Api\Serializer;

class CurrentUserSerializer extends UserSerializer
{
    /**
     * {@inheritdoc}
     */
    protected function getDefaultAttributes($user)
    {
        $attributes = parent::getDefaultAttributes($user);

        $attributes += [
            'isActivated'              => $user->is_activated,
            'email'                    => $user->email,
            'readTime'                 => $this->formatDate($user->read_time),
            'unreadNotificationsCount' => (int) $user->getUnreadNotificationsCount(),
            'newNotificationsCount'    => (int) $user->getNewNotificationsCount(),
            'preferences'              => (array) $user->preferences
        ];

        return $attributes;
    }
}


text:
package main

import (
	"./github.com/nu7hatch/gouuid"
	"./labix.org/v2/mgo"
	"./labix.org/v2/mgo/bson"
	"./ripple"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strings"
)

type Picture struct {
	Id        bson.ObjectId "_id,omitempty"
	KadaID    string        `json:"kadaid,omitempty"`
	Original  []byte        `json:"original,omitempty"`
	Thumbnail []byte        `json:"thumbnail,omitempty"`
	Email     []byte        `json:"email,omitempty"`
	Web       []byte        `json:"web,omitempty"`
}

type PictureController struct {
	col *mgo.Collection
}

func NewPictureController(col *mgo.Collection) *PictureController {
	pc := new(PictureController)
	pc.col = col
	return pc
}

func (this *PictureController) Get(ctx *ripple.Context) {
	var ug = ctx.Params["kadaID"]
	var t = ctx.Params["type"]

	if len(ug) > 0 {
		u, err := uuid.ParseHex(strings.ToLower(ug))
		if err != nil {
			ctx.Response.Body = "Invalid kadaID!"
			ctx.Response.Status = http.StatusBadRequest
		} else {
			g := u.String()

			var result *Picture
			query := this.col.Find(bson.M{"kadaid": g})
			if len(t) > 0 {
				query.Select(bson.M{"kadaid": 1, t: 1})
			}
			err := query.One(&result)
			if err != nil {
				ctx.Response.Status = http.StatusNotFound
				ctx.Response.Body = err
			} else {
				ctx.Response.Status = http.StatusOK
				ctx.Response.Body = result
			}
		}
	} /* else {
		var result []Picture
		query := this.col.Find(nil)
		if len(t) > 0 {
			if t != "all" {
				query.Select(bson.M{"kadaid": 1, t: 1})
			}
		}
		err := query.All(&result)
		if err != nil {
			ctx.Response.Body = err
		} else {
			ctx.Response.Body = result
		}
	} */
}

func (this *PictureController) postPut(ctx *ripple.Context) {
	var ug = ctx.Params["kadaID"]
	body, _ := ioutil.ReadAll(ctx.Request.Body)

	if len(ug) > 0 {
		u, err := uuid.ParseHex(strings.ToLower(ug))
		if err != nil {
			ctx.Response.Body = "Invalid kadaID!"
			ctx.Response.Status = http.StatusBadRequest
		} else {
			g := u.String()

			var pic = Picture{KadaID: g}
			json.Unmarshal(body, &pic)

			var result *Picture
			this.col.Find(bson.M{"kadaid": g}).One(&result)

			if result != nil {
				fmt.Println("update: ", g)
				this.col.Update(bson.M{"kadaid": g}, pic)
			} else {
				fmt.Println("insert: ", g)
				this.col.Upsert(pic, pic)
			}

			ctx.Response.Status = http.StatusOK
		}
	} else {
		ctx.Response.Status = http.StatusBadRequest
	}
}

func (this *PictureController) Post(ctx *ripple.Context) {
	this.postPut(ctx)
}

func (this *PictureController) Put(ctx *ripple.Context) {
	this.postPut(ctx)
}

func (this *PictureController) Delete(ctx *ripple.Context) {
	// Možda kad bih znao napisati funkciju u Gou
	// ovo nebi bilo tragično copy-pasteano tri puta
	// - Marko

	var ug = ctx.Params["kadaID"]
	if len(ug) > 0 {
		u, err := uuid.ParseHex(strings.ToLower(ug))
		if err != nil {
			ctx.Response.Body = "Invalid kadaID!"
			ctx.Response.Status = http.StatusBadRequest
		} else {
			g := u.String()

			err := this.col.Remove(bson.M{"kadaid": g})
			if err != nil {
				ctx.Response.Body = err
				ctx.Response.Status = http.StatusNotFound
			} else {
				ctx.Response.Status = http.StatusOK
			}
		}
	} else {
		ctx.Response.Status = http.StatusBadRequest
	}
}


text:
<?php

namespace Elastica\Filter;

/**
 * Prefix filter
 *
 * @category Xodoa
 * @package Elastica
 * @author Jasper van Wanrooy <jasper@vanwanrooy.net>
 * @link http://www.elasticsearch.org/guide/reference/query-dsl/prefix-filter.html
 */
class Prefix extends AbstractFilter
{
    /**
     * Holds the name of the field for the prefix.
     *
     * @var string
     */
    protected $_field = '';

    /**
     * Holds the prefix string.
     *
     * @var string
     */
    protected $_prefix = '';

    /**
     * Creates prefix filter
     *
     * @param string $field  Field name
     * @param string $prefix Prefix string
     */
    public function __construct($field = '', $prefix = '')
    {
        $this->setField($field);
        $this->setPrefix($prefix);
    }

    /**
     * Sets the name of the prefix field.
     *
     * @param  string                       $field Field name
     * @return \Elastica\Filter\Prefix
     */
    public function setField($field)
    {
        $this->_field = $field;

        return $this;
    }

    /**
     * Sets the prefix string.
     *
     * @param  string                       $prefix Prefix string
     * @return \Elastica\Filter\Prefix
     */
    public function setPrefix($prefix)
    {
        $this->_prefix = $prefix;

        return $this;
    }

    /**
     * Converts object to an array
     *
     * @see \Elastica\Filter\AbstractFilter::toArray()
     * @return array data array
     */
    public function toArray()
    {
        $this->setParam($this->_field, $this->_prefix);

        return parent::toArray();
    }
}


text:
module BELParser
  module Script
    # ApplyResourceURI applies the _uri_ property to
    # {BELParser::Parsers::AST::AnnotationDefinition} and
    # {BELParser::Parsers::AST::NamespaceDefinition} child nodes.
    class ApplyResourceURI
      include AST::Processor::Mixin

      def on_annotation_definition(node)
        update_uri_property(node)
      end

      def on_namespace_definition(node)
        update_uri_property(node)
      end

      private

      def update_uri_property(node)
        domain = node.domain
        if domain.url?
          resource_url = domain.child.string.string_literal
          node.uri     = BELParser::Resource.resolve_uri(resource_url)
        end

        node
      end
    end
  end
end


text:
package com.igitras.auth.mvc.dto;

import java.io.Serializable;

/**
 * Created by mason on 3/14/16.
 */
public class AccountDto implements Serializable {
    private boolean enabled;
    private String username;
    private String password;
    private String email;

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}


text:
/* $Id$ */
/* libnatpmp
 * Copyright (c) 2007-2008, Thomas BERNARD <miniupnp@free.fr>
 * http://miniupnp.free.fr/libnatpmp.html
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <string.h>
#include <time.h>
#include <sys/time.h>
#ifdef WIN32
#include <errno.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <io.h>
#define EWOULDBLOCK WSAEWOULDBLOCK
#define ECONNREFUSED WSAECONNREFUSED
#else
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#define closesocket close
#endif
#include "natpmp.h"
#include "getgateway.h"

LIBSPEC int initnatpmp(natpmp_t * p)
{
#ifdef WIN32
	u_long ioctlArg = 1;
#else
	int flags;
#endif
	struct sockaddr_in addr;
	if(!p)
		return NATPMP_ERR_INVALIDARGS;
	memset(p, 0, sizeof(natpmp_t));
	p->s = socket(PF_INET, SOCK_DGRAM, 0);
	if(p->s < 0)
		return NATPMP_ERR_SOCKETERROR;
#ifdef WIN32
	if(ioctlsocket(p->s, FIONBIO, &ioctlArg) == SOCKET_ERROR)
		return NATPMP_ERR_FCNTLERROR;
#else
	if((flags = fcntl(p->s, F_GETFL, 0)) < 0)
		return NATPMP_ERR_FCNTLERROR;
	if(fcntl(p->s, F_SETFL, flags | O_NONBLOCK) < 0)
		return NATPMP_ERR_FCNTLERROR;
#endif

	if(getdefaultgateway(&(p->gateway)) < 0)
		return NATPMP_ERR_CANNOTGETGATEWAY;

	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(NATPMP_PORT);
	addr.sin_addr.s_addr = p->gateway;
	if(connect(p->s, (struct sockaddr *)&addr, sizeof(addr)) < 0)
		return NATPMP_ERR_CONNECTERR;
	return 0;
}

LIBSPEC int closenatpmp(natpmp_t * p)
{
	if(!p)
		return NATPMP_ERR_INVALIDARGS;
	if(closesocket(p->s) < 0)
		return NATPMP_ERR_CLOSEERR;
	return 0;
}

int sendpendingrequest(natpmp_t *);
int sendpendingrequest(natpmp_t * p)
{
	int r;
/*	struct sockaddr_in addr;*/
	if(!p)
		return NATPMP_ERR_INVALIDARGS;
/*	memset(&addr, 0, sizeof(addr));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(NATPMP_PORT);
	addr.sin_addr.s_addr = p->gateway;
	r = (int)sendto(p->s, p->pending_request, p->pending_request_len, 0,
	                   (struct sockaddr *)&addr, sizeof(addr));*/
	r = (int)send(p->s, p->pending_request, p->pending_request_len, 0);
	return (r<0) ? NATPMP_ERR_SENDERR : r;
}

int sendnatpmprequest(natpmp_t *);
int sendnatpmprequest(natpmp_t * p)
{
	int n;
	if(!p)
		return NATPMP_ERR_INVALIDARGS;
	/* TODO : check if no request is allready pending */
	p->has_pending_request = 1;
	p->try_number = 1;
	n = sendpendingrequest(p);
	gettimeofday(&p->retry_time, NULL);	// check errors !
	p->retry_time.tv_usec += 250000;	/* add 250ms */
	if(p->retry_time.tv_usec >= 1000000) {
		p->retry_time.tv_usec -= 1000000;
		p->retry_time.tv_sec++;
	}
	return n;
}

LIBSPEC int getnatpmprequesttimeout(natpmp_t * p, struct timeval * timeout)
{
	struct timeval now;
	if(!p || !timeout)
		return NATPMP_ERR_INVALIDARGS;
	if(!p->has_pending_request)
		return NATPMP_ERR_NOPENDINGREQ;
	if(gettimeofday(&now, NULL) < 0)
		return NATPMP_ERR_GETTIMEOFDAYERR;
	timeout->tv_sec = p->retry_time.tv_sec - now.tv_sec;
	timeout->tv_usec = p->retry_time.tv_usec - now.tv_usec;
	if(timeout->tv_usec < 0) {
		timeout->tv_usec += 1000000;
		timeout->tv_sec--;
	}
	return 0;
}

LIBSPEC int sendpublicaddressrequest(natpmp_t * p)
{
	if(!p)
		return NATPMP_ERR_INVALIDARGS;
	//static const unsigned char request[] = { 0, 0 };
	p->pending_request[0] = 0;
	p->pending_request[1] = 0;
	p->pending_request_len = 2;
	// TODO: return 0 instead of sizeof(request) ??
	return sendnatpmprequest(p);
}

LIBSPEC int sendnewportmappingrequest(natpmp_t * p, int protocol,
                              uint16_t privateport, uint16_t publicport,
							  uint32_t lifetime)
{
	if(!p || (protocol!=NATPMP_PROTOCOL_TCP && protocol!=NATPMP_PROTOCOL_UDP))
		return NATPMP_ERR_INVALIDARGS;
	p->pending_request[0] = 0;
	p->pending_request[1] = protocol;
	p->pending_request[2] = 0;
	p->pending_request[3] = 0;
	*((uint16_t *)(p->pending_request + 4)) = htons(privateport);
	*((uint16_t *)(p->pending_request + 6)) = htons(publicport);
	*((uint32_t *)(p->pending_request + 8)) = htonl(lifetime);
	p->pending_request_len = 12;
	return sendnatpmprequest(p);
}

LIBSPEC int readnatpmpresponse(natpmp_t *, natpmpresp_t *);
LIBSPEC int readnatpmpresponse(natpmp_t * p, natpmpresp_t * response)
{
	unsigned char buf[16];
	struct sockaddr_in addr;
	socklen_t addrlen = sizeof(addr);
	int n;
	if(!p)
		return NATPMP_ERR_INVALIDARGS;
	n = recvfrom(p->s, buf, sizeof(buf), 0,
	             (struct sockaddr *)&addr, &addrlen);
	if(n<0)
		switch(errno) {
		/*case EAGAIN:*/
		case EWOULDBLOCK:
			n = NATPMP_TRYAGAIN;
			break;
		case ECONNREFUSED:
			n = NATPMP_ERR_NOGATEWAYSUPPORT;
			break;
		default:
			n = NATPMP_ERR_RECVFROM;
		}
	/* check that addr is correct (= gateway) */
	else if(addr.sin_addr.s_addr != p->gateway)
		n = NATPMP_ERR_WRONGPACKETSOURCE;
	else {
		response->resultcode = ntohs(*((uint16_t *)(buf + 2)));
		response->epoch = ntohl(*((uint32_t *)(buf + 4)));
		if(buf[0] != 0)
			n = NATPMP_ERR_UNSUPPORTEDVERSION;
		else if(buf[1] < 128 || buf[1] > 130)
			n = NATPMP_ERR_UNSUPPORTEDOPCODE;
		else if(response->resultcode != 0) {
			switch(response->resultcode) {
			case 1:
				n = NATPMP_ERR_UNSUPPORTEDVERSION;
				break;
			case 2:
				n = NATPMP_ERR_NOTAUTHORIZED;
				break;
			case 3:
				n = NATPMP_ERR_NETWORKFAILURE;
				break;
			case 4:
				n = NATPMP_ERR_OUTOFRESOURCES;
				break;
			case 5:
				n = NATPMP_ERR_UNSUPPORTEDOPCODE;
				break;
			default:
				n = NATPMP_ERR_UNDEFINEDERROR;
			}
		} else {
			response->type = buf[1] & 0x7f;
			if(buf[1] == 128)
				//response->publicaddress.addr = *((uint32_t *)(buf + 8));
				response->pnu.publicaddress.addr.s_addr = *((uint32_t *)(buf + 8));
			else {
				response->pnu.newportmapping.privateport = ntohs(*((uint16_t *)(buf + 8)));
				response->pnu.newportmapping.mappedpublicport = ntohs(*((uint16_t *)(buf + 10)));
				response->pnu.newportmapping.lifetime = ntohl(*((uint32_t *)(buf + 12)));
			}
			n = 0;
		}
	}
	return n;
}

int readnatpmpresponseorretry(natpmp_t * p, natpmpresp_t * response)
{
	int n;
	if(!p || !response)
		return NATPMP_ERR_INVALIDARGS;
	if(!p->has_pending_request)
		return NATPMP_ERR_NOPENDINGREQ;
	n = readnatpmpresponse(p, response);
	if(n<0) {
		if(n==NATPMP_TRYAGAIN) {
			struct timeval now;
			gettimeofday(&now, NULL);	// check errors !
			if(timercmp(&now, &p->retry_time, >=)) {
				int delay, r;
				if(p->try_number >= 9) {
					return NATPMP_ERR_NOGATEWAYSUPPORT;
				}
				/*printf("retry! %d\n", p->try_number);*/
				delay = 250 * (1<<p->try_number);	// ms
				/*for(i=0; i<p->try_number; i++)
					delay += delay;*/
				p->retry_time.tv_sec += (delay / 1000);
				p->retry_time.tv_usec += (delay % 1000) * 1000;
				if(p->retry_time.tv_usec >= 1000000) {
					p->retry_time.tv_usec -= 1000000;
					p->retry_time.tv_sec++;
				}
				p->try_number++;
				r = sendpendingrequest(p);
				if(r<0)
					return r;
			}
		}
	} else {
		p->has_pending_request = 0;
	}
	return n;
}

#ifdef ENABLE_STRNATPMPERR
LIBSPEC const char * strnatpmperr(int r)
{
	const char * s;
	switch(r) {
	case NATPMP_ERR_INVALIDARGS:
		s = "invalid arguments";
		break;
	case NATPMP_ERR_SOCKETERROR:
		s = "socket() failed";
		break;
	case NATPMP_ERR_CANNOTGETGATEWAY:
		s = "cannot get default gateway ip address";
		break;
	case NATPMP_ERR_CLOSEERR:
#ifdef WIN32
		s = "closesocket() failed";
#else
		s = "close() failed";
#endif
		break;
	case NATPMP_ERR_RECVFROM:
		s = "recvfrom() failed";
		break;
	case NATPMP_ERR_NOPENDINGREQ:
		s = "no pending request";
		break;
	case NATPMP_ERR_NOGATEWAYSUPPORT:
		s = "the gateway does not support nat-pmp";
		break;
	case NATPMP_ERR_CONNECTERR:
		s = "connect() failed";
		break;
	case NATPMP_ERR_WRONGPACKETSOURCE:
		s = "packet not received from the default gateway";
		break;
	case NATPMP_ERR_SENDERR:
		s = "send() failed";
		break;
	case NATPMP_ERR_FCNTLERROR:
		s = "fcntl() failed";
		break;
	case NATPMP_ERR_GETTIMEOFDAYERR:
		s = "gettimeofday() failed";
		break;
	case NATPMP_ERR_UNSUPPORTEDVERSION:
		s = "unsupported nat-pmp version error from server";
		break;
	case NATPMP_ERR_UNSUPPORTEDOPCODE:
		s = "unsupported nat-pmp opcode error from server";
		break;
	case NATPMP_ERR_UNDEFINEDERROR:
		s = "undefined nat-pmp server error";
		break;
	case NATPMP_ERR_NOTAUTHORIZED:
		s = "not authorized";
		break;
	case NATPMP_ERR_NETWORKFAILURE:
		s = "network failure";
		break;
	case NATPMP_ERR_OUTOFRESOURCES:
		s = "nat-pmp server out of resources";
		break;
	default:
		s = "Unknown libnatpmp error";
	}
	return s;
}
#endif


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Doctrine\Bundle\FixturesBundle\DoctrineFixturesBundle(),
            new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(),
            new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            new JMS\SerializerBundle\JMSSerializerBundle($this),
            new FOS\RestBundle\FOSRestBundle(),
            new Nelmio\ApiDocBundle\NelmioApiDocBundle(),
            new JMS\TwigJsBundle\JMSTwigJsBundle(),
            new FOS\JsRoutingBundle\FOSJsRoutingBundle(),

            new Rithis\HeroHRBundle\RithisHeroHRBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__ . '/config/config_' . $this->getEnvironment() . '.yml');
    }
}


text:
package com.microsoft.azure.management.powerbidedicated.v2017_10_01.implementation;

import com.microsoft.azure.management.powerbidedicated.v2017_10_01.OperationDisplay;
import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * Capacities REST API operation.
 */
public class OperationInner {
    /**
     * Operation name: {provider}/{resource}/{operation}.
     */
    @JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY)
    private String name;

    /**
     * The object that represents the operation.
     */
    @JsonProperty(value = "display")
    private OperationDisplay display;

    /**
     * Get operation name: {provider}/{resource}/{operation}.
     *
     * @return the name value
     */
    public String name() {
        return this.name;
    }

    /**
     * Get the object that represents the operation.
     *
     * @return the display value
     */
    public OperationDisplay display() {
        return this.display;
    }

    /**
     * Set the object that represents the operation.
     *
     * @param display the display value to set
     * @return the OperationInner object itself.
     */
    public OperationInner withDisplay(OperationDisplay display) {
        this.display = display;
        return this;
    }

}


text:
package com.github.oligo.wechat.message;

import com.github.oligo.wechat.message.framework.Event;
import com.github.oligo.wechat.message.framework.MessageType;
import com.github.oligo.wechat.message.framework.router.Rule;

/**
 * Created by Rogers on 15-7-20.
 */
public class WxRule implements Rule {
    private String type;
    private String user;
    private long msgId;
    private Event event;
    private long createTime;

    public WxRule(String type, String user, long msgId) {
        this.type = type;
        this.user = user;
        this.msgId = msgId;
    }

    public WxRule(String type, String event, String user, long createTime) {
        this.type = type;
        this.user = user;
        this.event = Event.valueOf(event.toUpperCase());
        this.createTime = createTime;
    }

    @Override
    public String asString(){
        if(type.equals("event")){
            return "/type/" + type + "/event/"+ event.toString().toLowerCase() + "/user/" + user + "/time/" + createTime;
        }else{
            return "/type/" + type + "/user/" + user + "/msgid" + msgId;
        }
    }

    @Override
    public boolean matchWith(MessageType type1){
        return type1.equals(MessageType.valueOf(type.toUpperCase()));
    }

    public String getType() {
        return type;
    }

    public String getUser() {
        return user;
    }

    public long getMsgId() {
        return msgId;
    }

    public long getCreateTime() {
        return createTime;
    }

    public Event getEvent() {
        return event;
    }
}


text:
"""
cnn+lstm implimentation on the lip movement data.

Akm Ashiquzzaman
13101002@uap-bd.edu
Fall 2016

after 1 epoch , val_acc: 0.0926

"""
from __future__ import print_function, division

#random seed fixing for reproducibility
import numpy as np
np.random.seed(1337)

import time

#Data loading
X_train = np.load('../data/videopart43.npy')
Y_train = np.load('../data/audiopart43.npy')

#Reshaping to the 'th' order to feed into the cnn
X_train = X_train.reshape((X_train.shape[0],1,53,53)).astype('float32')
Y_train = Y_train.reshape((Y_train.shape[0],4702)).astype('float32')

#setting batch_size and epoch

batchSize = 20
tt_epoch = 1

from keras.models import Sequential
from keras.layers import Dense,LSTM,Dropout, Activation, Flatten,Reshape,Permute
from keras.layers import Convolution2D, MaxPooling2D

#time to measure the experiment.
tt = time.time()

#model building starts here
seq = Sequential()

#first conv layer

seq.add(Convolution2D(512,5,5,border_mode='same',
				input_shape=(1,53,53)))
seq.add(Activation('relu'))
seq.add(MaxPooling2D(pool_size=(5,5)))
seq.add(Dropout(0.25))

#second conv layer

seq.add(Convolution2D(1024,3,3))
seq.add(Activation('relu'))
seq.add(MaxPooling2D(pool_size=(3,3)))
seq.add(Dropout(0.25))

#flattening and adding lc layer for lstm pre-processing

seq.add(Flatten())

#locally connected layers

seq.add(Dense(2048))
seq.add(Activation('relu'))
seq.add(Dropout(0.5))

seq.add(Dense(4096))
seq.add(Activation('relu'))
seq.add(Dropout(0.5))
#reshapeing and permute to feed the data into a lstm network

seq.add(Reshape((32,128)))
seq.add(Permute((2,1)))

#1st lstm layer

seq.add(LSTM(256,return_sequences=True))
seq.add(Activation('tanh'))
seq.add(Dropout(0.25))

#2nd lstm layer

seq.add(LSTM(128,return_sequences=True))
seq.add(Activation('tanh'))
seq.add(Dropout(0.25))

#3rd lstm layer

seq.add(LSTM(64))
seq.add(Activation('tanh'))
seq.add(Dropout(0.25))

#final lc layer

seq.add(Dense(4702))
seq.add(Activation('softmax'))

seq.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])

#checkpoint import
from keras.callbacks import ModelCheckpoint
from os.path import isfile, join
#weight file name
weight_file = '../weights/cnn_lstm_weight_v2.h5'

#loading previous weight file for resuming training
if isfile(weight_file):
	seq.load_weights(weight_file)

#weight-checkmark
checkpoint = ModelCheckpoint(weight_file, monitor='acc', verbose=1, save_best_only=True, mode='min')

callbacks_list = [checkpoint]

print('total time: ',time.time()-tt)

seq.fit(X_train,Y_train,batch_size=batchSize, nb_epoch=tt_epoch
	,validation_split=0.2,callbacks=callbacks_list)

#generating prediction for testing
pred = seq.predict(X_train,batch_size=batchSize,verbose=1)

print('pred shape',pred.shape)
print('pred dtype',pred.dtype)
np.save('../predictions/pred-cnn_v2.npy',pred)


text:
A collection of scripts that I'm using to monitor my pool's temperature via a Raspberry Pi and a 1-wire temperature probe. Specifically, a DS18B20 waterproof probe wired to a Pi-EzConnect GPIO hat.

## Prerequisites

* `rrdtool` - I'm just shelling out to rrdtool for now to do the actual data store work.
* python 2.7 - Most of the scripts are Python.
* OS packages for Raspian/Debian, in order to compile the pypi `python-rrdtool` module:
  * `libpango1.0-dev`
  * `libxml2-dev`
  * `libcairo2-dev`
  * `libglib2.0-dev`
  * `python-dev`
  * `librrd-dev`
* python modules - Run `pip install -r requirements.txt`
* php 5.x - The web frontend is hastily written in PHP. You'll need apache or another web server too.

## Config
### `location.py`

A simple config so I don't have to put my home location into the public repo. It should look something like this:

```
from pytz import timezone
import collections

# Location information
longitude = -5;
latitude = 22;
localtz = timezone('UTC')
webpath = 'https://mywebserver.com/poolpi'
color_start = 0xff0000
color_offset = 12
temperature_probes = collections.OrderedDict()
temperature_probes['outdoor'] = '28-011620f667ff'
temperature_probes['probe'] = '28-011620f667ee'
```

**NOTE**: Weather Underground has shutdown. As a result, I've removed outdoor temperature scraping. Instead of
having to deal with an external service, I've decided to just go with another temperature probe. So I've added
that to the config above. It's an ordered dictionary with the key being the name of the rrd gauge and value being
the serial number of the probe. The ordering is important for exporting the structure between Python and PHP.

`color_start` and `color_offset` are used to override the stock colors. The first gauge starts at red and then
each gauge after that shifts 12 bits.

### RRD

Create an rrd at `temperature.rrd` with the `tools/create_rrd.py` script.

### Cron

Just add a crontab to take the temperature every minute and store it in rrd:
```
* * * * *   poolpi/update_rrd.py
```

### Web

Symlink or document root the `web` directory. Then you can access `temps.php` for a rudimentary display of
hourly, daily, weekly and yearly graphs. One graph for each time period will have ambient and probe
temperature overlaid and another graph will have just the probe temperature so it's easier to see
its fluctuation without the scale of the ambient temperature zooming out the graph.

### Alexa

The Alexa Skill is in the `alexa` directory. Run the `build_lambda_zip.sh` script to install python
dependencies within the directory and zip it up. You can then place that zip in a Lambda function and
configure an Alexa Skill to use its ARN. The `location.py` config is copied into the zip for configuration
of the timezone and location of the web server that is hosting the `web` contents.


text:
package net.sf.pagecache.constructs.web.filter;

import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPOutputStream;

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

import net.sf.pagecache.constructs.web.GenericResponseWrapper;
import net.sf.pagecache.constructs.web.ResponseUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Provides GZIP compression of responses.
 *

 * See the filter-mappings.xml entry for the gzip filter for the URL patterns which will be gzipped. At present this
 * includes .jsp, .js and .css.
 *

 *
 * @author Greg Luck
 * @author Adam Murdoch
 * @version $Id: GzipFilter.java 744 2008-08-16 20:10:49Z gregluck $
 */
public class GzipFilter extends Filter {

    private static final Logger LOG = LoggerFactory.getLogger(GzipFilter.class);
    private static final String VARY_HEADER_PARAM = "varyHeader";
    private static final String RETURN_ON_NOT_OK_PARAM = "returnOnNonOK";

    private boolean setVaryHeader;
    private boolean returnOnNonOk = true;

    /**
     * Performs initialisation.
     *
     * @param filterConfig
     */
    protected void doInit(FilterConfig filterConfig) throws Exception {
        String varyParam = filterConfig.getInitParameter(VARY_HEADER_PARAM);
        if (varyParam != null) {
            setVaryHeader = Boolean.valueOf(varyParam);
        }

        String returnOnNotOkParam = filterConfig.getInitParameter(RETURN_ON_NOT_OK_PARAM);
        if (returnOnNotOkParam != null) {
            returnOnNonOk = Boolean.valueOf(returnOnNotOkParam);
        }
    }

    /**
     * A template method that performs any Filter specific destruction tasks. Called from {@link #destroy()}
     */
    protected void doDestroy() {
        // noop
    }

    /**
     * Performs the filtering for a request.
     */
    protected void doFilter(final HttpServletRequest request, final HttpServletResponse response, final FilterChain chain)
            throws Exception {
        if (!isIncluded(request) && acceptsEncoding(request, "gzip") && !response.isCommitted()) {
            // Client accepts zipped content
            if (LOG.isDebugEnabled()) {
                LOG.debug(request.getRequestURL() + ". Writing with gzip compression");
            }

            // Create a gzip stream
            final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
            final GZIPOutputStream gzout = new GZIPOutputStream(compressed);

            // Handle the request
            final GenericResponseWrapper wrapper = new GenericResponseWrapper(response, gzout);
            wrapper.setDisableFlushBuffer(true);
            chain.doFilter(request, wrapper);
            wrapper.flush();

            gzout.close();

            // double check one more time before writing out
            // repsonse might have been committed due to error
            if (response.isCommitted()) {
                return;
            }

            // return on these special cases when content is empty or unchanged
            switch (wrapper.getStatus()) {
            case HttpServletResponse.SC_NO_CONTENT:
            case HttpServletResponse.SC_RESET_CONTENT:
            case HttpServletResponse.SC_NOT_MODIFIED:
                return;
            default:
            }

            // Saneness checks
            byte[] compressedBytes = compressed.toByteArray();
            boolean shouldGzippedBodyBeZero = ResponseUtil.shouldGzippedBodyBeZero(compressedBytes, request);
            boolean shouldBodyBeZero = ResponseUtil.shouldBodyBeZero(request, wrapper.getStatus());
            if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
                // No reason to add GZIP headers or write body if no content was written or status code specifies no
                // content
                response.setContentLength(0);
                return;
            }

            // Write the zipped body
            ResponseUtil.addGzipHeader(response);

            // Only write out header Vary as needed
            if (setVaryHeader) {
                ResponseUtil.addVaryAcceptEncoding(wrapper);
            }

            response.setContentLength(compressedBytes.length);

            response.getOutputStream().write(compressedBytes);

        } else {
            // Client does not accept zipped content - don't bother zipping
            if (LOG.isDebugEnabled()) {
                LOG.debug(request.getRequestURL() + ". Writing without gzip compression because the request does not accept gzip.");
            }
            chain.doFilter(request, response);
        }
    }

    /**
     * Checks if the request uri is an include. These cannot be gzipped.
     */
    private boolean isIncluded(final HttpServletRequest request) {
        final String uri = (String) request.getAttribute("javax.servlet.include.request_uri");
        final boolean includeRequest = !(uri == null);

        if (includeRequest && LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL() + " resulted in an include request. This is unusable, because"
                    + "the response will be assembled into the overrall response. Not gzipping.");
        }
        return includeRequest;
    }

    /**
     * Determine whether the user agent accepts GZIP encoding. This feature is part of HTTP1.1. If a browser accepts
     * GZIP encoding it will advertise this by including in its HTTP header:
     *

     *
     * Accept-Encoding: gzip
     *
     *

     * Requests which do not accept GZIP encoding fall into the following categories:
     *

     *
Old browsers, notably IE 5 on Macintosh.
     *
Internet Explorer through a proxy. By default HTTP1.1 is enabled but disabled when going through a proxy. 90%
     * of non gzip requests seen on the Internet are caused by this.
     *

     * As of September 2004, about 34% of Internet requests do not accept GZIP encoding.
     *
     * @param request
     * @return true, if the User Agent request accepts GZIP encoding
     */
    protected boolean acceptsGzipEncoding(HttpServletRequest request) {
        return acceptsEncoding(request, "gzip");
    }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/activity_vertical_margin"
        android:layout_marginBottom="@dimen/activity_vertical_margin"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginRight="@dimen/activity_horizontal_margin">

        <TextView
            android:id="@+id/name_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/message_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/name_text"/>

        <TextView
            android:id="@+id/timestamp_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@id/message_text"/>

    </RelativeLayout>

</LinearLayout>


text:
from setuptools import setup, find_packages
import glob
from imp import load_source
import os
import sys

if not hasattr(sys, 'version_info') or sys.version_info < (2, 6, 0, 'final'):
    raise SystemExit("Couchapp requires Python 2.6 or later.")

executables = []
setup_requires = []
extra = {}

couchapp = load_source("couchapp", os.path.join("couchapp", "__init__.py"))

def get_data_files():
    data_files = []
    data_files.append(('couchapp',
                       ["LICENSE", "MANIFEST.in", "NOTICE", "README.rst",
                        "THANKS"]))
    return data_files

def ordinarypath(p):
    return p and p[0] != '.' and p[-1] != '~'

def get_packages_data():
    packagedata = {'couchapp': []}

    for root in ('templates',):
        for curdir, dirs, files in os.walk(os.path.join("couchapp", root)):
            curdir = curdir.split(os.sep, 1)[1]
            dirs[:] = filter(ordinarypath, dirs)
            for f in filter(ordinarypath, files):
                f = os.path.normpath(os.path.join(curdir, f))
                packagedata['couchapp'].append(f)
    return packagedata

MODULES = ['couchapp',
           'couchapp.autopush',
           'couchapp.autopush.brownie',
           'couchapp.autopush.brownie.datastructures',
           'couchapp.autopush.pathtools',
           'couchapp.autopush.watchdog',
           'couchapp.autopush.watchdog.observers',
           'couchapp.autopush.watchdog.tricks',
           'couchapp.autopush.watchdog.utils',
           'couchapp.hooks',
           'couchapp.hooks.compress',
           'couchapp.restkit',
           'couchapp.restkit.manager',
           'couchapp.restkit.contrib',
           'couchapp.simplejson',
           'couchapp.vendors',
           'couchapp.vendors.backends',
           ]

CLASSIFIERS = ['License :: OSI Approved :: Apache Software License',
               'Intended Audience :: Developers',
               'Intended Audience :: System Administrators',
               'Development Status :: 4 - Beta',
               'Programming Language :: Python',
               'Operating System :: OS Independent',
               'Topic :: Database',
               'Topic :: Utilities',
               ]

def get_scripts():
    scripts = [os.path.join("resources", "scripts", "couchapp")]
    if os.name == "nt":
        scripts.append(os.path.join("resources", "scripts", "couchapp.bat"))
    return scripts

DATA_FILES = get_data_files()

def get_py2exe_datafiles():
    datapath = os.path.join('couchapp', 'templates')
    head, tail = os.path.split(datapath)
    d = dict(get_data_files())
    for root, dirs, files in os.walk(datapath):
        files = [os.path.join(root, filename) for filename in files]
        root = root.replace(tail, datapath)
        root = root[root.index(datapath):]
        d[root] = files
    return d.items()

if os.name == "nt" or sys.platform == "win32":
    # py2exe needs to be installed to work
    try:
        import py2exe

        # Help py2exe to find win32com.shell
        try:
            import modulefinder
            import win32com
            for p in win32com.__path__[1:]:  # Take the path to win32comext
                modulefinder.AddPackagePath("win32com", p)
            pn = "win32com.shell"
            __import__(pn)
            m = sys.modules[pn]
            for p in m.__path__[1:]:
                modulefinder.AddPackagePath(pn, p)
        except ImportError:
            raise SystemExit('You need pywin32 installed ' +
                             'http://sourceforge.net/projects/pywin32')

        # If run without args, build executables, in quiet mode.
        if len(sys.argv) == 1:
            sys.argv.append("py2exe")
            sys.argv.append("-q")

        extra['console'] = [{'script': os.path.join("resources", "scripts", "couchapp"),
                             'copyright': 'Copyright (C) 2008-2011 Benoît Chesneau and others',
                             'product_version': couchapp.__version__
                             }]

    except ImportError:
        raise SystemExit('You need py2exe installed to run Couchapp.')

    DATA_FILES = get_py2exe_datafiles()

def main():
    # read long description
    with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
        long_description = f.read()

    INSTALL_REQUIRES = ['restkit==4.2.2', 'watchdog==0.6.0']

    try:
        import json
    except ImportError:
        INSTALL_REQUIRES.append('simplejson')

    options = dict(name='Couchapp',
                   version=couchapp.__version__,
                   url='http://github.com/couchapp/couchapp/tree/master',
                   license='Apache License 2',
                   author='Benoit Chesneau',
                   author_email='benoitc@e-engura.org',
                   description='Standalone CouchDB Application Development Made Simple.',
                   long_description=long_description,
                   tests_require = ['unittest2', 'nose', 'coverage',
                                    'nose-testconfig', 'mock'],
                   test_suite="tests",
                   keywords='couchdb couchapp',
                   platforms=['any'],
                   classifiers=CLASSIFIERS,
                   packages=find_packages(),
                   data_files=DATA_FILES,
                   include_package_data=True,
                   zip_safe=False,
                   install_requires=INSTALL_REQUIRES,
                   scripts=get_scripts(),
                   options=dict(py2exe={'dll_excludes': ["kernelbase.dll",
                                                         "powrprof.dll"],
                                        'packages': ["http_parser", "restkit",
                                                     "restkit.manager",
                                                     "restkit.contrib",
                                                     "pathtools.path",
                                                     "brownie",
                                                     "brownie.datastructures",
                                                     "watchdog",
                                                     "watchdog.observers",
                                                     "watchdog.tricks",
                                                     "watchdog.utils",
                                                     "win32pdh",
                                                     "win32pdhutil",
                                                     "win32api",
                                                     "win32con",
                                                     "subprocess"
                                                     ]
                                        },
                                bdist_mpkg=dict(zipdist=True,
                                                license='LICENSE',
                                                readme='resources/macosx/Readme.html',
                                                welcome='resources/macosx/Welcome.html')
                                )
                   )
    options.update(extra)
    setup(**options)

if __name__ == "__main__":
    main()


text:
#ifndef FILTER_H
#define FILTER_H

/** \file

  Digital filter

  This object stores a digital filter of order \f$n\f$.
  It contains the following data:
    - \f$ n*1 b_i \f$ feedforward coefficients
    - \f$ n*1 a_i \f$ feedback coefficients
    - \f$ n*c x_i \f$ input signal
    - \f$ n*c y_i \f$ output signal

  For convenience, the samplerate of the input signal is also stored in the
  object.

  Feedforward and feedback parameters can be modified using
  aubio_filter_get_feedback() and aubio_filter_get_feedforward().

  The function aubio_filter_do_outplace() computes the following output signal
  \f$ y[n] \f$ from the input signal \f$ x[n] \f$:

  \f{eqnarray*}{
     y[n] = b_0 x[n] & + & b_1 x[n-1] + b_2 x[n-2] + ... + b_P x[n-P] \\
                     & - & a_1 y[n-1] - a_2 y[n-2] - ... - a_P y[n-P] \\
  \f}

  The function aubio_filter_do() executes the same computation but modifies
  directly the input signal (in-place).

  The function aubio_filter_do_filtfilt() version runs the filter twice, first
  forward then backward, to compensate with the phase shifting of the forward
  operation.

  Some convenience functions are provided:
    - new_aubio_filter_a_weighting() and aubio_filter_set_a_weighting(),
    - new_aubio_filter_c_weighting() and aubio_filter_set_c_weighting().
    - new_aubio_filter_biquad() and aubio_filter_set_biquad().

  \example temporal/test-filter.c

*/

#ifdef __cplusplus
extern "C" {
#endif

/** Digital filter

*/
typedef struct _aubio_filter_t aubio_filter_t;

/** filter input vector (in-place)

  \param f filter object as returned by new_aubio_filter()
  \param in input vector to filter

*/
void aubio_filter_do (aubio_filter_t * f, fvec_t * in);

/** filter input vector (out-of-place)

  \param f filter object as returned by new_aubio_filter()
  \param in input vector to filter
  \param out output vector to store filtered input

*/
void aubio_filter_do_outplace (aubio_filter_t * f, fvec_t * in, fvec_t * out);

/** filter input vector forward and backward

  \param f ::aubio_filter_t object as returned by new_aubio_filter()
  \param in ::fvec_t input vector to filter
  \param tmp memory space to use for computation

*/
void aubio_filter_do_filtfilt (aubio_filter_t * f, fvec_t * in, fvec_t * tmp);

/** returns a pointer to feedback coefficients \f$ a_i \f$

  \param f filter object to get parameters from

  \return a pointer to the \f$ a_0 ... a_i ... a_P \f$ coefficients

*/
lvec_t *aubio_filter_get_feedback (aubio_filter_t * f);

/** returns a pointer to feedforward coefficients \f$ b_i \f$

  \param f filter object to get coefficients from

  \return a pointer to the \f$ b_0 ... b_i ... b_P \f$ coefficients

*/
lvec_t *aubio_filter_get_feedforward (aubio_filter_t * f);

/** get order of the filter

  \param f filter to get order from

  \return the order of the filter

*/
uint_t aubio_filter_get_order (aubio_filter_t * f);

/** get sampling rate of the filter

  \param f filter to get sampling rate from

  \return the sampling rate of the filter, in Hz

*/
uint_t aubio_filter_get_samplerate (aubio_filter_t * f);

/** get sampling rate of the filter

  \param f filter to get sampling rate from
  \param samplerate sample rate to set the filter to

  \return the sampling rate of the filter, in Hz

*/
uint_t aubio_filter_set_samplerate (aubio_filter_t * f, uint_t samplerate);

/** reset filter memory

  \param f filter object as returned by new_aubio_filter()

*/
void aubio_filter_do_reset (aubio_filter_t * f);

/** create new filter object

  This function creates a new ::aubio_filter_t object, given the order of the
  filter.

  \param order order of the filter (number of coefficients)

  \return the newly created filter object

*/
aubio_filter_t *new_aubio_filter (uint_t order);

/** delete a filter object

  \param f filter object to delete

*/
void del_aubio_filter (aubio_filter_t * f);

#ifdef __cplusplus
}
#endif

#endif /*FILTER_H*/


text:
<?xml version="1.0"?>
<enunciate label="ifyouwannabecool"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:noNamespaceSchemaLocation="http://enunciate.webcohesion.com/schemas/enunciate-1.30.xsd">
  <deployment host="www.ifyouwannabecool.com" context="api"/>
  <namespaces>
    <namespace id="api" uri="http://api.ifyouwannabecool.com/"/>
    <namespace id="link" uri="http://api.ifyouwannabecool.com/link"/>
    <namespace id="persona" uri="http://api.ifyouwannabecool.com/persona"/>
  </namespaces>
  <modules>
    <docs splashPackage="com.ifyouwannabecool.api" title="If You Wanna Be Cool API" copyright="IfYouWannaBeCool.com">
      <download name="License" file="LICENSE.txt" description="The license file governing the use of this API."/>
    </docs>
  </modules>
</enunciate>


text:
'''
Created on Jan 10, 2012

@author: tjhunter

All the data structures as used in the python files.
'''

class Coordinate(object):
  """ A geolocation representation.
  """
  def __init__(self, lat, lng):
    self.lat = lat
    self.lon = lng

  def __eq__(self, other):
    return self.lat == other.lat and self.lon == other.lon

  def __ne__(self, other):
    return not self.__eq__(other)

class Spot(object):
  """ Spot representation.
  """

  def __init__(self, link_id, offset, coordinate=None):
    self.linkId = link_id
    self.offset = offset
    self.coordinate = coordinate

  def __eq__(self, other):
    return self.linkId == other.linkId and int(10 * self.offset) == int(10 * other.offset)

  def __ne__(self, other):
    return not self.__eq__(other)

  def __repr__(self):
    return "Spot[%s, %.1f]" % (str(self.linkId), self.offset)

class Route(object):
  """ Representation of a netconfig.Route
  """

  def __init__(self, links, spots, geometry=None):
    self.link_ids = links
    self.spots = spots
    self.geometry = geometry
    #self.length = sum([link.length for link in self.link_ids[:-1]]) - self.firstSpot.offset + self.lastSpot.offset

  @property
  def firstSpot(self):
    return self.spots[0]

  @property
  def lastSpot(self):
    return self.spots[-1]

  @staticmethod
  def fromPair(links, start_spot, end_spot):
    return Spot(links, [start_spot, end_spot])

  def __repr__(self):
    return "Route[%s,link_ids=%s,%s]" % (str(self.firstSpot), str(self.link_ids), str(self.lastSpot))

class TSpot(object):
  """ A timed spot.
  """
  def __init__(self, spot, vehicle_id, time,
               hired=None, speed=None, obsCoordinate=None):
    self.spot = spot
    self.id = vehicle_id
    self.time = time
    self.hired = hired
    self.speed = speed
    self.obsCoordinate = obsCoordinate

  def __repr__(self):
    return "TSpot[%s,%s, %s]" % (str(self.spot), str(self.time), str(self.id))

class RouteTT(object):
  """ Python representation of the RouteTT object
  """

  def __init__(self, route, start_time, end_time, vehicle_id=None):
    self.route = route
    self.startTime = start_time
    self.endTime = end_time
    self.id = vehicle_id
    self.tt = (self.endTime - self.startTime).total_seconds()
    #self.vel = self.route.length / self.tt

  def __repr__(self):
    return "RouteTT[%s, %s, %s, %s]" % (str(self.id), str(self.startTime), str(self.endTime), str(self.route))

# TODO(?) rename to something else
class Point_pts(object):
  """ A point in the time-space diagram associated with time, space and speed
  """

  def __init__(self, space, time, speed):
    self.space = space
    self.time = time
    self.speed = speed

class CutTrajectory(object):
  """ A simplified trajectory for the stop/go model.
  """

  def __init__(self, rtts):
    """
    Arguments:
     - rtts: list of RouteTT objects
    """
    self.pieces = rtts
    self.numPieces = len(self.pieces)


text:
## The Manifest Format

The `Cargo.toml` file for each package is called its *manifest*. Every manifest
file consists of the following sections:

* [`cargo-features`](unstable.md) — Unstable, nightly-only features.
* [`[package]`](#the-package-section) — Defines a package.
  * [`name`](#the-name-field) — The name of the package.
  * [`version`](#the-version-field) — The version of the package.
  * [`authors`](#the-authors-field) — The authors of the package.
  * [`edition`](#the-edition-field) — The Rust edition.
  * [`description`](#the-description-field) — A description of the package.
  * [`documentation`](#the-documentation-field) — URL of the package documentation.
  * [`readme`](#the-readme-field) — Path to the package's README file.
  * [`homepage`](#the-homepage-field) — URL of the package homepage.
  * [`repository`](#the-repository-field) — URL of the package source repository.
  * [`license`](#the-license-and-license-file-fields) — The package license.
  * [`license-file`](#the-license-and-license-file-fields) — Path to the text of the license.
  * [`keywords`](#the-keywords-field) — Keywords for the package.
  * [`categories`](#the-categories-field) — Categories of the package.
  * [`workspace`](#the-workspace-field) — Path to the workspace for the package.
  * [`build`](#the-build-field) — Path to the package build script.
  * [`links`](#the-links-field) — Name of the native library the package links with.
  * [`exclude`](#the-exclude-and-include-fields) — Files to exclude when publishing.
  * [`include`](#the-exclude-and-include-fields) — Files to include when publishing.
  * [`publish`](#the-publish-field) — Can be used to prevent publishing the package.
  * [`metadata`](#the-metadata-table) — Extra settings for external tools.
  * [`default-run`](#the-default-run-field) — The default binary to run by [`cargo run`].
  * [`autobins`](cargo-targets.md#target-auto-discovery) — Disables binary auto discovery.
  * [`autoexamples`](cargo-targets.md#target-auto-discovery) — Disables example auto discovery.
  * [`autotests`](cargo-targets.md#target-auto-discovery) — Disables test auto discovery.
  * [`autobenches`](cargo-targets.md#target-auto-discovery) — Disables bench auto discovery.
* Target tables: (see [configuration](cargo-targets.md#configuring-a-target) for settings)
  * [`[lib]`](cargo-targets.md#library) — Library target settings.
  * [`[[bin]]`](cargo-targets.md#binaries) — Binary target settings.
  * [`[[example]]`](cargo-targets.md#examples) — Example target settings.
  * [`[[test]]`](cargo-targets.md#tests) — Test target settings.
  * [`[[bench]]`](cargo-targets.md#benchmarks) — Benchmark target settings.
* Dependency tables:
  * [`[dependencies]`](specifying-dependencies.md) — Package library dependencies.
  * [`[dev-dependencies]`](specifying-dependencies.md#development-dependencies) — Dependencies for examples, tests, and benchmarks.
  * [`[build-dependencies]`](specifying-dependencies.md#build-dependencies) — Dependencies for build scripts.
  * [`[target]`](specifying-dependencies.md#platform-specific-dependencies) — Platform-specific dependencies.
* [`[badges]`](#the-badges-section) — Badges to display on [crates.io].
* [`[features]`](features.md) — Conditional compilation features.
* [`[patch]`](overriding-dependencies.md#the-patch-section) — Override dependencies.
* [`[replace]`](overriding-dependencies.md#the-replace-section) — Override dependencies (deprecated).
* [`[profile]`](profiles.md) — Compiler settings and optimizations.
* [`[workspace]`](workspaces.md) — The workspace definition.

### The `[package]` section

The first section in a `Cargo.toml` is `[package]`.

```toml
[package]
name = "hello_world" # the name of the package
version = "0.1.0"    # the current version, obeying semver
authors = ["Alice <a@example.com>", "Bob <b@example.com>"]
```

The only fields required by Cargo are [`name`](#the-name-field) and
[`version`](#the-version-field). If publishing to a registry, the registry may
require additional fields. See the notes below and [the publishing
chapter][publishing] for requirements for publishing to [crates.io].

#### The `name` field

The package name is an identifier used to refer to the package. It is used
when listed as a dependency in another package, and as the default name of
inferred lib and bin targets.

The name must use only [alphanumeric] characters or `-` or `_`, and cannot be empty.
Note that [`cargo new`] and [`cargo init`] impose some additional restrictions on
the package name, such as enforcing that it is a valid Rust identifier and not
a keyword. [crates.io] imposes even more restrictions, such as
enforcing only ASCII characters, not a reserved name, not a special Windows
name such as "nul", is not too long, etc.

[alphanumeric]: ../../std/primitive.char.html#method.is_alphanumeric

#### The `version` field

Cargo bakes in the concept of [Semantic
Versioning](https://semver.org/), so make sure you follow some basic rules:

* Before you reach 1.0.0, anything goes, but if you make breaking changes,
  increment the minor version. In Rust, breaking changes include adding fields to
  structs or variants to enums.
* After 1.0.0, only make breaking changes when you increment the major version.
  Don't break the build.
* After 1.0.0, don't add any new public API (no new `pub` anything) in patch-level
  versions. Always increment the minor version if you add any new `pub` structs,
  traits, fields, types, functions, methods or anything else.
* Use version numbers with three numeric parts such as 1.0.0 rather than 1.0.

#### The `authors` field

The `authors` field lists people or organizations that are considered the
"authors" of the package. The exact meaning is open to interpretation — it may
list the original or primary authors, current maintainers, or owners of the
package. These names will be listed on the crate's page on
[crates.io]. An optional email address may be included within angled
brackets at the end of each author.

> **Note**: [crates.io] requires at least one author to be listed.

#### The `edition` field

You can opt in to a specific [Rust Edition] for your package with the
`edition` key in `Cargo.toml`. If you don't specify the edition, it will
default to 2015.

```toml
[package]
# ...
edition = '2018'
```

The `edition` key affects which edition your package is compiled with. Cargo
will always generate packages via [`cargo new`] with the `edition` key set to the
latest edition. Setting the `edition` key in `[package]` will affect all
targets/crates in the package, including test suites, benchmarks, binaries,
examples, etc.

#### The `description` field

The description is a short blurb about the package. [crates.io] will display
this with your package. This should be plain text (not Markdown).

```toml
[package]
# ...
description = "A short description of my package"
```

> **Note**: [crates.io] requires the `description` to be set.

#### The `documentation` field

The `documentation` field specifies a URL to a website hosting the crate's
documentation. If no URL is specified in the manifest file, [crates.io] will
automatically link your crate to the corresponding [docs.rs] page.

```toml
[package]
# ...
documentation = "https://docs.rs/bitflags"
```

#### The `readme` field

The `readme` field should be the path to a file in the package root (relative
to this `Cargo.toml`) that contains general information about the package.
This file will be transferred to the registry when you publish. [crates.io]
will interpret it as Markdown and render it on the crate's page.

```toml
[package]
# ...
readme = "README.md"
```

If no value is specified for this field, and a file named `README.md`,
`README.txt` or `README` exists in the package root, then the name of that
file will be used. You can suppress this behavior by setting this field to
`false`. If the field is set to `true`, a default value of `README.md` will
be assumed.

#### The `homepage` field

The `homepage` field should be a URL to a site that is the home page for your
package.

```toml
[package]
# ...
homepage = "https://serde.rs/"
```

#### The `repository` field

The `repository` field should be a URL to the source repository for your
package.

```toml
[package]
# ...
repository = "https://github.com/rust-lang/cargo/"
```

#### The `license` and `license-file` fields

The `license` field contains the name of the software license that the package
is released under. The `license-file` field contains the path to a file
containing the text of the license (relative to this `Cargo.toml`).

[crates.io] interprets the `license` field as an [SPDX 2.1 license
expression][spdx-2.1-license-expressions]. The name must be a known license
from the [SPDX license list 3.6][spdx-license-list-3.6]. Parentheses are not
currently supported. See the [SPDX site] for more information.

SPDX license expressions support AND and OR operators to combine multiple
licenses.[^slash]

```toml
[package]
# ...
license = "MIT OR Apache-2.0"
```

Using `OR` indicates the user may choose either license. Using `AND` indicates
the user must comply with both licenses simultaneously. The `WITH` operator
indicates a license with a special exception. Some examples:

* `MIT OR Apache-2.0`
* `LGPL-2.1-only AND MIT AND BSD-2-Clause`
* `GPL-2.0-or-later WITH Bison-exception-2.2`

If a package is using a nonstandard license, then the `license-file` field may
be specified in lieu of the `license` field.

```toml
[package]
# ...
license-file = "LICENSE.txt"
```

> **Note**: [crates.io] requires either `license` or `license-file` to be set.

[^slash]: Previously multiple licenses could be separated with a `/`, but that
usage is deprecated.

#### The `keywords` field

The `keywords` field is an array of strings that describe this package. This
can help when searching for the package on a registry, and you may choose any
words that would help someone find this crate.

```toml
[package]
# ...
keywords = ["gamedev", "graphics"]
```

> **Note**: [crates.io] has a maximum of 5 keywords. Each keyword must be
> ASCII text, start with a letter, and only contain letters, numbers, `_` or
> `-`, and have at most 20 characters.

#### The `categories` field

The `categories` field is an array of strings of the categories this package
belongs to.

```toml
categories = ["command-line-utilities", "development-tools::cargo-plugins"]
```

> **Note**: [crates.io] has a maximum of 5 categories. Each category should
> match one of the strings available at <https://crates.io/category_slugs>, and
> must match exactly.

#### The `workspace` field

The `workspace` field can be used to configure the workspace that this package
will be a member of. If not specified this will be inferred as the first
Cargo.toml with `[workspace]` upwards in the filesystem. Setting this is
useful if the member is not inside a subdirectory of the workspace root.

```toml
[package]
# ...
workspace = "path/to/workspace/root"
```

This field cannot be specified if the manifest already has a `[workspace]`
table defined. That is, a crate cannot both be a root crate in a workspace
(contain `[workspace]`) and also be a member crate of another workspace
(contain `package.workspace`).

For more information, see the [workspaces chapter](workspaces.md).

#### The `build` field

The `build` field specifies a file in the package root which is a [build
script] for building native code. More information can be found in the [build
script guide][build script].

[build script]: build-scripts.md

```toml
[package]
# ...
build = "build.rs"
```

The default is `"build.rs"`, which loads the script from a file named
`build.rs` in the root of the package. Use `build = "custom_build_name.rs"` to
specify a path to a different file or `build = false` to disable automatic
detection of the build script.

#### The `links` field

The `links` field specifies the name of a native library that is being linked
to. More information can be found in the [`links`][links] section of the build
script guide.

[links]: build-scripts.md#the-links-manifest-key

```toml
[package]
# ...
links = "foo"
```

#### The `exclude` and `include` fields

You can explicitly specify that a set of file patterns should be ignored or
included for the purposes of packaging. The patterns specified in the
`exclude` field identify a set of files that are not included, and the
patterns in `include` specify files that are explicitly included.

The patterns should be [gitignore]-style patterns. Briefly:

- `foo` matches any file or directory with the name `foo` anywhere in the
  package. This is equivalent to the pattern `**/foo`.
- `/foo` matches any file or directory with the name `foo` only in the root of
  the package.
- `foo/` matches any *directory* with the name `foo` anywhere in the package.
- Common glob patterns like `*`, `?`, and `[]` are supported:
  - `*` matches zero or more characters except `/`.  For example, `*.html`
    matches any file or directory with the `.html` extension anywhere in the
    package.
  - `?` matches any character except `/`. For example, `foo?` matches `food`,
    but not `foo`.
  - `[]` allows for matching a range of characters. For example, `[ab]`
    matches either `a` or `b`. `[a-z]` matches letters a through z.
- `**/` prefix matches in any directory. For example, `**/foo/bar` matches the
  file or directory `bar` anywhere that is directly under directory `foo`.
- `/**` suffix matches everything inside. For example, `foo/**` matches all
  files inside directory `foo`, including all files in subdirectories below
  `foo`.
- `/**/` matches zero or more directories. For example, `a/**/b` matches
  `a/b`, `a/x/b`, `a/x/y/b`, and so on.
- `!` prefix negates a pattern. For example, a pattern of `src/**.rs` and
  `!foo.rs` would match all files with the `.rs` extension inside the `src`
  directory, except for any file named `foo.rs`.

If git is being used for a package, the `exclude` field will be seeded with
the `gitignore` settings from the repository.

```toml
[package]
# ...
exclude = ["build/**/*.o", "doc/**/*.html"]
```

```toml
[package]
# ...
include = ["src/**/*", "Cargo.toml"]
```

The options are mutually exclusive: setting `include` will override an
`exclude`. Note that `include` must be an exhaustive list of files as otherwise
necessary source files may not be included. The package's `Cargo.toml` is
automatically included.

The include/exclude list is also used for change tracking in some situations.
For targets built with `rustdoc`, it is used to determine the list of files to
track to determine if the target should be rebuilt. If the package has a
[build script] that does not emit any `rerun-if-*` directives, then the
include/exclude list is used for tracking if the build script should be re-run
if any of those files change.

[gitignore]: https://git-scm.com/docs/gitignore

#### The `publish` field

The `publish` field can be used to prevent a package from being published to a
package registry (like *crates.io*) by mistake, for instance to keep a package
private in a company.

```toml
[package]
# ...
publish = false
```

The value may also be an array of strings which are registry names that are
allowed to be published to.

```toml
[package]
# ...
publish = ["some-registry-name"]
```

If publish array contains a single registry, `cargo publish` command will use
it when `--registry` flag is not specified.

#### The `metadata` table

Cargo by default will warn about unused keys in `Cargo.toml` to assist in
detecting typos and such. The `package.metadata` table, however, is completely
ignored by Cargo and will not be warned about. This section can be used for
tools which would like to store package configuration in `Cargo.toml`. For
example:

```toml
[package]
name = "..."
# ...

# Metadata used when generating an Android APK, for example.
[package.metadata.android]
package-name = "my-awesome-android-app"
assets = "path/to/static"
```

There is a similar table at the workspace level at
[`workspace.metadata`][workspace-metadata]. While cargo does not specify a
format for the content of either of these tables, it is suggested that
external tools may wish to use them in a consistent fashion, such as referring
to the data in `workspace.metadata` if data is missing from `package.metadata`,
if that makes sense for the tool in question.

[workspace-metadata]: workspaces.md#the-workspacemetadata-table

#### The `default-run` field

The `default-run` field in the `[package]` section of the manifest can be used
to specify a default binary picked by [`cargo run`]. For example, when there is
both `src/bin/a.rs` and `src/bin/b.rs`:

```toml
[package]
default-run = "a"
```

### The `[badges]` section

[crates.io] can display various badges for build status, test coverage, etc. for
each crate. All badges are optional.

- The badges pertaining to build status that are currently available are
  Appveyor, CircleCI, Cirrus CI, GitLab, Azure DevOps, Travis CI and Bitbucket
  Pipelines.
- Available badges pertaining to code test coverage are Codecov and Coveralls.
- There are also maintenance-related badges based on isitmaintained.com
  which state the issue resolution time, percent of open issues, and future
  maintenance intentions.

Most badge specifications require a `repository` key. It is expected to be in
`user/repo` format.

```toml
[badges]

# Appveyor: `repository` is required. `branch` is optional; default is `master`
# `service` is optional; valid values are `github` (default), `bitbucket`, and
# `gitlab`; `id` is optional; you can specify the appveyor project id if you
# want to use that instead. `project_name` is optional; use when the repository
# name differs from the appveyor project name.
appveyor = { repository = "...", branch = "master", service = "github" }

# Circle CI: `repository` is required. `branch` is optional; default is `master`
circle-ci = { repository = "...", branch = "master" }

# Cirrus CI: `repository` is required. `branch` is optional; default is `master`
cirrus-ci = { repository = "...", branch = "master" }

# GitLab: `repository` is required. `branch` is optional; default is `master`
gitlab = { repository = "...", branch = "master" }

# Azure DevOps: `project` is required. `pipeline` is required. `build` is optional; default is `1`
# Note: project = `organization/project`, pipeline = `name_of_pipeline`, build = `definitionId`
azure-devops = { project = "...", pipeline = "...", build="2" }

# Travis CI: `repository` in format "<user>/<project>" is required.
# `branch` is optional; default is `master`
travis-ci = { repository = "...", branch = "master" }

# Bitbucket Pipelines: `repository` is required. `branch` is required
bitbucket-pipelines = { repository = "...", branch = "master" }

# Codecov: `repository` is required. `branch` is optional; default is `master`
# `service` is optional; valid values are `github` (default), `bitbucket`, and
# `gitlab`.
codecov = { repository = "...", branch = "master", service = "github" }

# Coveralls: `repository` is required. `branch` is optional; default is `master`
# `service` is optional; valid values are `github` (default) and `bitbucket`.
coveralls = { repository = "...", branch = "master", service = "github" }

# Is it maintained resolution time: `repository` is required.
is-it-maintained-issue-resolution = { repository = "..." }

# Is it maintained percentage of open issues: `repository` is required.
is-it-maintained-open-issues = { repository = "..." }

# Maintenance: `status` is required. Available options are:
# - `actively-developed`: New features are being added and bugs are being fixed.
# - `passively-maintained`: There are no plans for new features, but the maintainer intends to
#   respond to issues that get filed.
# - `as-is`: The crate is feature complete, the maintainer does not intend to continue working on
#   it or providing support, but it works for the purposes it was designed for.
# - `experimental`: The author wants to share it with the community but is not intending to meet
#   anyone's particular use case.
# - `looking-for-maintainer`: The current maintainer would like to transfer the crate to someone
#   else.
# - `deprecated`: The maintainer does not recommend using this crate (the description of the crate
#   can describe why, there could be a better solution available or there could be problems with
#   the crate that the author does not want to fix).
# - `none`: Displays no badge on crates.io, since the maintainer has not chosen to specify
#   their intentions, potential crate users will need to investigate on their own.
maintenance = { status = "..." }
```

### Dependency sections

See the [specifying dependencies page](specifying-dependencies.md) for
information on the `[dependencies]`, `[dev-dependencies]`,
`[build-dependencies]`, and target-specific `[target.*.dependencies]` sections.

### The `[profile.*]` sections

The `[profile]` tables provide a way to customize compiler settings such as
optimizations and debug settings. See [the Profiles chapter](profiles.md) for
more detail.

[`cargo init`]: ../commands/cargo-init.md
[`cargo new`]: ../commands/cargo-new.md
[`cargo run`]: ../commands/cargo-run.md
[crates.io]: https://crates.io/
[docs.rs]: https://docs.rs/
[publishing]: publishing.md
[Rust Edition]: ../../edition-guide/index.html
[spdx-2.1-license-expressions]: https://spdx.org/spdx-specification-21-web-version#h.jxpfx0ykyb60
[spdx-license-list-3.6]: https://github.com/spdx/license-list-data/tree/v3.6
[SPDX site]: https://spdx.org/license-list


text:
import { exec, safeStringifyJson } from "builder-util"
import { unlinkIfExists } from "builder-util/out/fs"
import { emptyDir, ensureDir } from "fs-extra"
import { promises as fs } from "fs"
import { homedir } from "os"
import * as path from "path"
import pathSorter from "path-sort"

export class WineManager {
  wineDir: string | null = null
  private winePreparePromise: Promise<any> | null = null

  private env: any

  userDir: string | null = null

  async prepare() {
    if (this.env != null) {
      return
    }

    this.wineDir = path.join(homedir(), "wine-test")

    const env = process.env
    const user = env.SUDO_USER || env.LOGNAME || env.USER || env.LNAME || env.USERNAME || (env.HOME === "/root" ? "root" : null)
    if (user == null) {
      throw new Error(`Cannot determinate user name: ${safeStringifyJson(env)}`)
    }

    this.userDir = path.join(this.wineDir, "drive_c", "users", user)

    this.winePreparePromise = this.prepareWine(this.wineDir)
    this.env = await this.winePreparePromise
  }

  exec(...args: Array<string>) {
    return exec("wine", args, {env: this.env})
  }

  async prepareWine(wineDir: string) {
    await emptyDir(wineDir)
    //noinspection SpellCheckingInspection
    const env = {
      ...process.env,
      WINEDLLOVERRIDES: "winemenubuilder.exe=d",
      WINEPREFIX: wineDir,
    }

    await exec("wineboot", ["--init"], {env})

    // regedit often doesn't modify correctly
    let systemReg = await fs.readFile(path.join(wineDir, "system.reg"), "utf8")
    systemReg = systemReg.replace('"CSDVersion"="Service Pack 3"', '"CSDVersion"=" "')
    systemReg = systemReg.replace('"CurrentBuildNumber"="2600"', '"CurrentBuildNumber"="10240"')
    systemReg = systemReg.replace('"CurrentVersion"="5.1"', '"CurrentVersion"="10.0"')
    systemReg = systemReg.replace('"ProductName"="Microsoft Windows XP"', '"ProductName"="Microsoft Windows 10"')
    // noinspection SpellCheckingInspection
    systemReg = systemReg.replace('"CSDVersion"=dword:00000300', '"CSDVersion"=dword:00000000')
    await fs.writeFile(path.join(wineDir, "system.reg"), systemReg)

    // remove links to host OS
    const userDir = this.userDir!!
    const desktopDir = path.join(userDir, "Desktop")
    await Promise.all([
      unlinkIfExists(desktopDir),
      unlinkIfExists(path.join(userDir, "My Documents")),
      unlinkIfExists(path.join(userDir, "My Music")),
      unlinkIfExists(path.join(userDir, "My Pictures")),
      unlinkIfExists(path.join(userDir, "My Videos")),
    ])

    await ensureDir(desktopDir)
    return env
  }
}

enum ChangeType {
  ADDED, REMOVED, NO_CHANGE
}

export function diff(oldList: Array<string>, newList: Array<string>, rootDir: string) {
  const delta: any = {
    added: [],
    deleted: [],
  }
  const deltaMap = new Map<string, ChangeType>()
  // const objHolder = new Set(oldList)
  for (const item of oldList) {
    deltaMap.set(item, ChangeType.REMOVED)
  }

  for (const item of newList) {
    // objHolder.add(item)
    const d = deltaMap.get(item)
    if (d === ChangeType.REMOVED) {
      deltaMap.set(item, ChangeType.NO_CHANGE)
    }
    else {
      deltaMap.set(item, ChangeType.ADDED)
    }
  }

  for (const [item, changeType] of deltaMap.entries()) {
    if (changeType === ChangeType.REMOVED) {
      delta.deleted.push(item.substring(rootDir.length + 1))
    }
    else if (changeType === ChangeType.ADDED) {
      delta.added.push(item.substring(rootDir.length + 1))
    }
  }

  delta.added = pathSorter(delta.added)
  delta.deleted = pathSorter(delta.deleted)
  return delta
}