text:
Console application for logging CPU temperature with [Notebook FanControl ServiceClient](http://www.computerbase.de/forum/showthread.php?t=1070494).

Download and install Notebook FanControl and make sure the backend service is running.

redpajama_set_name: RedPajamaGithub


text:
package org.innovateuk.ifs.finance.service;

import org.innovateuk.ifs.commons.service.BaseRestService;
import org.innovateuk.ifs.commons.service.ServiceResult;
import org.innovateuk.ifs.finance.resource.OrganisationFinancesKtpYearsResource;
import org.innovateuk.ifs.finance.resource.OrganisationFinancesWithGrowthTableResource;
import org.innovateuk.ifs.finance.resource.OrganisationFinancesWithoutGrowthTableResource;
import org.springframework.stereotype.Service;

import static java.lang.String.format;

/**
 * A rest service to support the Your organisation pages.
 */
@Service
public class ApplicationYourOrganisationRestServiceImpl extends BaseRestService implements ApplicationYourOrganisationRestService {
    private String baseUrl = "/application/%d/organisation/%d/finance";

    @Override
    public ServiceResult<OrganisationFinancesWithGrowthTableResource> getOrganisationFinancesWithGrowthTable(
            long applicationId,
            long organisationId) {

        return getWithRestResult(format(baseUrl + "/with-growth-table", applicationId, organisationId),
                OrganisationFinancesWithGrowthTableResource.class).
                toServiceResult();
    }

    @Override
    public ServiceResult<OrganisationFinancesWithoutGrowthTableResource> getOrganisationFinancesWithoutGrowthTable(
            long applicationId,
            long organisationId) {

        return getWithRestResult(format(baseUrl + "/without-growth-table", applicationId, organisationId),
                OrganisationFinancesWithoutGrowthTableResource.class).
                toServiceResult();
    }

    @Override
    public ServiceResult<OrganisationFinancesKtpYearsResource> getOrganisationKtpYears(
            long applicationId,
            long organisationId) {

        return getWithRestResult(format(baseUrl + "/ktp-financial-years", applicationId, organisationId),
                OrganisationFinancesKtpYearsResource.class).
                toServiceResult();
    }

    @Override
    public ServiceResult<Void> updateOrganisationFinancesWithGrowthTable(
            long applicationId,
            long organisationId,
            OrganisationFinancesWithGrowthTableResource finances) {

        return postWithRestResult(format(baseUrl + "/with-growth-table", applicationId, organisationId), finances,
                Void.class).
                toServiceResult();
    }

    @Override
    public ServiceResult<Void> updateOrganisationFinancesWithoutGrowthTable(
            long applicationId,
            long organisationId,
            OrganisationFinancesWithoutGrowthTableResource finances) {

        return postWithRestResult(format(baseUrl + "/without-growth-table", applicationId, organisationId), finances, Void.class).
                toServiceResult();
    }

    @Override
    public ServiceResult<Void> updateOrganisationFinancesKtpYears(
            long applicationId,
            long organisationId,
            OrganisationFinancesKtpYearsResource finances) {

        return postWithRestResult(format(baseUrl + "/ktp-financial-years", applicationId, organisationId), finances, Void.class).
                toServiceResult();
    }
}


text:
package uk.gov.dvsa.ui.pages.vts.ChangeDetails;

import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import uk.gov.dvsa.framework.config.webdriver.MotAppDriver;
import uk.gov.dvsa.helper.FormDataHelper;

public class ChangeDetailsEmailPage extends ChangeDetailsPage {
    public static final String PAGE_TITLE = "Change email address";
    public static final String PATH = "/vehicle-testing-station/%s/email/change";

    @FindBy (id = "email") private WebElement emailField;

    public ChangeDetailsEmailPage(MotAppDriver driver) {
        super(driver, PAGE_TITLE);
    }

    public ChangeDetailsEmailPage inputContactDetailsEmail(String newEmail) {
        FormDataHelper.enterText(emailField, newEmail);
        return this;
    }
}


text:
<template class="ux-card__content">
  <slot></slot>
</template>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Parmelia pseudofallax Gyeln.

### Remarks
null


text:
@class PIRUser;

@interface PIRBankAccount : NSManagedObject

@property (nonatomic, retain) NSString * accountID;
@property (nonatomic, retain) NSString * accountNumber;
@property (nonatomic, retain) NSNumber * accountType;
@property (nonatomic, retain) NSString * bankName;
@property (nonatomic, retain) NSString * country;
@property (nonatomic, retain) NSNumber * isDefault;
@property (nonatomic, retain) NSString * routingNumber;
@property (nonatomic, retain) NSNumber * status;
@property (nonatomic, retain) NSString * pendingVerificationID;
@property (nonatomic, retain) NSNumber * isVerified;
@property (nonatomic, retain) PIRUser *user;

@end


text:
package cz.skaut.warehousemanager.soap;

import org.simpleframework.xml.Element;
import org.simpleframework.xml.Path;
import org.simpleframework.xml.Root;

import cz.skaut.warehousemanager.WarehouseApplication;
import cz.skaut.warehousemanager.helper.C;

@Root(name = "soap:Envelope")
public class ItemInventory extends BaseRequest {

	@Path("soap:Body/WarehouseItemInventoryAll/warehouseItemInventoryAllInput")
	@Element(name = "ID_Application")
	private String applicationID;

	@Path("soap:Body/WarehouseItemInventoryAll/warehouseItemInventoryAllInput")
	@Element(name = "ID_WarehouseItem")
	private long id;

	@Path("soap:Body/WarehouseItemInventoryAll/warehouseItemInventoryAllInput")
	@Element(name = "ID_Login")
	private String loginID;

	public ItemInventory(long itemId) {
		applicationID = C.APPLICATION_ID;
		id = itemId;
		loginID = WarehouseApplication.getPrefs().getString(C.USER_TOKEN, "");
	}
}


text:
package org.codehaus.groovy.grails.commons.metaclass;

/**
 * Abstract class that provides default implementation for isArgumentsMatch.
 *
 * @author Graeme Rocher
 * @since 0.2
 */
public abstract class AbstractDynamicConstructor implements DynamicConstructor {

    private Class<?>[] argumentTypes;

    /**
     * Takes an array of types required to match this constructor.
     *
     * @param argumentTypes The argument types
     */
    public AbstractDynamicConstructor(Class<?>[] argumentTypes) {
        this.argumentTypes = argumentTypes;
    }

    /**
     * @return True if the arguments types match those specified in the constructor
     */
    public boolean isArgumentsMatch(Object[] args) {
        if (args.length != argumentTypes.length) {
            return false;
        }

        for (int i = 0; i < args.length; i++) {
            if (!args[i].getClass().equals(argumentTypes[i])) {
                return false;
            }
        }
        return true;
    }
}


text:
package io.datarouter.client.hbase.config;

import javax.inject.Inject;
import javax.inject.Singleton;

import io.datarouter.client.hbase.web.HBaseHandler;
import io.datarouter.storage.tag.Tag;
import io.datarouter.web.dispatcher.BaseRouteSet;
import io.datarouter.web.dispatcher.DispatchRule;
import io.datarouter.web.user.role.DatarouterUserRole;

@Singleton
public class DatarouterHBaseRouteSet extends BaseRouteSet{

	@Inject
	public DatarouterHBaseRouteSet(DatarouterHBasePaths paths){
		super(paths.datarouter.clients.hbase);
		handle(paths.datarouter.clients.hbase).withHandler(HBaseHandler.class);
	}

	@Override
	protected DispatchRule applyDefault(DispatchRule rule){
		return rule
				.allowRoles(DatarouterUserRole.DATAROUTER_ADMIN)
				.withTag(Tag.DATAROUTER);
	}

}


text:
package com.bluesnap.androidapi.views.adapters;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.bluesnap.androidapi.R;
import com.bluesnap.androidapi.models.StateListObject;

import java.util.ArrayList;

/**
 * Created by roy.biber on 14/06/2016.
 */
public class StateListAdapter extends BaseAdapter implements Filterable {

    private final Activity context;
    public ArrayList<StateListObject> stateListObjects;
    CustomFilter filter;
    ArrayList<StateListObject> filterList;
    private String sharedLanguage;

    public StateListAdapter(Activity context, ArrayList<StateListObject> stateListObjects, String sharedLanguage) {

        this.sharedLanguage = sharedLanguage;
        this.context = context;
        this.stateListObjects = stateListObjects;
        this.filterList = stateListObjects;

    }

    @Override
    public int getCount() {
        return stateListObjects.size();
    }

    @Override
    public Object getItem(int position) {
        return stateListObjects.get(position);
    }

    @Override
    public long getItemId(int position) {
        return stateListObjects.indexOf(getItem(position));
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = context.getLayoutInflater();
        context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.custom_list_view, null);
        }

        TextView txtTitle = convertView.findViewById(R.id.bluesnap_customlist_list_view_text);
        ImageView bluesnap_customlist_list_view_icon = convertView.findViewById(R.id.bluesnap_customlist_list_view_icon);

        String stateFullName = stateListObjects.get(position).getStateFullName();
        String stateInitial = stateListObjects.get(position).getStateCode();

        txtTitle.setText(stateFullName);
        if (sharedLanguage.equals(stateListObjects.get(position).getStateFullName())) {
            bluesnap_customlist_list_view_icon.setVisibility(View.VISIBLE);
        } else {
            bluesnap_customlist_list_view_icon.setVisibility(View.INVISIBLE);
        }

        return convertView;

    }

    @Override
    public Filter getFilter() {
        if (filter == null) {
            filter = new CustomFilter();
        }

        return filter;
    }

    class CustomFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            FilterResults results = new FilterResults();

            if (constraint != null && constraint.length() > 0) {
                //CONSTARINT TO UPPER
                constraint = constraint.toString().toUpperCase();

                ArrayList<StateListObject> filters = new ArrayList<>();

                //get specific items
                for (int i = 0; i < filterList.size(); i++) {
                    if (filterList.get(i).getStateFullName().toUpperCase().contains(constraint)) {
                        StateListObject p = new StateListObject(filterList.get(i).getStateFullName(), filterList.get(i).getStateCode());

                        filters.add(p);
                    }
                }

                results.count = filters.size();
                results.values = filters;

            } else {
                results.count = filterList.size();
                results.values = filterList;

            }

            return results;
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {

            stateListObjects = (ArrayList<StateListObject>) results.values;
            notifyDataSetChanged();
        }

    }

}


text:
package com.nepxion.thunder.test.external;

import com.nepxion.thunder.test.core.User;

public interface AutowireService {
    User getUser(String name);
}


text:
.class public Landroid/service/notification/NotificationListenerService$Ranking;
.super Ljava/lang/Object;
.source "NotificationListenerService.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/service/notification/NotificationListenerService;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "Ranking"
.end annotation

# static fields
.field public static final VISIBILITY_NO_OVERRIDE:I = -0x3e8

# instance fields
.field private mChannel:Landroid/app/NotificationChannel;

.field private mImportance:I

.field private mImportanceExplanation:Ljava/lang/CharSequence;

.field private mIsAmbient:Z

.field private mKey:Ljava/lang/String;

.field private mMatchesInterruptionFilter:Z

.field private mOverrideGroupKey:Ljava/lang/String;

.field private mOverridePeople:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Ljava/lang/String;",
            ">;"
        }
    .end annotation
.end field

.field private mRank:I

.field private mShowBadge:Z

.field private mSnoozeCriteria:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Landroid/service/notification/SnoozeCriterion;",
            ">;"
        }
    .end annotation
.end field

.field private mSuppressedVisualEffects:I

.field private mVisibilityOverride:I

.field public semPinned:Z

# direct methods
.method static synthetic -wrap0(Landroid/service/notification/NotificationListenerService$Ranking;Ljava/lang/String;IZIIILjava/lang/CharSequence;Ljava/lang/String;Landroid/app/NotificationChannel;Ljava/util/ArrayList;Ljava/util/ArrayList;ZZ)V
    .locals 0

    invoke-direct/range {p0 .. p13}, Landroid/service/notification/NotificationListenerService$Ranking;->populate(Ljava/lang/String;IZIIILjava/lang/CharSequence;Ljava/lang/String;Landroid/app/NotificationChannel;Ljava/util/ArrayList;Ljava/util/ArrayList;ZZ)V

    return-void
.end method

.method public constructor <init>()V
    .locals 1

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

    const/4 v0, -0x1

    iput v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mRank:I

    return-void
.end method

.method public static importanceToString(I)Ljava/lang/String;
    .locals 2

    sparse-switch p0, :sswitch_data_0

    new-instance v0, Ljava/lang/StringBuilder;

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

    const-string/jumbo v1, "UNKNOWN("

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

    move-result-object v0

    invoke-static {p0}, Ljava/lang/String;->valueOf(I)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

    const-string/jumbo v1, ")"

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

    move-result-object v0

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

    move-result-object v0

    return-object v0

    :sswitch_0
    const-string/jumbo v0, "UNSPECIFIED"

    return-object v0

    :sswitch_1
    const-string/jumbo v0, "NONE"

    return-object v0

    :sswitch_2
    const-string/jumbo v0, "MIN"

    return-object v0

    :sswitch_3
    const-string/jumbo v0, "LOW"

    return-object v0

    :sswitch_4
    const-string/jumbo v0, "DEFAULT"

    return-object v0

    :sswitch_5
    const-string/jumbo v0, "HIGH"

    return-object v0

    nop

    :sswitch_data_0
    .sparse-switch
        -0x3e8 -> :sswitch_0
        0x0 -> :sswitch_1
        0x1 -> :sswitch_2
        0x2 -> :sswitch_3
        0x3 -> :sswitch_4
        0x4 -> :sswitch_5
        0x5 -> :sswitch_5
    .end sparse-switch
.end method

.method private populate(Ljava/lang/String;IZIIILjava/lang/CharSequence;Ljava/lang/String;Landroid/app/NotificationChannel;Ljava/util/ArrayList;Ljava/util/ArrayList;ZZ)V
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/String;",
            "IZIII",
            "Ljava/lang/CharSequence;",
            "Ljava/lang/String;",
            "Landroid/app/NotificationChannel;",
            "Ljava/util/ArrayList",
            "<",
            "Ljava/lang/String;",
            ">;",
            "Ljava/util/ArrayList",
            "<",
            "Landroid/service/notification/SnoozeCriterion;",
            ">;ZZ)V"
        }
    .end annotation

    iput-object p1, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mKey:Ljava/lang/String;

    iput p2, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mRank:I

    const/4 v0, 0x2

    if-ge p6, v0, :cond_0

    const/4 v0, 0x1

    :goto_0
    iput-boolean v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mIsAmbient:Z

    iput-boolean p3, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mMatchesInterruptionFilter:Z

    iput p4, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mVisibilityOverride:I

    iput p5, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mSuppressedVisualEffects:I

    iput p6, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mImportance:I

    iput-object p7, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mImportanceExplanation:Ljava/lang/CharSequence;

    iput-object p8, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mOverrideGroupKey:Ljava/lang/String;

    iput-object p9, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mChannel:Landroid/app/NotificationChannel;

    iput-object p10, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mOverridePeople:Ljava/util/ArrayList;

    iput-object p11, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mSnoozeCriteria:Ljava/util/ArrayList;

    iput-boolean p12, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mShowBadge:Z

    iput-boolean p13, p0, Landroid/service/notification/NotificationListenerService$Ranking;->semPinned:Z

    return-void

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

# virtual methods
.method public canShowBadge()Z
    .locals 1

    iget-boolean v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mShowBadge:Z

    return v0
.end method

.method public getAdditionalPeople()Ljava/util/List;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/List",
            "<",
            "Ljava/lang/String;",
            ">;"
        }
    .end annotation

    iget-object v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mOverridePeople:Ljava/util/ArrayList;

    return-object v0
.end method

.method public getChannel()Landroid/app/NotificationChannel;
    .locals 1

    iget-object v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mChannel:Landroid/app/NotificationChannel;

    return-object v0
.end method

.method public getImportance()I
    .locals 1

    iget v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mImportance:I

    return v0
.end method

.method public getImportanceExplanation()Ljava/lang/CharSequence;
    .locals 1

    iget-object v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mImportanceExplanation:Ljava/lang/CharSequence;

    return-object v0
.end method

.method public getKey()Ljava/lang/String;
    .locals 1

    iget-object v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mKey:Ljava/lang/String;

    return-object v0
.end method

.method public getOverrideGroupKey()Ljava/lang/String;
    .locals 1

    iget-object v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mOverrideGroupKey:Ljava/lang/String;

    return-object v0
.end method

.method public getRank()I
    .locals 1

    iget v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mRank:I

    return v0
.end method

.method public getSnoozeCriteria()Ljava/util/List;
    .locals 1
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()",
            "Ljava/util/List",
            "<",
            "Landroid/service/notification/SnoozeCriterion;",
            ">;"
        }
    .end annotation

    iget-object v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mSnoozeCriteria:Ljava/util/ArrayList;

    return-object v0
.end method

.method public getSuppressedVisualEffects()I
    .locals 1

    iget v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mSuppressedVisualEffects:I

    return v0
.end method

.method public getVisibilityOverride()I
    .locals 1

    iget v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mVisibilityOverride:I

    return v0
.end method

.method public isAmbient()Z
    .locals 1

    iget-boolean v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mIsAmbient:Z

    return v0
.end method

.method public matchesInterruptionFilter()Z
    .locals 1

    iget-boolean v0, p0, Landroid/service/notification/NotificationListenerService$Ranking;->mMatchesInterruptionFilter:Z

    return v0
.end method


text:
using System;
using Qwack.Core.Basic;
using Qwack.Transport.BasicTypes;

namespace Qwack.Core.Curves
{
    public class ConstantPriceCurve : BasicPriceCurve
    {

        public ConstantPriceCurve(double price, DateTime originDate, ICurrencyProvider ccyProvider)
            : base(originDate, new[] { originDate }, new[] { price }, PriceCurveType.Constant, ccyProvider) => Price = price;

        public double Price { get; }
    }
}


text:
package reuse.pipe.router;

import java.io.IOException;
import java.util.List;

import reuse.pipe.api.Converter;
import reuse.pipe.api.Target;

public abstract class AbstractListRouter<T> implements Converter<T,T> {
	List<Target<T>> targets;

	public AbstractListRouter(List<Target<T>> targets) {
		super();
		assert targets != null;
		assert targets.size() > 0;

		this.targets = targets;
	}

	@Override
	public void flush() {
		for (Target<T> target : targets) {
			target.flush();
		}
	}

	@Override
	public void close() throws IOException {
		for (Target<T> target : targets) {
			target.close();
		}
	}

	@Override
	public Target<T> getTarget() {
		throw new UnsupportedOperationException();
	}

	@Override
	public void setTarget(Target<T> target) {
		throw new UnsupportedOperationException();
	}

}


text:
/* { dg-do compile } */
/* { dg-options "-O1 -fdump-tree-dom3" } */

extern void abort (void);
struct rtx_def;
typedef struct rtx_def *rtx;
struct rtvec_def;
typedef struct rtvec_def *rtvec;
union tree_node;
typedef union tree_node *tree;
struct tree_common
{
  int code;
};
union tree_node
{
  struct tree_common common;
};
extern tree current_function_decl;
struct cgraph_rtl_info
{
  _Bool pure_function;
};
struct cgraph_rtl_info *cgraph_rtl_info (tree);
void
mark_constant_function (void)
{
  rtx insn;
  int nonlocal_memory_referenced;

  if (current_function_decl->common.code != 42)
    abort ();

  cgraph_rtl_info (current_function_decl)->pure_function = 1;
}

/* current_function_decl should be loaded once into a temporary
   and the temporary used as the argument to cgraph_rtl_info.
   This if we find current_function_decl used as an argument, then
   we have failed.  */
/* { dg-final { scan-tree-dump-times "\\(current_function_decl\\)" 0 "dom3"} } */
/* { dg-final { cleanup-tree-dump "dom3" } } */


text:
/*
 * File:   AsyncSerial.cpp
 * Author: Terraneo Federico
 * Distributed under the Boost Software License, Version 1.0.
 * Created on September 7, 2009, 10:46 AM
 *
 * v1.02: Fixed a bug in BufferedAsyncSerial: Using the default constructor
 * the callback was not set up and reading didn't work.
 *
 * v1.01: Fixed a bug that did not allow to reopen a closed serial port.
 *
 * v1.00: First release.
 *
 * IMPORTANT:
 * On Mac OS X boost asio's serial ports have bugs, and the usual implementation
 * of this class does not work. So a workaround class was written temporarily,
 * until asio (hopefully) will fix Mac compatibility for serial ports.
 *
 * Please note that unlike said in the documentation on OS X until asio will
 * be fixed serial port *writes* are *not* asynchronous, but at least
 * asynchronous *read* works.
 * In addition the serial port open ignores the following options: parity,
 * character size, flow, stop bits, and defaults to 8N1 format.
 * I know it is bad but at least it's better than nothing.
 *
 */

#include "asyncSerial.h"

#include <string>
#include <algorithm>
#include <iostream>
#include <boost/bind.hpp>

using namespace std;
using namespace boost;

//
//Class AsyncSerial
//

#ifndef __APPLE__

class AsyncSerialImpl: private boost::noncopyable
{
public:
    AsyncSerialImpl(): io(), port(io), backgroundThread(), open(false),
            error(false) {}

    boost::asio::io_service io; ///< Io service object
    boost::asio::serial_port port; ///< Serial port object
    boost::thread backgroundThread; ///< Thread that runs read/write operations
    bool open; ///< True if port open
    bool error; ///< Error flag
    mutable boost::mutex errorMutex; ///< Mutex for access to error

    /// Data are queued here before they go in writeBuffer
    std::vector<char> writeQueue;
    boost::shared_array<char> writeBuffer; ///< Data being written
    size_t writeBufferSize; ///< Size of writeBuffer
    boost::mutex writeQueueMutex; ///< Mutex for access to writeQueue
    char readBuffer[AsyncSerial::readBufferSize]; ///< data being read

    /// Read complete callback
    boost::function<void (const char*, size_t)> callback;
};

AsyncSerial::AsyncSerial(): pimpl(new AsyncSerialImpl)
{

}

AsyncSerial::AsyncSerial(const std::string& devname, unsigned int baud_rate,
        asio::serial_port_base::parity opt_parity,
        asio::serial_port_base::character_size opt_csize,
        asio::serial_port_base::flow_control opt_flow,
        asio::serial_port_base::stop_bits opt_stop)
        : pimpl(new AsyncSerialImpl)
{
    open(devname,baud_rate,opt_parity,opt_csize,opt_flow,opt_stop);
}

void AsyncSerial::open(const std::string& devname, unsigned int baud_rate,
        asio::serial_port_base::parity opt_parity,
        asio::serial_port_base::character_size opt_csize,
        asio::serial_port_base::flow_control opt_flow,
        asio::serial_port_base::stop_bits opt_stop)
{
    if(isOpen()) close();

    setErrorStatus(true);//If an exception is thrown, error_ remains true
    pimpl->port.open(devname);
    pimpl->port.set_option(asio::serial_port_base::baud_rate(baud_rate));
    pimpl->port.set_option(opt_parity);
    pimpl->port.set_option(opt_csize);
    pimpl->port.set_option(opt_flow);
    pimpl->port.set_option(opt_stop);

    //This gives some work to the io_service before it is started
    pimpl->io.post(boost::bind(&AsyncSerial::doRead, this));

    thread t(boost::bind(&asio::io_service::run, &pimpl->io));
    pimpl->backgroundThread.swap(t);
    setErrorStatus(false);//If we get here, no error
    pimpl->open=true; //Port is now open
}

bool AsyncSerial::isOpen() const
{
    return pimpl->open;
}

bool AsyncSerial::errorStatus() const
{
    boost::lock_guard<boost::mutex> l(pimpl->errorMutex);
    return pimpl->error;
}

void AsyncSerial::close()
{
    if(!isOpen()) return;

    pimpl->open=false;
    pimpl->io.post(boost::bind(&AsyncSerial::doClose, this));
    pimpl->backgroundThread.join();
    pimpl->io.reset();
    if(errorStatus())
    {
        throw(boost::system::system_error(boost::system::error_code(),
                "Error while closing the device"));
    }
}

void AsyncSerial::write(const char *data, size_t size)
{
    {
        boost::lock_guard<boost::mutex> l(pimpl->writeQueueMutex);
        pimpl->writeQueue.insert(pimpl->writeQueue.end(),data,data+size);
    }
    pimpl->io.post(boost::bind(&AsyncSerial::doWrite, this));
}

void AsyncSerial::write(const std::vector<char>& data)
{
    {
        boost::lock_guard<boost::mutex> l(pimpl->writeQueueMutex);
        pimpl->writeQueue.insert(pimpl->writeQueue.end(),data.begin(),
                data.end());
    }
    pimpl->io.post(boost::bind(&AsyncSerial::doWrite, this));
}

void AsyncSerial::writeString(const std::string& s)
{
    {
        boost::lock_guard<boost::mutex> l(pimpl->writeQueueMutex);
        pimpl->writeQueue.insert(pimpl->writeQueue.end(),s.begin(),s.end());
    }
    pimpl->io.post(boost::bind(&AsyncSerial::doWrite, this));
}

AsyncSerial::~AsyncSerial()
{
    if(isOpen())
    {
        try {
            close();
        } catch(...)
        {
            //Don't throw from a destructor
        }
    }
}

void AsyncSerial::doRead()
{
    pimpl->port.async_read_some(asio::buffer(pimpl->readBuffer,readBufferSize),
            boost::bind(&AsyncSerial::readEnd,
            this,
            asio::placeholders::error,
            asio::placeholders::bytes_transferred));
}

void AsyncSerial::readEnd(const boost::system::error_code& error,
        size_t bytes_transferred)
{
    if(error)
    {
        #ifdef __APPLE__
        if(error.value()==45)
        {
            //Bug on OS X, it might be necessary to repeat the setup
            //http://osdir.com/ml/lib.boost.asio.user/2008-08/msg00004.html
            doRead();
            return;
        }
        #endif //__APPLE__
        //error can be true even because the serial port was closed.
        //In this case it is not a real error, so ignore
        if(isOpen())
        {
            doClose();
            setErrorStatus(true);
        }
    } else {
        if(pimpl->callback) pimpl->callback(pimpl->readBuffer,
                bytes_transferred);
        doRead();
    }
}

void AsyncSerial::doWrite()
{
    //If a write operation is already in progress, do nothing
    if(pimpl->writeBuffer==0)
    {
        boost::lock_guard<boost::mutex> l(pimpl->writeQueueMutex);
        pimpl->writeBufferSize=pimpl->writeQueue.size();
        pimpl->writeBuffer.reset(new char[pimpl->writeQueue.size()]);
        copy(pimpl->writeQueue.begin(),pimpl->writeQueue.end(),
                pimpl->writeBuffer.get());
        pimpl->writeQueue.clear();
        async_write(pimpl->port,asio::buffer(pimpl->writeBuffer.get(),
                pimpl->writeBufferSize),
                boost::bind(&AsyncSerial::writeEnd, this, asio::placeholders::error));
    }
}

void AsyncSerial::writeEnd(const boost::system::error_code& error)
{
    if(!error)
    {
        boost::lock_guard<boost::mutex> l(pimpl->writeQueueMutex);
        if(pimpl->writeQueue.empty())
        {
            pimpl->writeBuffer.reset();
            pimpl->writeBufferSize=0;

            return;
        }
        pimpl->writeBufferSize=pimpl->writeQueue.size();
        pimpl->writeBuffer.reset(new char[pimpl->writeQueue.size()]);
        copy(pimpl->writeQueue.begin(),pimpl->writeQueue.end(),
                pimpl->writeBuffer.get());
        pimpl->writeQueue.clear();
        async_write(pimpl->port,asio::buffer(pimpl->writeBuffer.get(),
                pimpl->writeBufferSize),
                boost::bind(&AsyncSerial::writeEnd, this, asio::placeholders::error));
    } else {
        setErrorStatus(true);
        doClose();
    }
}

void AsyncSerial::doClose()
{
    boost::system::error_code ec;
    pimpl->port.cancel(ec);
    if(ec) setErrorStatus(true);
    pimpl->port.close(ec);
    if(ec) setErrorStatus(true);
}

void AsyncSerial::setErrorStatus(bool e)
{
    boost::lock_guard<boost::mutex> l(pimpl->errorMutex);
    pimpl->error=e;
}

void AsyncSerial::setReadCallback(const boost::function<void (const char*, size_t)>& callback)
{
    pimpl->callback=callback;
}

void AsyncSerial::clearReadCallback()
{
    pimpl->callback.clear();
}

#else //__APPLE__

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>

class AsyncSerialImpl: private boost::noncopyable
{
public:
    AsyncSerialImpl(): backgroundThread(), open(false), error(false) {}

    boost::thread backgroundThread; ///< Thread that runs read operations
    bool open; ///< True if port open
    bool error; ///< Error flag
    mutable boost::mutex errorMutex; ///< Mutex for access to error

    int fd; ///< File descriptor for serial port

    char readBuffer[AsyncSerial::readBufferSize]; ///< data being read

    /// Read complete callback
    boost::function<void (const char*, size_t)> callback;
};

AsyncSerial::AsyncSerial(): pimpl(new AsyncSerialImpl)
{

}

AsyncSerial::AsyncSerial(const std::string& devname, unsigned int baud_rate,
        asio::serial_port_base::parity opt_parity,
        asio::serial_port_base::character_size opt_csize,
        asio::serial_port_base::flow_control opt_flow,
        asio::serial_port_base::stop_bits opt_stop)
        : pimpl(new AsyncSerialImpl)
{
    open(devname,baud_rate,opt_parity,opt_csize,opt_flow,opt_stop);
}

void AsyncSerial::open(const std::string& devname, unsigned int baud_rate,
        asio::serial_port_base::parity opt_parity,
        asio::serial_port_base::character_size opt_csize,
        asio::serial_port_base::flow_control opt_flow,
        asio::serial_port_base::stop_bits opt_stop)
{
    if(isOpen()) close();

    setErrorStatus(true);//If an exception is thrown, error remains true

    struct termios new_attributes;
    speed_t speed;
    int status;

    // Open port
    pimpl->fd=::open(devname.c_str(), O_RDWR | O_NOCTTY | O_NONBLOCK);
    if (pimpl->fd<0) throw(boost::system::system_error(
            boost::system::error_code(),"Failed to open port"));

    // Set Port parameters.
    status=tcgetattr(pimpl->fd,&new_attributes);
    if(status<0  || !isatty(pimpl->fd))
    {
        ::close(pimpl->fd);
        throw(boost::system::system_error(
                    boost::system::error_code(),"Device is not a tty"));
    }
    new_attributes.c_iflag = IGNBRK;
    new_attributes.c_oflag = 0;
    new_attributes.c_lflag = 0;
    new_attributes.c_cflag = (CS8 | CREAD | CLOCAL);//8 data bit,Enable receiver,Ignore modem
    /* In non canonical mode (Ctrl-C and other disabled, no echo,...) VMIN and VTIME work this way:
    if the function read() has'nt read at least VMIN chars it waits until has read at least VMIN
    chars (even if VTIME timeout expires); once it has read at least vmin chars, if subsequent
    chars do not arrive before VTIME expires, it returns error; if a char arrives, it resets the
    timeout, so the internal timer will again start from zero (for the nex char,if any)*/
    new_attributes.c_cc[VMIN]=1;// Minimum number of characters to read before returning error
    new_attributes.c_cc[VTIME]=1;// Set timeouts in tenths of second

    // Set baud rate
    switch(baud_rate)
    {
        case 50:speed= B50; break;
        case 75:speed= B75; break;
        case 110:speed= B110; break;
        case 134:speed= B134; break;
        case 150:speed= B150; break;
        case 200:speed= B200; break;
        case 300:speed= B300; break;
        case 600:speed= B600; break;
        case 1200:speed= B1200; break;
        case 1800:speed= B1800; break;
        case 2400:speed= B2400; break;
        case 4800:speed= B4800; break;
        case 9600:speed= B9600; break;
        case 19200:speed= B19200; break;
        case 38400:speed= B38400; break;
        case 57600:speed= B57600; break;
        case 115200:speed= B115200; break;
        case 230400:speed= B230400; break;
        default:
        {
            ::close(pimpl->fd);
            throw(boost::system::system_error(
                        boost::system::error_code(),"Unsupported baud rate"));
        }
    }

    cfsetospeed(&new_attributes,speed);
    cfsetispeed(&new_attributes,speed);

    //Make changes effective
    status=tcsetattr(pimpl->fd, TCSANOW, &new_attributes);
    if(status<0)
    {
        ::close(pimpl->fd);
        throw(boost::system::system_error(
                    boost::system::error_code(),"Can't set port attributes"));
    }

    //These 3 lines clear the O_NONBLOCK flag
    status=fcntl(pimpl->fd, F_GETFL, 0);
    if(status!=-1) fcntl(pimpl->fd, F_SETFL, status & ~O_NONBLOCK);

    setErrorStatus(false);//If we get here, no error
    pimpl->open=true; //Port is now open

    thread t(bind(&AsyncSerial::doRead, this));
    pimpl->backgroundThread.swap(t);
}

bool AsyncSerial::isOpen() const
{
    return pimpl->open;
}

bool AsyncSerial::errorStatus() const
{
    boost::lock_guard<boost::mutex> l(pimpl->errorMutex);
    return pimpl->error;
}

void AsyncSerial::close()
{
    if(!isOpen()) return;

    pimpl->open=false;

    ::close(pimpl->fd); //The thread waiting on I/O should return

    pimpl->backgroundThread.join();
    if(errorStatus())
    {
        throw(boost::system::system_error(boost::system::error_code(),
                "Error while closing the device"));
    }
}

void AsyncSerial::write(const char *data, size_t size)
{
    if(::write(pimpl->fd,data,size)!=size) setErrorStatus(true);
}

void AsyncSerial::write(const std::vector<char>& data)
{
    if(::write(pimpl->fd,&data[0],data.size())!=data.size())
        setErrorStatus(true);
}

void AsyncSerial::writeString(const std::string& s)
{
    if(::write(pimpl->fd,&s[0],s.size())!=s.size()) setErrorStatus(true);
}

AsyncSerial::~AsyncSerial()
{
    if(isOpen())
    {
        try {
            close();
        } catch(...)
        {
            //Don't throw from a destructor
        }
    }
}

void AsyncSerial::doRead()
{
    //Read loop in spawned thread
    for(;;)
    {
        int received=::read(pimpl->fd,pimpl->readBuffer,readBufferSize);
        if(received<0)
        {
            if(isOpen()==false) return; //Thread interrupted because port closed
            else {
                setErrorStatus(true);
                continue;
            }
        }
        if(pimpl->callback) pimpl->callback(pimpl->readBuffer, received);
    }
}

void AsyncSerial::readEnd(const boost::system::error_code& error,
        size_t bytes_transferred)
{
    //Not used
}

void AsyncSerial::doWrite()
{
    //Not used
}

void AsyncSerial::writeEnd(const boost::system::error_code& error)
{
    //Not used
}

void AsyncSerial::doClose()
{
    //Not used
}

void AsyncSerial::setErrorStatus(bool e)
{
    boost::lock_guard<boost::mutex> l(pimpl->errorMutex);
    pimpl->error=e;
}

void AsyncSerial::setReadCallback(const boost::function<void (const char*, size_t)>& callback) {
    pimpl->callback=callback;
}

void AsyncSerial::clearReadCallback()
{
    pimpl->callback.clear();
}

#endif //__APPLE__

//
//Class CallbackAsyncSerial
//

CallbackAsyncSerial::CallbackAsyncSerial(): AsyncSerial()
{

}

CallbackAsyncSerial::CallbackAsyncSerial(const std::string& devname,
        unsigned int baud_rate,
        asio::serial_port_base::parity opt_parity,
        asio::serial_port_base::character_size opt_csize,
        asio::serial_port_base::flow_control opt_flow,
        asio::serial_port_base::stop_bits opt_stop)
        :AsyncSerial(devname,baud_rate,opt_parity,opt_csize,opt_flow,opt_stop)
{

}

void CallbackAsyncSerial::setCallback(const boost::function<void (const char*, size_t)>& callback)
{
    setReadCallback(callback);
}

void CallbackAsyncSerial::clearCallback()
{
    clearReadCallback();
}

CallbackAsyncSerial::~CallbackAsyncSerial()
{
    clearReadCallback();
}


text:
#include "usb.h"
#include "samd/usb_samd.h"
#include "samd/usb_samd_internal.h"

#define NVM_USB_PAD_TRANSN_POS  45
#define NVM_USB_PAD_TRANSN_SIZE 5
#define NVM_USB_PAD_TRANSP_POS  50
#define NVM_USB_PAD_TRANSP_SIZE 5
#define NVM_USB_PAD_TRIM_POS  55
#define NVM_USB_PAD_TRIM_SIZE 3

#undef ENABLE

#define USB_GCLK_GEN                    0

void usb_init(){
	uint32_t pad_transn, pad_transp, pad_trim;

	PM->APBBMASK.reg |= PM_APBBMASK_USB;

	GCLK->CLKCTRL.reg = GCLK_CLKCTRL_CLKEN |
			GCLK_CLKCTRL_GEN(USB_GCLK_GEN) |
			GCLK_CLKCTRL_ID(USB_GCLK_ID);

	/* Reset */
	USB->DEVICE.CTRLA.reg = USB_CTRLA_SWRST;
	while (USB->DEVICE.SYNCBUSY.bit.SWRST);

	USB->DEVICE.CTRLA.reg = USB_CTRLA_ENABLE | USB_CTRLA_MODE_DEVICE;
	while (USB->DEVICE.SYNCBUSY.bit.ENABLE);

	/* Load Pad Calibration */
	pad_transn = ( *((uint32_t *)(NVMCTRL_OTP4)
			+ (NVM_USB_PAD_TRANSN_POS / 32))
		>> (NVM_USB_PAD_TRANSN_POS % 32))
		& ((1 << NVM_USB_PAD_TRANSN_SIZE) - 1);

	if (pad_transn == 0x1F) {
		pad_transn = 5;
	}

	pad_transp =( *((uint32_t *)(NVMCTRL_OTP4)
			+ (NVM_USB_PAD_TRANSP_POS / 32))
			>> (NVM_USB_PAD_TRANSP_POS % 32))
			& ((1 << NVM_USB_PAD_TRANSP_SIZE) - 1);

	if (pad_transp == 0x1F) {
		pad_transp = 29;
	}

	pad_trim =( *((uint32_t *)(NVMCTRL_OTP4)
			+ (NVM_USB_PAD_TRIM_POS / 32))
			>> (NVM_USB_PAD_TRIM_POS % 32))
			& ((1 << NVM_USB_PAD_TRIM_SIZE) - 1);

	if (pad_trim == 0x7) {
		pad_trim = 3;
	}

	USB->DEVICE.PADCAL.reg = USB_PADCAL_TRANSN(pad_transn) | USB_PADCAL_TRANSP(pad_transp) | USB_PADCAL_TRIM(pad_trim);

	memset(usb_endpoints, 0, usb_num_endpoints*sizeof(UsbDeviceDescriptor));
	USB->DEVICE.DESCADD.reg = (uint32_t)(&usb_endpoints[0]);
	USB->DEVICE.INTENSET.reg = USB_DEVICE_INTENSET_EORST;

	usb_reset();
}

#define USB_EPTYPE_DISABLED 0
#define USB_EPTYPE_CONTROL 1
#define USB_EPTYPE_ISOCHRONOUS 2
#define USB_EPTYPE_BULK 3
#define USB_EPTYPE_INTERRUPT 4
#define USB_EPTYPE_DUAL_BANK 5

void usb_reset(){
	usb_endpoints[0].DeviceDescBank[0].ADDR.reg = (uint32_t) &ep0_buf_out;
	usb_endpoints[0].DeviceDescBank[0].PCKSIZE.bit.SIZE=USB_EP_size_to_gc(USB_EP0_SIZE);
	usb_endpoints[0].DeviceDescBank[1].ADDR.reg = (uint32_t) &ep0_buf_in;
	usb_endpoints[0].DeviceDescBank[1].PCKSIZE.bit.SIZE=USB_EP_size_to_gc(USB_EP0_SIZE);
	usb_endpoints[0].DeviceDescBank[1].PCKSIZE.bit.AUTO_ZLP=1;
	USB->DEVICE.DeviceEndpoint[0].EPINTENSET.reg = USB_DEVICE_EPINTENSET_RXSTP;
	USB->DEVICE.DeviceEndpoint[0].EPCFG.reg  = USB_DEVICE_EPCFG_EPTYPE0(USB_EPTYPE_CONTROL)
	                                         | USB_DEVICE_EPCFG_EPTYPE1(USB_EPTYPE_CONTROL);
}

void usb_set_address(uint8_t addr) {
	USB->DEVICE.DADD.reg = USB_DEVICE_DADD_ADDEN | addr;
}

inline UsbDeviceDescBank* ep_ram(uint8_t epaddr) {
	return &usb_endpoints[epaddr&0x3F].DeviceDescBank[!!(epaddr&0x80)];
}

inline void usb_enable_ep(uint8_t ep, uint8_t type, usb_size bufsize) {
	if (ep & 0x80) {
		usb_endpoints[ep & 0x3f].DeviceDescBank[1].PCKSIZE.bit.SIZE = USB_EP_size_to_gc(bufsize);
		USB->DEVICE.DeviceEndpoint[ep & 0x3f].EPCFG.bit.EPTYPE1 = type + 1;
		USB->DEVICE.DeviceEndpoint[ep & 0x3f].EPSTATUSCLR.reg = USB_DEVICE_EPSTATUS_BK1RDY
		                                                      | USB_DEVICE_EPSTATUS_STALLRQ(0x2)
		                                                      | USB_DEVICE_EPSTATUS_DTGLIN;
	} else {
		usb_endpoints[ep & 0x3f].DeviceDescBank[0].PCKSIZE.bit.SIZE = USB_EP_size_to_gc(bufsize);
		USB->DEVICE.DeviceEndpoint[ep & 0x3f].EPCFG.bit.EPTYPE0 = type + 1;
		USB->DEVICE.DeviceEndpoint[ep & 0x3f].EPSTATUSSET.reg = USB_DEVICE_EPSTATUS_BK0RDY;
		USB->DEVICE.DeviceEndpoint[ep & 0x3f].EPSTATUSCLR.reg = USB_DEVICE_EPSTATUS_STALLRQ(0x1)
		                                                      | USB_DEVICE_EPSTATUS_DTGLOUT;
	}
}

inline void usb_disable_ep(uint8_t ep) {
	if (ep & 0x80) {
		USB->DEVICE.DeviceEndpoint[ep & 0x3f].EPSTATUSCLR.reg = USB_DEVICE_EPSTATUS_BK1RDY;
		USB->DEVICE.DeviceEndpoint[ep & 0x3f].EPCFG.bit.EPTYPE1 = USB_EPTYPE_DISABLED;
	} else {
		USB->DEVICE.DeviceEndpoint[ep & 0x3f].EPSTATUSSET.reg = USB_DEVICE_EPSTATUS_BK0RDY;
		USB->DEVICE.DeviceEndpoint[ep & 0x3f].EPCFG.bit.EPTYPE0 = USB_EPTYPE_DISABLED;
	}
}

inline void usb_reset_ep(uint8_t ep){
	if (ep & 0x80) {
		USB->DEVICE.DeviceEndpoint[ep & 0x3f].EPSTATUSCLR.reg = USB_DEVICE_EPSTATUS_BK1RDY;
	} else {
		USB->DEVICE.DeviceEndpoint[ep & 0x3f].EPSTATUSSET.reg = USB_DEVICE_EPSTATUS_BK0RDY;
	}
}

inline usb_bank usb_ep_start_out(uint8_t ep, uint8_t* data, usb_size len) {
	usb_endpoints[ep].DeviceDescBank[0].PCKSIZE.bit.MULTI_PACKET_SIZE = len;
	usb_endpoints[ep].DeviceDescBank[0].PCKSIZE.bit.BYTE_COUNT = 0;
	usb_endpoints[ep].DeviceDescBank[0].ADDR.reg = (uint32_t) data;
	USB->DEVICE.DeviceEndpoint[ep].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0 | USB_DEVICE_EPINTFLAG_TRFAIL0;
	USB->DEVICE.DeviceEndpoint[ep].EPINTENSET.reg = USB_DEVICE_EPINTENSET_TRCPT0;
	USB->DEVICE.DeviceEndpoint[ep].EPSTATUSCLR.reg = USB_DEVICE_EPSTATUS_BK0RDY;
	return 0;
}

inline usb_bank usb_ep_start_in(uint8_t ep, const uint8_t* data, usb_size size, bool zlp) {
	ep &= 0x3f;
	usb_endpoints[ep].DeviceDescBank[1].PCKSIZE.bit.AUTO_ZLP = zlp;
	usb_endpoints[ep].DeviceDescBank[1].PCKSIZE.bit.MULTI_PACKET_SIZE = 0;
	usb_endpoints[ep].DeviceDescBank[1].PCKSIZE.bit.BYTE_COUNT = size;
	usb_endpoints[ep].DeviceDescBank[1].ADDR.reg = (uint32_t) data;
	USB->DEVICE.DeviceEndpoint[ep].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1 | USB_DEVICE_EPINTFLAG_TRFAIL1;
	USB->DEVICE.DeviceEndpoint[ep].EPINTENSET.reg = USB_DEVICE_EPINTENSET_TRCPT1;
	USB->DEVICE.DeviceEndpoint[ep].EPSTATUSSET.reg = USB_DEVICE_EPSTATUS_BK1RDY;
	return 0;
}

inline bool usb_ep_empty(uint8_t ep) {
	if (ep & 0x80) {
		return !(USB->DEVICE.DeviceEndpoint[ep & 0x3F].EPSTATUS.bit.BK1RDY || usb_ep_pending(ep));
	} else {
		return !(USB->DEVICE.DeviceEndpoint[ep & 0x3F].EPSTATUS.bit.BK0RDY || usb_ep_pending(ep));
	}
}

inline bool usb_ep_ready(uint8_t ep) {
	return usb_ep_empty(ep);
}

inline bool usb_ep_pending(uint8_t ep) {
	if (ep & 0x80) {
		return USB->DEVICE.DeviceEndpoint[ep & 0x3F].EPINTFLAG.bit.TRCPT1;
	} else {
		return USB->DEVICE.DeviceEndpoint[ep & 0x3F].EPINTFLAG.bit.TRCPT0;
	}
}

inline void usb_ep_handled(uint8_t ep) {
	if (ep & 0x80) {
		USB->DEVICE.DeviceEndpoint[ep & 0x3F].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1;
	} else {
		USB->DEVICE.DeviceEndpoint[ep & 0x3F].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT0;
	}
}

inline usb_size usb_ep_out_length(uint8_t ep){
	return usb_endpoints[ep].DeviceDescBank[0].PCKSIZE.bit.BYTE_COUNT;
}

inline void usb_detach(void) {
	USB->DEVICE.CTRLB.bit.DETACH = 1;
	NVIC_DisableIRQ(USB_IRQn);
}

inline void usb_attach(void) {
	NVIC_EnableIRQ(USB_IRQn);
	USB->DEVICE.CTRLB.bit.DETACH = 0;
}

/// Enable the OUT stage on the default control pipe.
inline void usb_ep0_out(void) {
	usb_ep_start_out(0x00, ep0_buf_out, USB_EP0_SIZE);
}

inline void usb_ep0_in(uint8_t size){
	usb_ep_start_in(0x80, ep0_buf_in, size, true);
}

inline void usb_ep0_stall(void) {
	USB->DEVICE.DeviceEndpoint[0].EPSTATUSSET.reg = USB_DEVICE_EPSTATUS_STALLRQ(0x3);
}

void usb_set_speed(USB_Speed speed) {
	if (USB_SPEED_FULL == speed) {
		USB->DEVICE.CTRLB.bit.SPDCONF = USB_DEVICE_CTRLB_SPDCONF_0_Val;
	} else if(USB_SPEED_LOW == speed) {
		USB->DEVICE.CTRLB.bit.SPDCONF = USB_DEVICE_CTRLB_SPDCONF_1_Val;
	}
}
USB_Speed usb_get_speed() {
	if (USB->DEVICE.STATUS.bit.SPEED == 0) {
		return USB_SPEED_LOW;
	} else {
		return USB_SPEED_FULL;
	}
}

void USB_Handler() {
	uint32_t summary = USB->DEVICE.EPINTSMRY.reg;
	uint32_t status = USB->DEVICE.INTFLAG.reg;

	if (status & USB_DEVICE_INTFLAG_EORST) {
		USB->DEVICE.INTFLAG.reg = USB_DEVICE_INTFLAG_EORST;
		usb_reset();
		usb_cb_reset();
		return;
	}

	if (summary & (1<<0)) {
		uint32_t flags = USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg;
		USB->DEVICE.DeviceEndpoint[0].EPINTFLAG.reg = USB_DEVICE_EPINTFLAG_TRCPT1 | USB_DEVICE_EPINTFLAG_TRCPT0 | USB_DEVICE_EPINTFLAG_RXSTP;
		if (flags & USB_DEVICE_EPINTFLAG_RXSTP) {
			memcpy(&usb_setup, ep0_buf_out, sizeof(usb_setup));
			usb_handle_setup();
		}
		if (flags & USB_DEVICE_EPINTFLAG_TRCPT0) {
			usb_handle_control_out_complete();
		}
		if (flags & USB_DEVICE_EPINTFLAG_TRCPT1) {
			usb_handle_control_in_complete();
		}
	}

	for (int i=1; i<usb_num_endpoints; i++) {
		if (summary & 1<<i) {
			uint32_t flags = USB->DEVICE.DeviceEndpoint[i].EPINTFLAG.reg;
			USB->DEVICE.DeviceEndpoint[i].EPINTENCLR.reg = flags;
		}
	}

	usb_cb_completion();
}

void* samd_serial_number_string_descriptor() {
	char buf[27];

	const unsigned char* id = (unsigned char*) 0x0080A00C;
	for (int i=0; i<26; i++) {
		unsigned idx = (i*5)/8;
		unsigned pos = (i*5)%8;
		unsigned val = ((id[idx] >> pos) | (id[idx+1] << (8-pos))) & ((1<<5)-1);
		buf[i] = "0123456789ABCDFGHJKLMNPQRSTVWXYZ"[val];
	}
	buf[26] = 0;
	return usb_string_to_descriptor(buf);
}


text:
package org.batfish.vendor.a10.representation;

import javax.annotation.Nonnull;
import org.batfish.datamodel.Prefix;

/** An access-list address, representing a specific prefix. */
public class AccessListAddressPrefix implements AccessListAddress {
  @Nonnull
  public Prefix getPrefix() {
    return _prefix;
  }

  public AccessListAddressPrefix(Prefix prefix) {
    _prefix = prefix;
  }

  @Nonnull private final Prefix _prefix;

  @Override
  public <T> T accept(AccessListAddressVisitor<T> visitor) {
    return visitor.visitPrefix(this);
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IDT.TaskActions
{
    public interface IInterval
    {
        TimeSpan Calculate(int count);
    }
}


text:
SELECT `_class`, `availablePhysicalMemory`, `availableSwapSpace`, `totalPhysicalMemory`, `totalSwapSpace` FROM `SwapSpaceMonitorMemoryUsage2` WHERE 1;

--
-- INSERT template for table `SwapSpaceMonitorMemoryUsage2`
--
INSERT INTO `SwapSpaceMonitorMemoryUsage2`(`_class`, `availablePhysicalMemory`, `availableSwapSpace`, `totalPhysicalMemory`, `totalSwapSpace`) VALUES (?, ?, ?, ?, ?);

--
-- UPDATE template for table `SwapSpaceMonitorMemoryUsage2`
--
UPDATE `SwapSpaceMonitorMemoryUsage2` SET `_class` = ?, `availablePhysicalMemory` = ?, `availableSwapSpace` = ?, `totalPhysicalMemory` = ?, `totalSwapSpace` = ? WHERE 1;

--
-- DELETE template for table `SwapSpaceMonitorMemoryUsage2`
--
DELETE FROM `SwapSpaceMonitorMemoryUsage2` WHERE 0;


text:
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Client extends Remote {
  public void alert(String msg) throws RemoteException;
}


text:
package aws

import (
	"fmt"
	"testing"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/service/ec2"

	"github.com/hashicorp/terraform/helper/resource"
	"github.com/hashicorp/terraform/terraform"
)

func TestAccAWSCustomerGateway_basic(t *testing.T) {
	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckCustomerGatewayDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccCustomerGatewayConfig,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckCustomerGateway(
						"aws_customer_gateway.foo",
					),
				),
			},
			resource.TestStep{
				Config: testAccCustomerGatewayConfigUpdateTags,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckCustomerGateway(
						"aws_customer_gateway.foo",
					),
				),
			},
			resource.TestStep{
				Config: testAccCustomerGatewayConfigForceReplace,
				Check: resource.ComposeTestCheckFunc(
					testAccCheckCustomerGateway(
						"aws_customer_gateway.foo",
					),
				),
			},
		},
	})
}

func testAccCheckCustomerGatewayDestroy(s *terraform.State) error {
	conn := testAccProvider.Meta().(*AWSClient).ec2conn

	for _, rs := range s.RootModule().Resources {
		if rs.Type != "aws_customer_gatewah" {
			continue
		}

		gatewayFilter := &ec2.Filter{
			Name:   aws.String("customer-gateway-id"),
			Values: []*string{aws.String(rs.Primary.ID)},
		}

		resp, err := conn.DescribeCustomerGateways(&ec2.DescribeCustomerGatewaysInput{
			Filters: []*ec2.Filter{gatewayFilter},
		})

		if ae, ok := err.(awserr.Error); ok && ae.Code() == "InvalidCustomerGatewayID.NotFound" {
			continue
		}

		if err == nil {
			if len(resp.CustomerGateways) > 0 {
				return fmt.Errorf("Customer gateway still exists: %v", resp.CustomerGateways)
			}
		}

		return err
	}

	return nil
}

func testAccCheckCustomerGateway(gatewayResource string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[gatewayResource]
		if !ok {
			return fmt.Errorf("Not found: %s", gatewayResource)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		gateway, ok := s.RootModule().Resources[gatewayResource]
		if !ok {
			return fmt.Errorf("Not found: %s", gatewayResource)
		}

		ec2conn := testAccProvider.Meta().(*AWSClient).ec2conn
		gatewayFilter := &ec2.Filter{
			Name:   aws.String("customer-gateway-id"),
			Values: []*string{aws.String(gateway.Primary.ID)},
		}

		_, err := ec2conn.DescribeCustomerGateways(&ec2.DescribeCustomerGatewaysInput{
			Filters: []*ec2.Filter{gatewayFilter},
		})

		if err != nil {
			return err
		}

		return nil
	}
}

const testAccCustomerGatewayConfig = `
resource "aws_customer_gateway" "foo" {
	bgp_asn = 60000
	ip_address = "172.0.0.1"
	type = "ipsec.1"
	tags {
		Name = "foo-gateway"
	}
}
`

// Add the Another: "tag" tag.
const testAccCustomerGatewayConfigUpdateTags = `
resource "aws_customer_gateway" "foo" {
	bgp_asn = 60000
	ip_address = "172.0.0.1"
	type = "ipsec.1"
	tags {
		Name = "foo-gateway"
		Another = "tag"
	}
}
`

// Change the ip_address.
const testAccCustomerGatewayConfigForceReplace = `
resource "aws_customer_gateway" "foo" {
	bgp_asn = 60000
	ip_address = "172.10.10.1"
	type = "ipsec.1"
	tags {
		Name = "foo-gateway"
		Another = "tag"
	}
}
`


text:
from siconos.mechanics.collision.tools import Contactor
from siconos.io.mechanics_io import Hdf5
import siconos.io.mechanics_io
import siconos.numerics as Numerics
from siconos.mechanics.collision.convexhull import ConvexHull
import numpy as np

# Shape parameters of a single link
num_parts = 8
radius = 0.1
width = 0.03
girth = 0.03
length = 0.2

# Chain and ball parameters
num_links = 5
ball_radius = 0.5

# Creation of the hdf5 file for input/output
with Hdf5() as io:

    # Definition of a half-torus as a composition of convex shapes.
    all_pts = []
    s = np.pi/(num_parts-1)/2
    center = radius-girth
    for i,d in enumerate([-1,1]):
        for j,r in enumerate(np.linspace(0, np.pi, num_parts)):
            pts = np.array([
                [ width, radius*np.sin(r-s)*d+d*length, radius*np.cos(r-s)*d],
                [-width, radius*np.sin(r-s)*d+d*length, radius*np.cos(r-s)*d],
                [ width, radius*np.sin(r+s)*d+d*length, radius*np.cos(r+s)*d],
                [-width, radius*np.sin(r+s)*d+d*length, radius*np.cos(r+s)*d],
                [ width, center*np.sin(r-s)*d+d*length, center*np.cos(r-s)*d],
                [-width, center*np.sin(r-s)*d+d*length, center*np.cos(r-s)*d],
                [ width, center*np.sin(r+s)*d+d*length, center*np.cos(r+s)*d],
                [-width, center*np.sin(r+s)*d+d*length, center*np.cos(r+s)*d],
            ])
            all_pts += list(pts)
            io.addConvexShape('Chainlink%02d'%(i*num_parts+j), pts)

    # connector: using the 16 points closest to center, create two
    # hulls for upper and lower part
    all_pts = np.array(all_pts)
    connect = all_pts[np.argsort((all_pts[:,1]-0)**2)[:16]]
    io.addConvexShape('Chainlink%02d'%(num_parts*2+0), connect[connect[:,2] > 0])
    io.addConvexShape('Chainlink%02d'%(num_parts*2+1), connect[connect[:,2] < 0])

    # computation of inertia and volume of all points
    ch = ConvexHull(all_pts)
    link_inertia, volume = ch.inertia(ch.centroid())

    # computation of inertia and volume of all points including
    # extrema of the ball
    ball_pos = np.array([0, ball_radius+length*2/3, 0])
    ch = ConvexHull(np.vstack((all_pts,
                               [ball_pos + [0,ball_radius,0],
                                ball_pos + [0,0, ball_radius],
                                ball_pos + [0,0,-ball_radius],
                                ball_pos + [ ball_radius,0,0],
                                ball_pos + [-ball_radius,0,0]])))
    ball_inertia, volume = ch.inertia(ch.centroid())

    # ball at the end of the chain
    io.addPrimitiveShape('Ball', 'Sphere', [ball_radius])

    chainlink = [Contactor('Chainlink%02d'%i) for i in range(num_parts*2+2)]
    ball = [Contactor('Ball', relative_translation=ball_pos)]
    mass = 0.1
    initvel = 0.0
    inertia = link_inertia
    for i in range(num_links):
        io.addObject('link%02d'%(i*2+0), chainlink,
                     translation=[0, 0, 10+(i*2+0)*length*2],
                     orientation=[(1, 0, 0), np.pi/2],
                     velocity=[0, 0, 0, 0, 0, 0],
                     mass=mass*(i>0), inertia=inertia)
        # Last link has the ball
        if (i+1)==num_links:
            # Ball is 10x heavier, and give slide sideways initial
            # velocity to cause collapse of the chain.
            chainlink += ball
            mass = 1
            initvel = 0.1
            inertia = ball_inertia
        io.addObject('link%02d'%(i*2+1), chainlink,
                     translation=[0, 0, 10+(i*2+1)*length*2],
                     orientation=[(1, 1, 1), np.pi*2/3],
                     velocity=[initvel, 0, 0, 0, 0, 0],
                     mass=mass, inertia=inertia)

    # Definition of the ground shape
    io.addPrimitiveShape('Ground', 'Box', (10, 10, 1))

    # the ground object made with the ground shape. As the mass is
    # not given, it is a static object only involved in contact
    # detection.
    io.addObject('ground', [Contactor('Ground')],
                 translation=[0, 0, 0])

    # Definition of a non smooth law. As no group ids are specified it
    # is between contactors of group id 0.
    io.addNewtonImpactFrictionNSL('contact', mu=0.03, e=0.0)

# Run the simulation from the inputs previously defined and add
# results to the hdf5 file. The visualisation of the output may be done
# with the vview command.
with Hdf5(mode='r+') as io:

    io.run(with_timer=False,
           t0=0,
           T=20,
           h=0.001,
           theta=0.50001,
           Newton_max_iter=1,
           set_external_forces=None,
           solver=Numerics.SICONOS_FRICTION_3D_NSGS,
           itermax=10000,
           tolerance=1e-8,
           numerics_verbose=False,
           output_frequency=None)


text:
<!DOCTYPE html>
<body>
<script src="../resources/js-test.js"></script>
<script>
debug("This test checks that -internal-* properties are not exposed to JS.")
debug("");
debug("");

// This contains the properties along with an accepted value to ensure that we can't
// set it from JavaScript.
var internalProperties = { "-internal-marquee-direction": "alternate" };
for (var property in internalProperties) {
    debug("Testing " + property);
    element = document.createElement("foo");
    document.body.appendChild(element);
    shouldBeNull("window.getComputedStyle(element).getPropertyValue(property)")
    shouldBeUndefined("element.style[property]")

    debug("Value after setting " + property + " to " + internalProperties[property]);
    element.style.setProperty(property, internalProperties[property]);
    shouldBeUndefined("element.style[property]")

    document.body.removeChild(element);
    debug("");
}
</script>
</body>


text:
/*****************************************************************************/
/*                                    XDMF                                   */
/*                       eXtensible Data Model and Format                    */
/*                                                                           */
/*  Id : XdmfHeavyDataDescription.hpp                                        */
/*                                                                           */
/*  Author:                                                                  */
/*     Andrew Burns                                                          */
/*     andrew.j.burns2@us.army.mil                                           */
/*     US Army Research Laboratory                                           */
/*     Aberdeen Proving Ground, MD                                           */
/*                                                                           */
/*     Copyright @ 2013 US Army Research Laboratory                          */
/*     All Rights Reserved                                                   */
/*     See Copyright.txt for details                                         */
/*                                                                           */
/*     This software is distributed WITHOUT ANY WARRANTY; without            */
/*     even the implied warranty of MERCHANTABILITY or FITNESS               */
/*     FOR A PARTICULAR PURPOSE.  See the above copyright notice             */
/*     for more information.                                                 */
/*                                                                           */
/*****************************************************************************/
#ifndef XDMFHEAVYDATADESCRIPTION_HPP_
#define XDMFHEAVYDATADESCRIPTION_HPP_

// C Compatible Includes
#include "XdmfCore.hpp"
#include "XdmfItem.hpp"

#ifdef __cplusplus

/**
 * @brief Holds information about a dsm buffer so that a process can connect.
 *
 * XdmfDescription stores the information required to process
 * to a data format
 */
class XDMFCORE_EXPORT XdmfHeavyDataDescription : public XdmfItem {

public:

  /**
   *
   */
  static shared_ptr<XdmfHeavyDataDescription> New();

  virtual ~XdmfHeavyDataDescription();

  LOKI_DEFINE_VISITABLE(XdmfHeavyDataDescription, XdmfItem)
  static const std::string ItemTag;

  std::map<std::string, std::string> getItemProperties() const;

  virtual std::string getItemTag() const;

  std::string getPortDescription() const;

  using XdmfItem::insert;

  void setPortDescription(std::string portDesc);

  virtual void traverse(const shared_ptr<XdmfBaseVisitor> visitor);

  XdmfHeavyDataDescription(XdmfHeavyDataDescription &);

protected:

  XdmfHeavyDataDescription();

  virtual void
  populateItem(const std::map<std::string, std::string> & itemProperties,
               const std::vector<shared_ptr<XdmfItem> > & childItems,
               const XdmfCoreReader * const reader);

private:

  XdmfHeavyDataDescription(const XdmfHeavyDataDescription &);  // Not implemented.
  void operator=(const XdmfHeavyDataDescription &);  // Not implemented.

  std::string mPortDescription;
};

#endif

#ifdef __cplusplus
extern "C" {
#endif

// C wrappers go here

struct XDMFHEAVYDATADESCRIPTION; // Simply as a typedef to ensure correct typing
typedef struct XDMFHEAVYDATADESCRIPTION XDMFHEAVYDATADESCRIPTION;

XDMFCORE_EXPORT XDMFHEAVYDATADESCRIPTION * XdmfHeavyDataDescriptionNew();

// C Wrappers for parent classes are generated by macros

XDMF_ITEM_C_CHILD_DECLARE(XdmfHeavyDataDescription, XDMFHEAVYDATADESCRIPTION, XDMFCORE)

#ifdef __cplusplus
}
#endif

#endif /* XDMFHeavyDataDESCRIPTION_HPP_ */


text:
\documentclass{../lib}
\begin{document}

\begin{ledCmnt}
Use keyword *ledGame* to translate LED into Easel-ready SequenceL:
\end{ledCmnt}

\begin{ledDef}
ledGame
\end{ledDef}

\begin{ledDef}
\funDefNoWhere{initialState}{0}
\end{ledDef}

\begin{ledDef}
\funDefNoWhere{newState}{\plusOp{currentState}{1}}
\end{ledDef}

\begin{ledCmnt}
Display number in *currentState*:
\end{ledCmnt}

\begin{ledDef}
\funDefNoWhere{images}{\setNonempty{text \parentheses{strgToVal \parentheses{prettyPrint \parentheses{currentState}}, point \parentheses{500, 400}, 100, color \parentheses{0, 0, 255}}}}
\end{ledDef}

\begin{ledCmnt}
test:
\begin{verbatim}
cmd:>pp(initialState_)
"0"
\end{verbatim}
\end{ledCmnt}

\end{document}


text:
using System;
using System.Threading;
using System.Threading.Tasks;

namespace DeviceHive.Client
{
    internal class AsyncLock
    {
        private readonly AsyncSemaphore m_semaphore;
        private readonly Task<Releaser> m_releaser;

        #region Constructor

        public AsyncLock()
        {
            m_semaphore = new AsyncSemaphore(1);
            m_releaser = Task.FromResult(new Releaser(this));
        }
        #endregion

        #region Public Methods

        public Task<Releaser> LockAsync()
        {
            var wait = m_semaphore.WaitAsync();
            return wait.IsCompleted ?
                m_releaser :
                wait.ContinueWith((_, state) => new Releaser((AsyncLock)state),
                    this, CancellationToken.None,
                    TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
        }
        #endregion

        #region Releaser struct

        public struct Releaser : IDisposable
        {
            private readonly AsyncLock m_toRelease;

            internal Releaser(AsyncLock toRelease)
            {
                m_toRelease = toRelease;
            }

            public void Dispose()
            {
                if (m_toRelease != null)
                    m_toRelease.m_semaphore.Release();
            }
        }
        #endregion
    }
}


text:
package com.microsoftopentechnologies.intellij.helpers.activityConfiguration.azureCustomWizardParameter;

import com.android.tools.idea.templates.Parameter;
import com.android.tools.idea.wizard.ScopedDataBinder;
import com.android.tools.idea.wizard.WizardParameterFactory;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.text.Document;

public class AzureWizardParameterFactory implements WizardParameterFactory {

    @Override
    public String[] getSupportedTypes() {
        return new String[] { "azureCustomParameter" };
    }

    @Override
    public JComponent createComponent(String s, Parameter parameter) {
        return new AzureParameterPane();
    }

    @Override
    public ScopedDataBinder.ComponentBinding<String, JComponent> createBinding(JComponent jComponent, Parameter parameter) {
        return new ScopedDataBinder.ComponentBinding<String, JComponent>() {
            @Nullable
            @Override
            public String getValue(JComponent component) {
                return ((AzureParameterPane) component).getValue();
            }

            @Override
            public void setValue(@Nullable String newValue, JComponent component) {
                ((AzureParameterPane) component).setValue(newValue);
            }

            @Nullable
            @Override
            public Document getDocument(JComponent component) {
                return ((AzureParameterPane) component).getDocument();
            }
        };
    }

}